Enables sections to be backward compatible with the structure format
(before some actions were missing as they were defined in the tree part).
legacy format : tao <= 2.6.x
this method should be deprecated from 2.8.0 / 3.0.0
961237
private function migrateDataFromLegacyFormat(){

        if(count($this->trees) > 0){

            //tree attributes to be migrated.
           $mapping = array(
              'editClassUrl' => array(
                'attr'   => 'selectClass',
                'action' => array(
                    'id'      => 'edit_class',
                    'name'    => 'edit class',
                    'group'   => 'none',
                    'context' => 'class',
                    'binding' => 'load'
                ) 
              ),
              'editInstanceUrl' => array(
                'attr'   => 'selectInstance',
                'action' => array(
                    'id'      => 'edit_instance',
                    'name'    => 'edit instance',
                    'group'   => 'none',
                    'context' => 'instance',
                    'binding' => 'load'
                ) 
              ),
              'addInstanceUrl'  => array(
                'attr'   => 'addInstance',
                'action' => array(
                    'id'      => 'add_instance',
                    'name'    => 'add instance',
                    'group'   => 'none',
                    'context' => 'instance',
                    'binding' => 'instantiate'
                ) 
              ),
              'addSubClassUrl'  => array(
                'attr'   => 'addClass',
                'action' => array(
                    'id'      => 'add_class',
                    'name'    => 'add class',
                    'group'   => 'none',
                    'context' => 'class',
                    'binding' => 'subClass'
                ) 
              ),
              'deleteUrl' => array(
                'attr'   => 'addClass',
                'action' => array(
                    'id'      => 'add_class',
                    'name'    => 'add class',
                    'group'   => 'none',
                    'context' => 'class',
                    'binding' => 'subClass'
                ) 
              ),
              'moveInstanceUrl' => array(
                'attr'   => 'moveInstance',
                'action' => array(
                    'id'      => 'move',
                    'name'    => 'move',
                    'group'   => 'none',
                    'context' => 'instance',
                    'binding' => 'moveNode'
                ) 
              )
           );

           foreach($this->trees as $index => $tree){
               $needMigration = false;
               $treeAttributes = $tree->getAttributes();
            
               //check if this attribute needs a migration
               foreach($treeAttributes as $attr){
                    if(array_key_exists($attr, $mapping)){
                        $needMigration = true;
                        break;
                    } 
               }
               if($needMigration){
                    $newData = array();

                    //migrate the tree
                    foreach($treeAttributes as $attr){
                        //if the attribute belongs to the mapping
                        if(array_key_exists($attr, $mapping)){
                            $url = $tree->get($attr);
                            $actionName = false;
    
                            //try to find an action with the same url
                            foreach($this->actions as $action){
                                if($action->getRelativeUrl() == $url){
                                    $actionName = $action->getId();
                                    break;
                                }
                            }
                            if($actionName){
                                $newData[$mapping[$attr]['attr']] = $actionName;
                            } else {
    
                                //otherwise create a new action from the mapping
                                $newData[$mapping[$attr]['attr']] = $mapping[$attr]['action']['id'];
                                $actionData = $mapping[$attr]['action'];
                                $actionData['url'] = $url;
                                
                                list($extension, $controller, $action) = explode('/', trim($url, '/'));
                                $actionData['extension'] = $extension;
                                $actionData['controller'] = $controller;
                                $actionData['action'] = $action;
                                
                                $this->actions[] = new Action($actionData); 
                            }
                        } else {
                            $newData[$attr] = $tree->get($attr);
                        }
                    }
    
                    //the tree is replaced
                    $this->trees[$index] = new Tree($newData);
               }
           }
        }
    }
178821
protected void _format(SarlBehavior behavior, IFormattableDocument document) {
		formatAnnotations(behavior, document, XbaseFormatterPreferenceKeys.newLineAfterClassAnnotations);
		formatModifiers(behavior, document);

		final ISemanticRegionsFinder regionFor = this.textRegionExtensions.regionFor(behavior);
		document.append(regionFor.keyword(this.keywords.getBehaviorKeyword()), ONE_SPACE);

		document.surround(regionFor.keyword(this.keywords.getExtendsKeyword()), ONE_SPACE);
		document.format(behavior.getExtends());

		formatBody(behavior, document);
	}
