Given an input schema, resolve all the TVEs in all the output column
expressions.  This method is necessary to be able to do this for
inlined projection nodes that don't have a child from which they can get
an output schema.
16580
void resolveColumnIndexesUsingSchema(NodeSchema inputSchema) {
        // get all the TVEs in the output columns
        int difftor = 0;
        for (SchemaColumn col : m_outputSchema) {
            col.setDifferentiator(difftor);
            ++difftor;
            Collection<TupleValueExpression> allTves =
                    ExpressionUtil.getTupleValueExpressions(col.getExpression());
            // and update their indexes against the table schema
            for (TupleValueExpression tve : allTves) {
                tve.setColumnIndexUsingSchema(inputSchema);
                assert (tve.getColumnIndex() >= 0 && tve.getColumnIndex() < inputSchema.size());
            }
        }
        // DON'T RE-SORT HERE
    }
1202684
public NodeSchema toTVEAndFixColumns(Map<String, Pair<String, Integer>> nameMap) {
      final NodeSchema ns = copyAndReplaceWithTVE();    // First convert all non-TVE expressions to TVE in a copy
       m_columns.clear();
       m_columnsMapHelper.clear();
       for(int indx = 0; indx < ns.size(); ++indx) {    // then update columns
           final SchemaColumn sc = ns.getColumn(indx);
           assert(sc.getExpression() instanceof TupleValueExpression);
           if(nameMap.containsKey(sc.getColumnName())) {
               final String newColName = nameMap.get(sc.getColumnName()).getFirst();
               sc.reset(sc.getTableName(), sc.getTableAlias(), newColName, sc.getColumnAlias());
               sc.setDifferentiator(indx);
               TupleValueExpression exp = (TupleValueExpression) sc.getExpression();
               exp.setColumnIndex(indx);
               exp.setColumnName(newColName);
               exp.setDifferentiator(indx);
           }
       }
       for(SchemaColumn sc : ns) {
           addColumn(sc);
       }
       return this;
    }
592225
@Override
    public Schema transform(Schema inputSchema) {
        Schema.Builder newSchema = new Schema.Builder();
        for (int i = 0; i < inputSchema.numColumns(); i++) {
            if (inputSchema.getType(i) == ColumnType.String) {
                newSchema.addColumnDouble(inputSchema.getMetaData(i).getName());
            } else
                newSchema.addColumn(inputSchema.getMetaData(i));

        }
        return newSchema.build();
    }
