Build an XML string that contains some randomly positioned goal items
492718
def getItemXML():
    ''' '''
    xml=""
    for item in range(NUM_GOALS):
        x = str(random.randint(old_div(-ARENA_WIDTH,2),old_div(ARENA_WIDTH,2)))
        z = str(random.randint(old_div(-ARENA_BREADTH,2),old_div(ARENA_BREADTH,2)))
        xml += '''<DrawItem x="''' + x + '''" y="210" z="''' + z + '''" type="''' + GOAL_TYPE + '''"/>'''
    return xml
1255045
protected function buildXml()
    {
        if (empty($_POST['CKFinderCommand']) || $_POST['CKFinderCommand'] != 'true') {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
        }

        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
        }

        $oCookiesNode = new Ckfinder_Connector_Utils_XmlNode("Cookies");
        $this->_connectorNode->addChild($oCookiesNode);
        $i = 0;
        foreach ($_COOKIE as $name => $value) {
            if (!is_array($value) && strpos($name, "CKFinder_") !== 0) {
                $oCookieNode[$i] = new Ckfinder_Connector_Utils_XmlNode("Cookie");
                $oCookiesNode->addChild($oCookieNode[$i]);
                $oCookieNode[$i]->addAttribute("name", $name);
                $oCookieNode[$i]->addAttribute("value", $value);
                $i++;
            }
        }
    }
1323181
function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
    var valueDim = opt.valueDim;
    var symbolBoundingData = itemModel.get('symbolBoundingData');
    var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
    var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
    var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
    var boundingLength;

    if (zrUtil.isArray(symbolBoundingData)) {
        var symbolBoundingExtent = [
            convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
            convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
        ];
        symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
        boundingLength = symbolBoundingExtent[pxSignIdx];
    }
    else if (symbolBoundingData != null) {
        boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
    }
    else if (symbolRepeat) {
        boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
    }
    else {
        boundingLength = layout[valueDim.wh];
    }

    output.boundingLength = boundingLength;

    if (symbolRepeat) {
        output.repeatCutLength = layout[valueDim.wh];
    }

    output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
}
55650
function xmlText(node, opt_cdata) {
  var buf = [];
  xmlTextR(node, buf, opt_cdata);
  return buf.join('');
}
867045
def generate(basename, xml):
    ''''''

    if basename.endswith('.js'):
        filename = basename
    else:
        filename = basename + '.js'

    msgs = []
    enums = []
    filelist = []
    for x in xml:
        msgs.extend(x.message)
        enums.extend(x.enum)
        filelist.append(os.path.basename(x.filename))

    for m in msgs:
        if xml[0].little_endian:
            m.fmtstr = '<'
        else:
            m.fmtstr = '>'
        for f in m.ordered_fields:
            m.fmtstr += mavfmt(f)
        m.order_map = [ 0 ] * len(m.fieldnames)
        for i in range(0, len(m.fieldnames)):
            m.order_map[i] = m.ordered_fieldnames.index(m.fieldnames[i])

    print("Generating %s" % filename)
    outf = open(filename, "w")
    generate_preamble(outf, msgs, filelist, xml[0])
    generate_enums(outf, enums)
    generate_message_ids(outf, msgs)
    generate_classes(outf, msgs)
    generate_mavlink_class(outf, msgs, xml[0])
    generate_footer(outf)
    outf.close()
    print("Generated %s OK" % filename)
254020
def fromXMLname(string):
    """"""

    retval = sub(r'_xFFFF_','', string )

    def fun( matchobj ):
        return _fromUnicodeHex( matchobj.group(0) )

    retval = sub(r'_x[0-9A-Za-z]+_', fun, retval )
        
    return retval