489154
function selectFormat(format) {
  let method = "toTable";
  let extension = `.${format}`;

  switch (format) {
    case "json":
      method = "toJSON";
      break;
    case "csv":
      method = "toCSV";
      break;
    case "html":
      method = "toHTML";
      break;
    case "md":
      method = "toMarkdown";
      break;
    default:
      break;
  }

  return {
    extension: extension,
    method: method
  }
}
1079673
private void updateSubtreeMap(final ITreeData paramNode, final INodeReadTrx paramRtx) throws TTIOException {
        assert paramNode != null;
        assert paramRtx != null;

        mIsInSubtree.set(paramNode, paramNode, true);
        if (paramNode.hasParent()) {
            paramRtx.moveTo(paramNode.getDataKey());
            while (((ITreeStructData)paramRtx.getNode()).hasParent()) {
                paramRtx.moveTo(paramRtx.getNode().getParentKey());
                mIsInSubtree.set(paramRtx.getNode(), paramNode, true);
            }
        }
    }
1369695
@Override
    public R visitDeprecated(DeprecatedTree node, P p) {
        return defaultAction(node, p);
    }
777286
function (elems, context) {
            var oldFragment = $.buildFragment,
                ret;

            elems = [elems];
            // Set context per 1.8 logic
            context = context || document;
            context = !context.nodeType && context[0] || context;
            context = context.ownerDocument || context;

            ret = oldFragment.call(jQuery, elems, context);

            return ret.cacheable ? $.clone(ret.fragment) : ret.fragment || ret;
        }
433959
protected function convert_legacy_criterion_elements() {

        $this->write_xml('workshopform_rubric_config', array('layout' => 'list'));

        $firstelement = reset($this->elements);
        if ($firstelement === false) {
            // no elements defined in moodle.xml
            return;
        }

        // write the xml describing the artificial single rubric item
        $this->xmlwriter->begin_tag('workshopform_rubric_dimension', array('id' => $firstelement['id']));
        $this->xmlwriter->full_tag('sort', 1);
        $this->xmlwriter->full_tag('description', trim(get_string('dimensionnumber', 'workshopform_rubric', '')));
        $this->xmlwriter->full_tag('descriptionformat', FORMAT_HTML);

        foreach ($this->elements as $element) {
            $this->write_xml('workshopform_rubric_level', array(
                'id'               => $element['id'],
                'grade'            => $element['maxscore'],
                'definition'       => $element['description'],
                'definitionformat' => FORMAT_HTML
            ), array('/workshopform_rubric_level/id'));
        }

        $this->xmlwriter->end_tag('workshopform_rubric_dimension');
    }