1155950
def resolve_structure(self, fc, ct):
        
        if self.debug: print("++++++++ Resolving structure of (%s) with %s"%(fc, ct))
        for w in ct.structure.withs:
            try:
                if w.instance == 'parent' or w.instance == 'this':
                    w2 = With(w.instance, w.as_)
                else:
                    w2 = With(fc.paths[w.instance].value,
                              w.as_)
            except:
                raise ModelError("Unable to resolve With parameters for "
                                 "'{0}' in component '{1}'",
                                 w.as_, fc.id)
            fc.structure.add(w2)
            
        if len(ct.structure.tunnels) > 0:
            raise ModelError("Tunnel is not yet supported in PyLEMS!");
            
        for fe in ct.structure.for_eachs:
            fc.structure.add_for_each(fe)
            
        for ev in ct.structure.event_connections:
            try:
                
                from_inst = fc.structure.withs[ev.from_].instance
                to_inst = fc.structure.withs[ev.to].instance
                
                if self.debug: print("EC..: "+from_inst+" to "+to_inst+ " in "+str(fc.paths))
                
                if len(fc.texts) > 0 or len(fc.paths) > 0:
                    
                    source_port = fc.texts[ev.source_port].value if ev.source_port and len(ev.source_port)>0 and ev.source_port in fc.texts else None
                    target_port = fc.texts[ev.target_port].value if ev.target_port and len(ev.target_port)>0 and ev.target_port in fc.texts else None
                    
                    if self.debug: print("sp: %s"%source_port)
                    if self.debug: print("tp: %s"%target_port)

                    receiver = None

                    # TODO: Get more efficient way to find parent comp
                    if '../' in ev.receiver:
                        receiver_id = None
                        parent_attr = ev.receiver[3:]
                        if self.debug: print("Finding %s in the parent of: %s (%i)"%(parent_attr, fc, id(fc)))
                        
                        for comp in self.components.values():
                            if self.debug: print(" - Checking %s (%i)" %(comp.id,id(comp))) 
                            for child in comp.children:
                                if self.debug: print("    - Checking %s (%i)" %(child.id,id(child))) 
                                for child2 in child.children:
                                    if child2.id == fc.id and child2.type == fc.type and child.id == fc.parent_id:
                                        if self.debug: print("    - Got it?: %s (%i), child: %s"%(child.id, id(child), child2))
                                        receiver_id = child.parameters[parent_attr]
                                        if self.debug: print("Got it: "+receiver_id)
                                        break

                        if receiver_id is not None:            
                            for comp in self.fat_components:
                                if comp.id == receiver_id:
                                        receiver = comp
                                        if self.debug: print("receiver is: %s"%receiver)

                    if self.debug: print("rec1: %s"%receiver)
                    if not receiver:
                        receiver = fc.component_references[ev.receiver].referenced_component if ev.receiver else None
                    receiver_container = fc.texts[ev.receiver_container].value if (fc.texts and ev.receiver_container) else ''

                    if self.debug: print("rec2: %s"%receiver)
                    if len(receiver_container)==0:
                        # TODO: remove this hard coded check!
                        receiver_container = 'synapses'

                else:
                    #if from_inst == 'parent':
                        #par = fc.component_references[ev.receiver]
                    
                    if self.debug: 
                        print("+++++++++++++++++++")
                        print(ev.toxml())
                        print(ev.source_port)
                        print(fc)
                    source_port = ev.source_port
                    target_port = ev.target_port
                    receiver = None
                    receiver_container = None
                    
                ev2 = EventConnection(from_inst,
                                      to_inst,
                                      source_port,
                                      target_port,
                                      receiver,
                                      receiver_container)
                if self.debug: 
                    print("Created EC: "+ev2.toxml())
                    print(receiver)
                    print(receiver_container)
            except:
                logging.exception("Something awful happened!")
                raise ModelError("Unable to resolve event connection parameters in component '{0}'",fc)
            fc.structure.add(ev2)
                
        for ch in ct.structure.child_instances:
            try:
                if self.debug: print(ch.toxml())
                if '../' in ch.component:
                    parent = self.get_parent_component(fc)
                    if self.debug: print("Parent: %s"%parent)
                    comp_ref = ch.component[3:]
                    if self.debug: print("comp_ref: %s"%comp_ref)
                    comp_id = parent.parameters[comp_ref]
                    comp = self.fat_components[comp_id]
                    ch2 = ChildInstance(ch.component, comp)
                else:    
                    ref_comp = fc.component_references[ch.component].referenced_component
                    ch2 = ChildInstance(ch.component, ref_comp)
            except Exception as e:
                if self.debug: print(e)
                raise ModelError("Unable to resolve child instance parameters for "
                                 "'{0}' in component '{1}'",
                                 ch.component, fc.id)
            fc.structure.add(ch2)

        for mi in ct.structure.multi_instantiates:
            try:
                if mi.component:
                    mi2 = MultiInstantiate(component=fc.component_references[mi.component].referenced_component,
                                           number=int(fc.parameters[mi.number].numeric_value))
                else:
                    mi2 = MultiInstantiate(component_type=fc.component_references[mi.component_type].referenced_component,
                                           number=int(fc.parameters[mi.number].numeric_value))                    
            except:
                raise ModelError("Unable to resolve multi-instantiate parameters for "
                                 "'{0}' in component '{1}'",
                                 mi.component, fc)
            fc.structure.add(mi2)
443603
function populate(schemas) {
  var resolver = new Resolver(schemas);
  // Reduce force sequential execution.
  return Promise.reduce(resolver.resolve(), populateSchema.bind(this), []);
}
352662
def intermediary_to_schema(tables, relationships, output):
    
    dot_file = _intermediary_to_dot(tables, relationships)
    graph = AGraph()
    graph = graph.from_string(dot_file)
    extension = output.split('.')[-1]
    graph.draw(path=output, prog='dot', format=extension)
445337
private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {
        if (!node.isDefined()) {
            return node;
        }

        ModelType type = node.getType();
        ModelNode resolved;
        if (type == ModelType.EXPRESSION) {
            resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);
        } else if (type == ModelType.OBJECT) {
            resolved = node.clone();
            for (Property prop : resolved.asPropertyList()) {
                resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));
            }
        } else if (type == ModelType.LIST) {
            resolved = node.clone();
            ModelNode list = new ModelNode();
            list.setEmptyList();
            for (ModelNode current : resolved.asList()) {
                list.add(resolveExpressionsRecursively(current));
            }
            resolved = list;
        } else if (type == ModelType.PROPERTY) {
            resolved = node.clone();
            resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));
        } else {
            resolved = node;
        }

        return resolved;
    }