765965
function buildSpriteString(icons) {
  const symbols = Object.keys(icons)
    .map(icon => toSvgSymbol(icon, icons[icon]))
    .join('');

  return `<svg xmlns="${DEFAULT_ATTRS.xmlns}"><defs>${symbols}</defs></svg>`;
}
98993
def _construct(self, strings_collection):
        
        
        # 0. Add a unique character to each string in the collection,
        #    to preserve simplicity while building the tree
        strings_collection = utils.make_unique_endings(strings_collection)
        
        root = ast.AnnotatedSuffixTree.Node()
        root.strings_collection = strings_collection
        
        # For each string in the collection...
        for string_ind in xrange(len(strings_collection)):
            string = strings_collection[string_ind]
            # For each suffix of that string...
            # (do not handle unique last characters as suffixes)
            for suffix_start in xrange(len(string)-1):
                suffix = string[suffix_start:]
                # ... first try to find maximal matching path
                node = root
                child_node = node.chose_arc(suffix)
                while child_node:
                    (str_ind, substr_start, substr_end) = child_node.arc()
                    match = utils.match_strings(
                                suffix, strings_collection[str_ind][substr_start:substr_end])
                    if match == substr_end-substr_start:
                        # matched the arc, proceed with child node
                        suffix = suffix[match:]
                        suffix_start += match
                        node = child_node
                        node.weight += 1
                        child_node = node.chose_arc(suffix)
                    else:
                        # ... then, where the matching path ends;
                        # create new inner node
                        # (that's the only possible alternative
                        #  since we have unique string endings)
                        node.remove_child(child_node)
                        new_node = node.add_new_child(string_ind, suffix_start,
                                                      suffix_start+match)
                        new_leaf = new_node.add_new_child(string_ind, suffix_start+match,
                                                          len(string))
                        (osi, oss, ose) = child_node._arc
                        child_node._arc = (osi, oss+match, ose)
                        new_node.add_child(child_node)
                        new_leaf.weight = 1
                        new_node.weight = 1 + child_node.weight
                        suffix = ''
                        break
                        
                # ... or create new leaf if there was no appropriate arc to proceed
                if suffix:
                    new_leaf = node.add_new_child(string_ind, suffix_start, len(string))
                    new_leaf.weight = 1
                    
        # Root will also be annotated by the weight of its children,
        # to preserve simplicity while calculating string matching
        for k in root.children:
            root.weight += root.children[k].weight
        
        return root
95976
function makePossibleRangesHTML(source, tokens, offset) {
		offset = offset || 0;
		var result = [];
		var attrStart = -1, attrName = '', attrValue = '', attrValueRange, tagName;
		tokens.forEach(function(tok) {
			switch (tok.type) {
				case 'tag':
					tagName = source.substring(tok.start, tok.end);
					if (/^<[\w\:\-]/.test(tagName)) {
						// add tag name
						result.push(range({
							start: tok.start + 1, 
							end: tok.end
						}));
					}
					break;
				case 'attribute':
					attrStart = tok.start;
					attrName = source.substring(tok.start, tok.end);
					break;
					
				case 'string':
					// attribute value
					// push full attribute first
					result.push(range(attrStart, tok.end - attrStart));
					
					attrValueRange = range(tok);
					attrValue = attrValueRange.substring(source);
					
					// is this a quoted attribute?
					if (isQuote(attrValue.charAt(0)))
						attrValueRange.start++;
					
					if (isQuote(attrValue.charAt(attrValue.length - 1)))
						attrValueRange.end--;
					
					result.push(attrValueRange);
					
					if (attrName == 'class') {
						result = result.concat(classNameRanges(attrValueRange.substring(source), attrValueRange.start));
					}
					
					break;
			}
		});
		
		// offset ranges
		result = result.filter(function(item) {
			if (item.length()) {
				item.shift(offset);
				return true;
			}
		});

		// remove duplicates
		return utils.unique(result, function(item) {
			return item.toString();
		});
	}