797409
function formatNodes(merged, notSplit) {
    // grab the class name out (if it exists)
    remainingNodes = _.reject(merged, function(i) {
      if (i["tagname"] === "class") {
        classPrefix = i["name"];
        nodes[classPrefix] = createBasicTranslation(classPrefix, "class", i, options);

        if (i["inherits"] !== undefined && i["inherits"].length > 0) 
          nodes[classPrefix]["inherits"] = i["inherits"];

        if (i["allowchild"] !== undefined) 
          nodes[classPrefix]["allowchild"] = i["allowchild"].doc;

        return true;
      }
    });

    // flag nodes that don't have doc
    // or that just contain "@todo" in the beginning
    remainingNodes = _.map(remainingNodes, function(n) {
      if (n["doc"] === undefined || /^@todo/i.test(n["doc"]))
        n.undocumented = true;

      return n;
    });

    remainingNodes = _.reject(remainingNodes, function(i) {
      var isEvent = i["tagname"] == "event";
      var isConstructor = i["tagname"] == "constructor";
      var joinChar = isEvent ? "@" : ".";

      if (classPrefix === undefined && options.globalNS) 
        classPrefix = options.globalNS;

      if (new RegExp("^" + options.globalNS + joinChar + i["name"]).test(i["original_name"]))
        className = options.globalNS;
      else
        className = classPrefix;

      memberName = [className, i["name"]].join(joinChar);

      if (memberName.lastIndexOf(".") === memberName.length - 1 && i["inheritdoc"] === undefined) {
        console.error(i);    
        console.error("FATAL".red + ": this object doesn't have a proper name. Check that your comment is written correctly. Typically, his happens when: ");
        console.error("   * A statement above is missing a semicolon--including closing function tags--see this bug: " + "http://code.google.com/p/esprima/issues/detail?id=347&thanks=347&ts=1348621099".cyan);
        console.error("   * The line above a comment is a single line comment--see this bug: " + "https://github.com/senchalabs/jsduck/issues/247".cyan);
        process.exit(1)
      }

      if (isConstructor)
        memberName = classPrefix + ".new";
      
      if (memberName.charAt(0) == ".")
        memberName = memberName.slice(1);

      if (i["tagname"] === "method" || i["tagname"] === "constructor" || isEvent) {
        nodes[memberName] = createBasicTranslation(memberName, i["tagname"], i, options);
        nodes[memberName]["signatures"] = [];
        var ret = {};

        // these next blocks don't yet handle alternate signatures...
        // but are written as if they will :)
        if (i["params"] !== undefined) {
            var sig = { "arguments": [] };
            nodes[memberName]["arguments"] = [];

            _.each(i["params"], function(p) {
              // construct the args object
              var args = {};
              args.name = p["name"];
              args.description = p["doc"];
              args.default_value = p["default"];

              args.types = [];

              // types could be multiple
              if (p["type"].indexOf("|") >= 0) {
                p["type"].split("|").forEach(function(t) {
                  args.types.push(trim(t));
                });
              }
              else if (p["type"].indexOf(",") >= 0) {
                console.warn("Warning".yellow + ": you're using ',' to separate types in " + memberName + ", use '|' instead.");
              }
              else {
                args.types.push(p["type"]);
              }

              args.optional = p["optional"];

              sig.arguments.push(args);

              // there are args on "signatures" and a separate arguments property
              nodes[memberName]["arguments"].push(args);
            });
        }

        if (i["return"] !== undefined && i["return"].type !== undefined) {
          if (i["return"].type.indexOf("[") == 0) { // TODO: probably not best to do this here
            ret.type = i["return"].type.substr(1, i["return"].type.length - 2);
            ret.isArray = true;
          }
          else {
            ret.type = i["return"].type;
          }

          ret.description = i["return"].doc;

          // there are returns on "signatures" and a separate returns property
          //nodes[memberName]["returns"].push(ret);
        }

        var pushedObj = { };

        if (_.size(nodes[memberName]["arguments"]) > 0)    
          pushedObj["arguments"] = nodes[memberName]["arguments"];

        if (_.size(ret) > 0 && ret.type !== "undefined")
          pushedObj["returns"] = [ret];

        nodes[memberName]["signatures"].push(pushedObj);

        if (isEvent) {
          if (i["cancelable"] !== undefined)
            nodes[memberName]["cancelable"] = i["cancelable"];
          if (i["bubbles"] !== undefined)
            nodes[memberName]["bubbles"] = i["bubbles"];
        }

        if (i["tagname"] === "method") {
          // avoid reinitializing on each node loop
          if (reportObject[className] === undefined) {
              reportObject[className] = {};
              reportObject[className].missingMembers = [];
          }
          
          // go through the list of what esprima said were methods
          // and make sure they have real documentation
          var funcLength = availableFunctions.length;

          for (var l = 0; l < funcLength; l++) {
            var func = availableFunctions[l];

            // we found a matching function! 
            if (func.name === i["name"]) { 
              // if it's tagged as incomplete or private, just skip it
              if (nodes[memberName]["private"] || nodes[memberName]["ignore"]) {
                // no op, we'll slice below
              }
              // now make sure the parameters match, too
              else if (func.params !== undefined) {
                _.any(func.params, function (funcArg, idx) {
                  // catch instance where args are missing documentation
                  if (idx >= nodes[memberName]["arguments"].length) {
                    reportObject[className].missingMembers.push({name: i["name"], member: nodes[memberName], reason: "Missing documented arguments"});
                    return true;
                  }
                  // catch instance where arg and func names don't match
                  else if (funcArg.name !== nodes[memberName]["arguments"][idx].name) {
                    reportObject[className].missingMembers.push({name: i["name"], member: nodes[memberName], reason: "Documented arguments missing proper name"});
                    return true;
                  }
                });
              }

              // all the doc "tests" passed, remove this method from the reporting object
              availableFunctions.splice(l, 1);
              break;
            }
          }
        }

        methodCount++;
        return true;
      }

      else if (i["tagname"] === "property") {
        nodes[memberName] = createBasicTranslation(memberName, "property", i, options);
        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: [ { type: i["type"], default_value: i["default"] } ] } ];
        return true;
      }

      else if (i["tagname"] === "attribute") {
        nodes[memberName] = createBasicTranslation(memberName, "attribute", i, options);

        var returnsArray = [];

        if (i["default"] !== undefined && i["default"] !== null)
          nodes[memberName]["defaults"] = i["default"];

        if (i["type"]) {
          var types = i["type"].split("|");

          _.each(types, function(t) {
            returnsArray.push({type: trim(t)});
          });
        }

        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: returnsArray } ];
        return true;
      }

      else if (i["tagname"] === "binding") {
        nodes[memberName] = createBasicTranslation(memberName, "binding", i, options);
        nodes[memberName]["signatures"] = [ { arguments: undefined, returns: [ { type: i["type"] } ] } ];
        return true;
      }

      else {
        console.warn("Warning".yellow + ": I don't know what " + i["tagname"] + " is supposed to do in " + file);
        return true;
      }
    });

    if (notSplit) {
      checkMissingFunctions(notSplit);      
      reportObject[className].documented = methodCount;
    }

    // do pre-distribute early work
    _.each(nodes, function (node, id) {
      var clone;

      // assign hierarchy helpers
      node.aliases  = [];
      node.children = [];

      // set source file of the node
      node.file = file;

      if ('class' === node.type) {
        node.subclasses = [];
      }

      // collect sections
      if ('section' === node.type) {
        list[node.id] = node;
        return;
      }

      // elements with undefined section get '' section,
      // and will be resolved later, when we'll have full
      // element list
      list[(node.section || '') + '.' + node.id] = node;

      // bound methods produce two methods with the same description but different signatures
      // E.g. Element.foo(@element, a, b) becomes
      // Element.foo(element, a, b) and Element#foo(a, b)
      if ('method' === node.type && node.bound) {
        clone = _.clone(node);
        clone.id = node.id.replace(/(.+)\.(.+)$/, '$1#$2');

        // link to methods
        node.bound = clone.id;
        clone.bound = node.id;

        // insert bound method clone
        list[(node.section || '') + '.' + clone.id] = clone;
      }
    });
  }