356089
def get_flattened_bsp_keys_from_schema(schema):
    
    keys = []

    for key in schema.declared_fields.keys():
        field = schema.declared_fields[key]

        if isinstance(field, mm.fields.Nested) and \
                isinstance(field.schema, BoundSpatialPoint):
            keys.append("{}.{}".format(key, "position"))

    return keys
1053326
function resolveExtensions(schema) {

                var xprops, props;

                xprops = getExtendedProperties(schema, []);

                //unwind the property stack so that the earliest gets inheritance link
                schema.properties = schema.properties || {};
                function copyprop(item) { //util to get around jslint complaints about doing this directly in loop
                    schema.properties[item.key] = item.val;
                }

                while (xprops.length > 0) {
                    props = xprops.pop();
                    props.forEach(copyprop);
                }
            }
397880
function (schema, models, modelsToIgnore, modelPropertyMacro) {
    // Resolve the schema (Handle nested schemas)
    schema = resolveSchema(schema);

    if(typeof modelPropertyMacro !== 'function') {
      modelPropertyMacro = function(prop){
        return (prop || {}).default;
      };
    }

    modelsToIgnore= modelsToIgnore || {};

    var type = schema.type || 'object';
    var format = schema.format;
    var model;
    var output;

    if (!_.isUndefined(schema.example)) {
      output = schema.example;
    } else if (_.isUndefined(schema.items) && _.isArray(schema.enum)) {
      output = schema.enum[0];
    }

    if (_.isUndefined(output)) {
      if (schema.$ref) {
        model = models[simpleRef(schema.$ref)];

        if (!_.isUndefined(model)) {
          if (_.isUndefined(modelsToIgnore[model.name])) {
            modelsToIgnore[model.name] = model;
            output = schemaToJSON(model.definition, models, modelsToIgnore, modelPropertyMacro);
            delete modelsToIgnore[model.name];
          } else {
            if (model.type === 'array') {
              output = [];
            } else {
              output = {};
            }
          }
        }
      } else if (!_.isUndefined(schema.default)) {
        output = schema.default;
      } else if (type === 'string') {
        if (format === 'date-time') {
          output = new Date().toISOString();
        } else if (format === 'date') {
          output = new Date().toISOString().split('T')[0];
        } else {
          output = 'string';
        }
      } else if (type === 'integer') {
        output = 0;
      } else if (type === 'number') {
        output = 0.0;
      } else if (type === 'boolean') {
        output = true;
      } else if (type === 'object') {
        output = {};

        _.forEach(schema.properties, function (property, name) {
          var cProperty = _.cloneDeep(property);

          // Allow macro to set the default value
          cProperty.default = modelPropertyMacro(property);

          output[name] = schemaToJSON(cProperty, models, modelsToIgnore, modelPropertyMacro);
        });
      } else if (type === 'array') {
        output = [];

        if (_.isArray(schema.items)) {
          _.forEach(schema.items, function (item) {
            output.push(schemaToJSON(item, models, modelsToIgnore, modelPropertyMacro));
          });
        } else if (_.isPlainObject(schema.items)) {
          output.push(schemaToJSON(schema.items, models, modelsToIgnore, modelPropertyMacro));
        } else if (_.isUndefined(schema.items)) {
          output.push({});
        } else {
          console.log('Array type\'s \'items\' property is not an array or an object, cannot process');
        }
      }
    }

    return output;
  }
760897
def source_schema(self, sources=None, tables=None, clean=False):
        

        sources = self._resolve_sources(sources, tables, None,
                                        predicate=lambda s: s.is_processable)

        for source in sources:
            source.update_table()
            self.log("Creating source schema for '{}': Table {},  {} columns"
                     .format(source.name, source.source_table.name, len(source.source_table.columns)))

        self.commit()
1001532
private void resolveColumnReferences() {

        if (isDistinctSelect || isGrouped) {
            acceptsSequences = false;
        }

        for (int i = 0; i < rangeVariables.length; i++) {
            Expression e = rangeVariables[i].nonIndexJoinCondition;

            if (e == null) {
                continue;
            }

            resolveColumnReferencesAndAllocate(e, i + 1, false);
        }

        resolveColumnReferencesAndAllocate(queryCondition,
                                           rangeVariables.length, false);

        for (int i = 0; i < indexLimitVisible; i++) {
            resolveColumnReferencesAndAllocate(exprColumns[i],
                                               rangeVariables.length,
                                               acceptsSequences);
        }

        for (int i = indexLimitVisible; i < indexStartOrderBy; i++) {
            resolveColumnReferencesAndAllocate(exprColumns[i],
                                               rangeVariables.length, false);
        }

    /************************* Volt DB Extensions *************************/
        resolveColumnReferencesInGroupBy();
    /**********************************************************************/

        resolveColumnReferencesInOrderBy(sortAndSlice);
    }
