construct a $varName (rolemap) isa $typeVariable relation
@param varName            variable name
@param relationPlayers collection of rolePlayer-roleType mappings
@return corresponding {@link Statement}
559168
private Statement relationPattern(Variable varName, Collection<RelationProperty.RolePlayer> relationPlayers) {
        Statement var = new Statement(varName);
        for (RelationProperty.RolePlayer rp : relationPlayers) {
            Statement rolePattern = rp.getRole().orElse(null);
            var = rolePattern != null? var.rel(rolePattern, rp.getPlayer()) : var.rel(rp.getPlayer());
        }
        return var;
    }
1317528
@Override
  public void recordVariableUpdate(VariableInstanceEntity variable) {
    if (isHistoryLevelAtLeast(HistoryLevel.ACTIVITY)) {
      HistoricVariableInstanceEntity historicProcessVariable = getEntityCache().findInCache(HistoricVariableInstanceEntity.class, variable.getId());
      if (historicProcessVariable == null) {
        historicProcessVariable = getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceByVariableInstanceId(variable.getId());
      }

      if (historicProcessVariable != null) {
        getHistoricVariableInstanceEntityManager().copyVariableValue(historicProcessVariable, variable);
      } else {
        getHistoricVariableInstanceEntityManager().copyAndInsert(variable);
      }
    }
  }
788842
private static void buildTypeVariableMap(ParameterizedType type,
                                             Map<TypeVariable<?>, Type> typeVariableMap) {
        if (type.getRawType() instanceof Class) {
            TypeVariable<?>[] typeVariables = ((Class<?>) type.getRawType()).getTypeParameters();
            Type[] typeArguments = type.getActualTypeArguments();

            for (int i = 0; i < typeArguments.length; i++) {
                TypeVariable<?> variable = typeVariables[i];
                Type typeArgument = typeArguments[i];

                if (typeArgument instanceof Class) {
                    typeVariableMap.put(variable, typeArgument);
                } else if (typeArgument instanceof GenericArrayType) {
                    typeVariableMap.put(variable, typeArgument);
                } else if (typeArgument instanceof ParameterizedType) {
                    typeVariableMap.put(variable, typeArgument);
                } else if (typeArgument instanceof TypeVariable) {
                    TypeVariable<?> typeVariableArgument = (TypeVariable<?>) typeArgument;
                    Type resolvedType = typeVariableMap.get(typeVariableArgument);
                    if (resolvedType == null)
                        resolvedType = resolveBound(typeVariableArgument);
                    typeVariableMap.put(variable, resolvedType);
                }
            }
        }
    }
203195
public void setRelationType(String relationType) {

        try {
            m_relationType = CmsRelationType.valueOf(relationType);
        } catch (Throwable e) {
            setThrowable(e);
        }
    }
939470
public function handle(VariableRepositoryInterface $variables)
    {
        if (!$group = $variables->group($this->group)) {
            return null;
        }

        return (new Decorator())->decorate($group)->{$this->field};
    }
502780
public function writeVariableValue(Variable $variable, $valueType = self::RW_VALUE)
    {
        switch ($valueType) {
            case self::RW_DEFAULTVALUE:
                $getterToCall = 'getDefaultValue';
                break;
                
            case self::RW_CORRECTRESPONSE:
                $getterToCall = 'getCorrectResponse';
                break;
                
            default:
                $getterToCall = 'getValue';
        }
        
        try {
            $value = call_user_func(array($variable, $getterToCall));
            $cardinality = $variable->getCardinality();
            $baseType = $variable->getBaseType();

            if (is_null($value) === true) {
                $this->writeBoolean(true);

                return;
            }

            // Non-null value.
            $this->writeBoolean(false);

            if ($cardinality === Cardinality::RECORD) {
                // is-scalar
                $this->writeBoolean(false);

                // count
                $this->writeShort(count($value));

                // content
                foreach ($value as $k => $v) {
                    $this->writeRecordField(array($k, $v), is_null($v));
                }
            } else {
                $toCall = 'write' . ucfirst(BaseType::getNameByConstant($baseType));

                if ($cardinality === Cardinality::SINGLE) {
                    // is-scalar
                    $this->writeBoolean(true);

                    // content
                    $this->$toCall(($value instanceof QtiScalar) ? $value->getValue() : $value);
                } else {
                    // is-scalar
                    $this->writeBoolean(false);

                    // count
                    $this->writeShort(count($value));

                    // MULTIPLE or ORDERED
                    foreach ($value as $v) {
                        if (is_null($v) === false) {
                            $this->writeBoolean(false);
                            $this->$toCall(($v instanceof QtiScalar) ? $v->getValue() : $v);
                        } else {
                            $this->writeBoolean(true);
                        }
                    }
                }
            }
        } catch (BinaryStreamAccessException $e) {
            $msg = "An error occured while writing a Variable value.";
            throw new QtiBinaryStreamAccessException($msg, $this, QtiBinaryStreamAccessException::VARIABLE, $e);
        }
    }