224564
function prettifyXml(xmlInput, options = {}) {
  const {
    indent: indentOption = 2,
    newline: newlineOption = EOL,
  } = options
  const indentString = stringTimesN(indentOption, ' ')

  let formatted = ''
  const regex = /(>)(<)(\/*)/g
  const xml = xmlInput.replace(regex, `$1${newlineOption}$2$3`)
  let pad = 0
  xml.split(/\r?\n/).forEach(l => {
    const line = l.trim()

    let indent = 0
    if (line.match(/.+<\/\w[^>]*>$/)) {
      indent = 0
    } else if (line.match(/^<\/\w/)) {
      // Somehow istanbul doesn't see the else case as covered, although it is. Skip it.
      /* istanbul ignore else  */
      if (pad !== 0) {
        pad -= 1
      }
    } else if (line.match(/^<\w([^>]*[^\/])?>.*$/)) {
      indent = 1
    } else {
      indent = 0
    }

    const padding = stringTimesN(pad, indentString)
    formatted += padding + line + newlineOption // eslint-disable-line prefer-template
    pad += indent
  })

  return formatted.trim()
}
443496
def GetMissionXML(summary):
    ''' '''
    
    positions = buildPositionList(items)
    
    return '''<?xml version="1.0" encoding="UTF-8" ?>
    <Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <About>
            <Summary>''' + summary + '''</Summary>
        </About>

        <ServerSection>
            <ServerHandlers>
                <FlatWorldGenerator generatorString="3;7,220*1,5*3,2;3;,biome_1" />
                <DrawingDecorator>
                    <DrawCuboid x1="-50" y1="227" z1="-50" x2="50" y2="227" z2="50" type="air" />   <!-- to clear old items-->
                    <DrawCuboid x1="-50" y1="226" z1="-50" x2="50" y2="226" z2="50" type="monster_egg" variant="chiseled_brick" />
                    <DrawCuboid x1="-3" y1="226" z1="-3" x2="3" y2="226" z2="3" type="dirt" />
                    <DrawCuboid x1="-3" y1="227" z1="-3" x2="3" y2="227" z2="3" type="red_flower" variant="blue_orchid" /> <!-- yes, blue orchids are indeed a type of red flower. -->
                    ''' + getItemDrawing(positions) + '''
                </DrawingDecorator>
                <ServerQuitFromTimeUp timeLimitMs="150000"/>
                <ServerQuitWhenAnyAgentFinishes />
            </ServerHandlers>
        </ServerSection>

        <AgentSection mode="Survival">
            <Name>Delia</Name>
            <AgentStart>
                <Placement x="0.5" y="227.0" z="0.5"/>
                <Inventory>
                </Inventory>
            </AgentStart>
            <AgentHandlers>
                <RewardForCollectingItem>
                    <Item reward="10" type="planks" variant="spruce dark_oak" />
                    <Item reward="100" type="cooked_rabbit carrot baked_potato brown_mushroom"/>
                    <Item reward="500" type="bowl"/>
                    <Item reward="1000" type="rabbit_stew"/>
                </RewardForCollectingItem>
                <RewardForDiscardingItem>
                    <Item reward="-2" type="planks"/>
                    <Item reward="-6" type="cooked_rabbit carrot baked_potato brown_mushroom"/>
                </RewardForDiscardingItem>
                <ContinuousMovementCommands turnSpeedDegs="480"/>
                <SimpleCraftCommands/>
                <InventoryCommands/>
                <ObservationFromSubgoalPositionList>''' + getSubgoalPositions(positions) + '''
                </ObservationFromSubgoalPositionList>
                <ObservationFromFullInventory/>
                <AgentQuitFromCollectingItem>
                    <Item type="rabbit_stew" description="Supper's Up!!"/>
                </AgentQuitFromCollectingItem>''' + video_requirements + '''
            </AgentHandlers>
        </AgentSection>

    </Mission>'''
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
31708
function eachNode(src, callback) {
        var index = 0;
        var text, range, length, payload;
        while (index < src.length) {

            // find the next tag
            range = _findTag(src, index);
            if (!range) {
                range = { from: src.length, length: 0 };
            }

            // add the text before the tag
            length = range.from - index;
            if (length > 0) {
                text = src.substr(index, length);
                if (/\S/.test(text)) {
                    payload = extractPayload(text);
                    payload.sourceOffset = index;
                    payload.sourceLength = length;
                    callback(payload);
                }
            }

            // add the tag
            if (range.length > 0) {
                payload = extractPayload(src.substr(range.from, range.length));
                payload.sourceOffset = range.from;
                payload.sourceLength = range.length;
                callback(payload);
            }

            // advance
            index = range.from + range.length;
        }
    }