1100976
function convertTrees() {
	setDefault("treeClass","mktree");
	setDefault("nodeClosedClass","liClosed");
	setDefault("nodeOpenClass","liOpen");
	setDefault("nodeBulletClass","liBullet");
	setDefault("nodeLinkClass","bullet");
	setDefault("preProcessTrees",true);
	if (preProcessTrees) {
		if (!document.createElement) { return; } // Without createElement, we can't do anything
		var uls = document.getElementsByTagName("ul");
		if (uls==null) { return; }
		var uls_length = uls.length;
		for (var uli=0;uli<uls_length;uli++) {
			var ul=uls[uli];
			if (ul.nodeName=="UL" && ul.className==treeClass) {
				processList(ul);
				ul.setAttribute( "data-xdh-mktree", "handled" );
			}
		}
	}
}
29025
def override_supported_formats(formats):
    
    def decorator(function):
        @wraps(function)
        def wrapper(self, *args, **kwargs):
            self.supported_formats = formats
            return function(self, *args, **kwargs)
        return wrapper
    return decorator
1303695
public final void meta_section() throws RecognitionException {
		CommonTree metalit=null;

		try {
			// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:73:5: ( ^( VT_META (metalit= LITERAL )? ) )
			// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:73:7: ^( VT_META (metalit= LITERAL )? )
			{
			match(input,VT_META,FOLLOW_VT_META_in_meta_section224); 
			if ( input.LA(1)==Token.DOWN ) {
				match(input, Token.DOWN, null); 
				// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:73:24: (metalit= LITERAL )?
				int alt8=2;
				int LA8_0 = input.LA(1);
				if ( (LA8_0==LITERAL) ) {
					alt8=1;
				}
				switch (alt8) {
					case 1 :
						// src/main/resources/org/drools/compiler/lang/dsl/DSLMapWalker.g:73:24: metalit= LITERAL
						{
						metalit=(CommonTree)match(input,LITERAL,FOLLOW_LITERAL_in_meta_section228); 
						}
						break;

				}

				match(input, Token.UP, null); 
			}


			        if ( metalit == null || (metalit!=null?metalit.getText():null) == null || (metalit!=null?metalit.getText():null).length() == 0 ) {
			            entry_stack.peek().retval.setMetaData(DSLMappingEntry.EMPTY_METADATA);
			        } else {
			                entry_stack.peek().retval.setMetaData(new DSLMappingEntry.DefaultDSLEntryMetaData( (metalit!=null?metalit.getText():null) ));
			            }
			    
			}

		}
		catch (RecognitionException re) {
			reportError(re);
			recover(input,re);
		}
		finally {
			// do for sure before leaving
		}
	}