91866
private VarSymbol makeSyntheticVar(long flags, String name, Type type, Symbol owner) {
        return makeSyntheticVar(flags, names.fromString(name), type, owner);
    }
860760
public function toQuery( $variableSet, $factVariableBinding )
	{
		$clauses = array();

		$dimensionClause = "";
		if ( $this->dimension )
		{
			// $qname = qname( $this->dimension );
			$dimensionClause = "fn:QName('{$this->dimension['namespace']}','{$this->dimension['name']}')";
		}
		else if ( $this->dimensionExpression )
		{
			$dimensionClause = $this->dimensionExpression;
		}
		else
		{
			return "false()";
		}

		if ( ! $this->members )
		{
			return "xfi:fact-has-explicit-dimension(.,$dimensionClause)";
		}

		foreach ( $this->members as $member )
		{
			$memberClause = "";
			if ( isset( $member['qname'] ) )
			{
				// $qname = qname( $member['qname'] );
				$memberClause = "fn:QName('{$member['qname']['namespace']}','{$member['qname']['name']}')";
			}
			else if ( isset( $member['qnameExpression'] ) )
			{
				$memberClause = $member['qnameExpression'];
			}
			elseif ( isset( $member['variable'] ) )
			{
				// $memberClause = "fn:QName('{$member['variable']['namespace']}','{$member['variable']['name']}')";
				// TODO Can the QName resulting from this query be determined once for this set of aspect facts?
				//      If the implied variable can depend on other variables that are linked to the current fact
				//      then the QName cannot be determined upfront.  However it formula rule prohibit such a
				//      relationship then it can.
				//      For now assume the worst case and have the clause evaluated for every fact
				$variable = $member['variable']['originalPrefix']
					? "\${$member['variable']['originalPrefix']}:{$member['variable']['name']}"
					: "\${$member['variable']['name']}";

				// $variable is 'the current fact'
				$memberClause = "xfi:fact-explicit-dimension-value( $variable, $dimensionClause )";
			}
			else
			{
				continue;
			}

			// Dimensions filter spec 2.1 states:
			// If a filter member does not contain a filter-member linkrole, arcrole and axis, then the only
			// domain member in its filter-member set is the domain member identified by the filter-member value.
			if ( ! isset( $member['arcrole'] ) || ! isset( $member['axis'] ) || ! isset( $member['linkrole'] ) )
			{
				if ( isset( $member['axis'] ) && in_array( $member['axis'], array( 'DRS-child', 'DRS-descendant' ) ) )
				{
					$axis = isset( $member['axis'] ) ? $member['axis'] : "";
					$linkrole = isset( $member['linkrole'] ) ? $member['linkrole'] : "";
					$xpath = "( if (xfi:fact-has-explicit-dimension(.,$dimensionClause)) then " .
							 "( some \$member in xfi:filter-member-DRS-selection($dimensionClause,fn:node-name(.),$memberClause,'$linkrole','$axis') satisfies (xfi:fact-explicit-dimension-value(.,$dimensionClause) eq \$member) )" .
							 " else fn:false() )";
					$clauses[] = $xpath;
				}
				else
				{
					$clauses[] = "xfi:fact-has-explicit-dimension-value(.,$dimensionClause,$memberClause)";
				}
			}
			else
			{
				$arcrole = isset( $member['arcrole'] ) ? $member['arcrole'] : "";
				$axis = isset( $member['axis'] ) ? $member['axis'] : "";
				$linkrole = isset( $member['linkrole'] ) ? $member['linkrole'] : "";

				// TODO This needs optimizing otherwise the whole expression is evaluated for every fact element.
				$xpath = "( if (xfi:fact-has-explicit-dimension(.,$dimensionClause)) then " .
						 "( some \$member in xfi:filter-member-network-selection($dimensionClause,$memberClause,'$linkrole','$arcrole','$axis') satisfies (xfi:fact-explicit-dimension-value(.,$dimensionClause) eq \$member) )" .
						 " else fn:false() )";
				$clauses[] = $xpath;
			}
		}

		return implode( " or ", $clauses );

	}
434946
private void processTypeVariables(TypeVariable<?>[] variables, Type[] values) {
        for (int i = 0; i < variables.length; i++) {
            processTypeVariable(variables[i], values[i]);
        }
    }
754247
function typeVarNames(t) {
    return Z.concat (
      t.type === VARIABLE ? [t.name] : [],
      Z.chain (function(k) { return typeVarNames (t.types[k]); }, t.keys)
    );
  }
108431
protected static CmsRelationType getRelationType(String typeName) {

        for (CmsRelationType relType : CmsRelationType.getAll()) {
            if (relType.getName().equalsIgnoreCase(typeName)) {
                return relType;
            }
        }
        return null;
    }