1363815
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
        
        nl = "\n"
        out = []
        namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
                                                            for v in vlist)
        nextLevelIndent = indent + "  "

        # collapse out indents if formatting is not desired
        if not formatted:
            indent = ""
            nextLevelIndent = ""
            nl = ""

        selfTag = None
        if doctag is not None:
            selfTag = doctag
        else:
            if self.__name:
                selfTag = self.__name

        if not selfTag:
            if namedItemsOnly:
                return ""
            else:
                selfTag = "ITEM"

        out += [ nl, indent, "<", selfTag, ">" ]

        for i,res in enumerate(self.__toklist):
            if isinstance(res,ParseResults):
                if i in namedItems:
                    out += [ res.asXML(namedItems[i],
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
                else:
                    out += [ res.asXML(None,
                                        namedItemsOnly and doctag is None,
                                        nextLevelIndent,
                                        formatted)]
            else:
                # individual token, see if there is a name for it
                resTag = None
                if i in namedItems:
                    resTag = namedItems[i]
                if not resTag:
                    if namedItemsOnly:
                        continue
                    else:
                        resTag = "ITEM"
                xmlBodyText = _xml_escape(_ustr(res))
                out += [ nl, nextLevelIndent, "<", resTag, ">",
                                                xmlBodyText,
                                                "</", resTag, ">" ]

        out += [ nl, indent, "</", selfTag, ">" ]
        return "".join(out)
34003
public String generateMarkov(int length, int context, String seed) {
    String str = seed;
    while (str.length() < length) {
      String prefix = str.substring(Math.max(str.length() - context, 0), str.length());
      TrieNode node = inner.matchPredictor(prefix);
      long cursorCount = node.getCursorCount();
      long fate = CompressionUtil.random.nextLong() % cursorCount;
      String next = null;
      Stream<TrieNode> stream = node.getChildren().map(x -> x);
      List<TrieNode> children = stream.collect(Collectors.toList());
      for (TrieNode child : children) {
        fate -= child.getCursorCount();
        if (fate <= 0) {
          if (child.getChar() != NodewalkerCodec.END_OF_STRING) {
            next = child.getToken();
          }
          break;
        }
      }
      if (null != next) {
        str += next;
      }
      else {
        break;
      }
    }
    return str;
  }
95326
function parsePlistXML (node) {
  var i, new_obj, key, val, new_arr, res, d;

  if (!node)
    return null;

  if (node.nodeName === 'plist') {
    new_arr = [];
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        new_arr.push( parsePlistXML(node.childNodes[i]));
      }
    }
    return new_arr;

  } else if (node.nodeName === 'dict') {
    new_obj = {};
    key = null;
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        if (key === null) {
          key = parsePlistXML(node.childNodes[i]);
        } else {
          new_obj[key] = parsePlistXML(node.childNodes[i]);
          key = null;
        }
      }
    }
    return new_obj;

  } else if (node.nodeName === 'array') {
    new_arr = [];
    for (i=0; i < node.childNodes.length; i++) {
      // ignore comment nodes (text)
      if (!shouldIgnoreNode(node.childNodes[i])) {
        res = parsePlistXML(node.childNodes[i]);
        if (null != res) new_arr.push(res);
      }
    }
    return new_arr;

  } else if (node.nodeName === '#text') {
    // TODO: what should we do with text types? (CDATA sections)

  } else if (node.nodeName === 'key') {
    return node.childNodes[0].nodeValue;

  } else if (node.nodeName === 'string') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      res += node.childNodes[d].nodeValue;
    }
    return res;

  } else if (node.nodeName === 'integer') {
    // parse as base 10 integer
    return parseInt(node.childNodes[0].nodeValue, 10);

  } else if (node.nodeName === 'real') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      if (node.childNodes[d].nodeType === 3) {
        res += node.childNodes[d].nodeValue;
      }
    }
    return parseFloat(res);

  } else if (node.nodeName === 'data') {
    res = '';
    for (d=0; d < node.childNodes.length; d++) {
      if (node.childNodes[d].nodeType === 3) {
        res += node.childNodes[d].nodeValue.replace(/\s+/g, '');
      }
    }

    // decode base64 data to a Buffer instance
    return new Buffer(res, 'base64');

  } else if (node.nodeName === 'date') {
    return new Date(node.childNodes[0].nodeValue);

  } else if (node.nodeName === 'true') {
    return true;

  } else if (node.nodeName === 'false') {
    return false;
  }
}
379921
def to_xml
      out = ""
      builder = Builder::XmlMarkup.new(:target => out, :indent => 2)
      builder.instruct!
      build_xml(builder)
      out
    end