1346274
def to_deprecated_son(self, prefix='', tag='i4x'):
        
        # This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),
        # because that format was used to store data historically in mongo

        # adding tag b/c deprecated form used it
        son = SON({prefix + 'tag': tag})
        for field_name in ('org', 'course'):
            # Temporary filtering of run field because deprecated form left it out
            son[prefix + field_name] = getattr(self.course_key, field_name)
        for (dep_field_name, field_name) in [('category', 'block_type'), ('name', 'block_id')]:
            son[prefix + dep_field_name] = getattr(self, field_name)

        son[prefix + 'revision'] = self.course_key.branch
        return son
128085
private static void validateFormatForViewAction(Format format) throws ApiException {
		switch (format) {
		case JSON:
		case JSONP:
		case XML:
		case HTML:
			return;
		default:
			throw new ApiException(ApiException.Type.BAD_FORMAT, "The format OTHER should not be used with views and actions.");
		}
	}
177566
def formats(self, value):
        

        if value is not None:
            assert type(value) is FormatsTree, "'{0}' attribute: '{1}' type is not 'FormatsTree'!".format(
                "formats", value)
        self.__formats = value
1358835
def rebuild_collection_tree(old_collection_ident, new_document_id_map, plpy):
    
    get_tree = plpy.prepare('''
    WITH RECURSIVE t(node, parent, document, title, childorder, latest, path)
        AS (SELECT tr.nodeid, tr.parent_id, tr.documentid, tr.title,
                   tr.childorder, tr.latest, ARRAY[tr.nodeid]
            FROM trees tr
            WHERE tr.documentid = $1 AND tr.is_collated = 'False'
    UNION ALL
        SELECT c.nodeid, c.parent_id, c.documentid, c.title,
               c.childorder, c.latest, path || ARRAY[c.nodeid]
        FROM trees c JOIN t ON (c.parent_id = t.node)
        WHERE not c.nodeid = ANY(t.path)
    )
    SELECT * FROM t
    ''', ('integer',))

    def get_old_tree():
        return plpy.execute(get_tree, (old_collection_ident,))

    tree = {}  # { old_nodeid: {'data': ...}, ...}
    children = {}  # { nodeid: [child_nodeid, ...], child_nodeid: [...]}
    for i in get_old_tree():
        tree[i['node']] = {'data': i, 'new_nodeid': None}
        children.setdefault(i['parent'], [])
        children[i['parent']].append(i['node'])

    insert_tree = plpy.prepare('''
    INSERT INTO trees (nodeid, parent_id, documentid,
        title, childorder, latest)
    VALUES (DEFAULT, $1, $2, $3, $4, $5)
    RETURNING nodeid
    ''', ('integer', 'integer', 'text', 'integer', 'boolean'))

    def execute(fields):
        results = plpy.execute(insert_tree, fields, 1)
        return results[0]['nodeid']

    root_node = children[None][0]

    def build_tree(node, parent):
        data = tree[node]['data']
        new_node = execute([parent, new_document_id_map.get(data['document'],
                            data['document']), data['title'],
                            data['childorder'], data['latest']])
        for i in children.get(node, []):
            build_tree(i, new_node)
    build_tree(root_node, None)
1248557
public void buildDeprecatedMethodInfo(XMLNode node, Content methodsContentTree) {
        methodWriter.addDeprecatedMemberInfo((ExecutableElement)currentMember, methodsContentTree);
    }
1090050
FormatStep updateElement(ChronoElement<?> element) {

        FormatProcessor<?> proc = update(this.processor, element);

        if (this.processor == proc) {
            return this;
        }

        return new FormatStep(
            proc,
            this.level,
            this.section,
            this.sectionalAttrs,
            this.fullAttrs,
            this.reserved,
            this.padLeft,
            this.padRight,
            this.orMarker,
            this.lastOrBlockIndex
        );

    }