1346367
protected void addExportVariableIfPresent(String variable, String typeName) {
        String expVar = findPropertyValue(variable).getLatestValue();
        if(expVar != null && !expVar.isEmpty()) {
            addVariable(new CodeVariableBuilder().exportOnly().variableType(typeName).variableName(expVar));
        }
    }
999678
public static Map<String,String> formatExportedVars( Instance instance ) {

		// The map we will return
		Map<String, String> exportedVars = new HashMap<> ();

		// Iterate over the instance and its ancestors.
		// There is no loop in parent relations, so no risk of conflict in variable names.
		for( Instance inst = instance; inst != null; inst = inst.getParent()) {

			String prefix = "";
			if( inst != instance )
				prefix = "ANCESTOR_" + inst.getComponent().getName() + "_";

			Map<String,String> exports = InstanceHelpers.findAllExportedVariables( inst );
			for(Entry<String, String> entry : exports.entrySet()) {

				// FIXME: removing the prefix may result in inconsistencies when a facet
				// and a component export variables with the same "local name".
				// And this has nothing to do with ancestors. This is about inheritance.
				String vname = prefix + VariableHelpers.parseVariableName( entry.getKey()).getValue();
				vname = vname.replaceAll( "(-|%s)+", "_" );
				exportedVars.put( vname, entry.getValue());
			}
		}

		return exportedVars;
	}
833170
public static Set<Fragment> inferRelationTypes(TransactionOLTP tx, Set<Fragment> allFragments) {

        Set<Fragment> inferredFragments = new HashSet<>();

        Map<Variable, Type> labelVarTypeMap = getLabelVarTypeMap(tx, allFragments);
        if (labelVarTypeMap.isEmpty()) return inferredFragments;

        Multimap<Variable, Type> instanceVarTypeMap = getInstanceVarTypeMap(allFragments, labelVarTypeMap);

        Multimap<Variable, Variable> relationRolePlayerMap = getRelationRolePlayerMap(allFragments, instanceVarTypeMap);
        if (relationRolePlayerMap.isEmpty()) return inferredFragments;

        // for each type, get all possible relation type it could be in
        Multimap<Type, RelationType> relationMap = HashMultimap.create();
        labelVarTypeMap.values().stream().distinct().forEach(
                type -> addAllPossibleRelations(relationMap, type));

        // inferred labels should be kept separately, even if they are already in allFragments set
        Map<Label, Statement> inferredLabels = new HashMap<>();
        relationRolePlayerMap.asMap().forEach((relationVar, rolePlayerVars) -> {

            Set<Type> possibleRelationTypes = rolePlayerVars.stream()
                    .filter(instanceVarTypeMap::containsKey)
                    .map(rolePlayer -> getAllPossibleRelationTypes(
                            instanceVarTypeMap.get(rolePlayer), relationMap))
                    .reduce(Sets::intersection).orElse(Collections.emptySet());

            //TODO: if possibleRelationTypes here is empty, the query will not match any data
            if (possibleRelationTypes.size() == 1) {

                Type relationType = possibleRelationTypes.iterator().next();
                Label label = relationType.label();

                // add label fragment if this label has not been inferred
                if (!inferredLabels.containsKey(label)) {
                    Statement labelVar = var();
                    inferredLabels.put(label, labelVar);
                    Fragment labelFragment = Fragments.label(new TypeProperty(label.getValue()), labelVar.var(), ImmutableSet.of(label));
                    inferredFragments.add(labelFragment);
                }

                // finally, add inferred isa fragments
                Statement labelVar = inferredLabels.get(label);
                IsaProperty isaProperty = new IsaProperty(labelVar);
                EquivalentFragmentSet isaEquivalentFragmentSet = EquivalentFragmentSets.isa(isaProperty,
                        relationVar, labelVar.var(), relationType.isImplicit());
                inferredFragments.addAll(isaEquivalentFragmentSet.fragments());
            }
        });

        return inferredFragments;
    }
1370523
public static EquivalentFragmentSet relates(VarProperty varProperty, Variable relationType, Variable role) {
        return new AutoValue_RelatesFragmentSet(varProperty, relationType, role);
    }
937525
public function get(string $variableName = null, int $type = Variables::TYPE_STRING)
    {
        if ($variableName === null) {
            throw new BadMethodCallException('Variable name must be specified');
        }
        if (isset($this->variables[$variableName])) {
            return $this->cast($this->variables[$variableName], $type);
        }
        return $this->cast(null, $type);
    }
607449
private static void recordVariable(final TypeVariable var, final List<TypeVariable> found) {
        // prevent cycles
        if (!found.contains(var)) {
            found.add(var);
            for (Type type : var.getBounds()) {
                findVariables(type, found);
            }
        }
    }