831217
@Override
    public Schema transform(Schema schema) {
        int nCols = schema.numColumns();
        List<ColumnMetaData> meta = schema.getColumnMetaData();
        List<ColumnMetaData> newMeta = new ArrayList<>(nCols);
        newMeta.addAll(meta);
        newMeta.add(new StringMetaData(outputColumnName));
        return schema.newSchema(newMeta);
    }
263664
public AbstractExpression replaceWithTVE(
            Map<AbstractExpression, Integer> aggTableIndexMap,
            Map<Integer, ParsedColInfo> indexToColumnMap) {
        Integer ii = aggTableIndexMap.get(this);
        if (ii != null) {
            ParsedColInfo col = indexToColumnMap.get(ii);
            TupleValueExpression tve = new TupleValueExpression(
                    col.m_tableName, col.m_tableAlias,
                    col.m_columnName, col.m_alias,
                    this, ii);
            if (this instanceof TupleValueExpression) {
                tve.setOrigStmtId(((TupleValueExpression)this).getOrigStmtId());
            }
            // To prevent pushdown of LIMIT when ORDER BY references an agg. ENG-3487.
            if (hasAnySubexpressionOfClass(AggregateExpression.class)) {
                tve.setHasAggregate(true);
            }

            return tve;
        }

        AbstractExpression lnode = null;
        AbstractExpression rnode = null;
        if (m_left != null) {
            lnode = m_left.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
        }
        if (m_right != null) {
            rnode = m_right.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
        }

        ArrayList<AbstractExpression> newArgs = null;
        boolean changed = false;
        if (m_args != null) {
            newArgs = new ArrayList<>();
            for (AbstractExpression expr: m_args) {
                AbstractExpression ex = expr.replaceWithTVE(aggTableIndexMap, indexToColumnMap);
                newArgs.add(ex);
                if (ex != expr) {
                    changed = true;
                }
            }
        }

        if (m_left != lnode || m_right != rnode || changed) {
            AbstractExpression resExpr = clone();
            resExpr.setLeft(lnode);
            resExpr.setRight(rnode);
            resExpr.setArgs(newArgs);
            return resExpr;
        }

        return this;
    }
984901
def resolve_virtual_columns(self, *names):
        
        from .views.legacy import get_field_definition
        virtual_columns = {}
        for name in names:
            field = get_field_definition(name)
            column = TextColumn(sources=field.fields, label=field.pretty_name,
                                processor=field.callback)
            column.name = field.pretty_name if field.pretty_name else field.fields[0]
            virtual_columns[name] = column

        # Make sure it's in the same order as originally defined
        new_columns = OrderedDict()
        for name in self._meta.columns:  # Can't use self.config yet, hasn't been generated
            if self.columns.get(name):
                column = self.columns[name]
            else:
                column = virtual_columns[name]
            new_columns[column.name] = column
        self.columns = new_columns
959550
function resolveSchema(root, ref) {
  /* jshint validthis: true */
  var p = URI.parse(ref)
    , refPath = _getFullPath(p)
    , baseId = getFullPath(this._getId(root.schema));
  if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
    var id = normalizeId(refPath);
    var refVal = this._refs[id];
    if (typeof refVal == 'string') {
      return resolveRecursive.call(this, root, refVal, p);
    } else if (refVal instanceof SchemaObject) {
      if (!refVal.validate) this._compile(refVal);
      root = refVal;
    } else {
      refVal = this._schemas[id];
      if (refVal instanceof SchemaObject) {
        if (!refVal.validate) this._compile(refVal);
        if (id == normalizeId(ref))
          return { schema: refVal, root: root, baseId: baseId };
        root = refVal;
      } else {
        return;
      }
    }
    if (!root.schema) return;
    baseId = getFullPath(this._getId(root.schema));
  }
  return getJsonPointer.call(this, p, baseId, root.schema, root);
}
836522
protected SchemaNode resolveSchemaNode(final Map<String, SchemaNode> schemaNodes, final App app, final URI uri) throws FrameworkException {

		// find schema nodes for the given source and target nodes
		final Object source = root.resolveURI(uri);
		if (source != null && source instanceof StructrTypeDefinition) {

			return (SchemaNode)((StructrTypeDefinition)source).getSchemaNode();

		} else {

			if (uri.isAbsolute()) {

				final Class type = StructrApp.resolveSchemaId(uri);
				if (type != null) {

					return schemaNodes.get(type.getSimpleName());
				}
			}
		}

		return null;
	}