Convert an archetypes reference in src/src_relation to a UIDReference
    in dst/fieldname.
350851
def touidref(src, dst, src_relation, src_portal_type, fieldname):
    
    field = dst.getField(fieldname)
    refs = src.getRefs(relationship=src_relation)

    if len(refs) == 1:
        value = get_uid(refs[0])
    elif len(refs) > 1:
        value = filter(lambda x: x, [get_uid(ref) for ref in refs])
    else:
        value = field.get(src)
    if not value:
        value = ''
    if not field:
        raise RuntimeError('Cannot find field %s/%s' % (fieldname, src))
    if field.required and not value:
        logger.exception('Required %s field %s/%s has no value' %
                         (src.portal_type, src, fieldname))
    field.set(src, value)
216742
def gen_stm(src, dst):
        
        return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst)
1000144
def gen_str(src, dst):
        
        return ReilBuilder.build(ReilMnemonic.STR, src, ReilEmptyOperand(), dst)
1066155
private Object convertObjectToSingleValue(Object rawValue, ExtendedAttributeDefinition attrDef, EvaluationContext context, int index,
                                              boolean ignoreWarnings) throws ConfigEvaluatorException {
        if (rawValue instanceof String) {
            return convertStringToSingleValue((String) rawValue, attrDef, context, ignoreWarnings);
        } else if (rawValue instanceof ConfigElement.Reference) {
            ConfigElement.Reference reference = processReference((ConfigElement.Reference) rawValue, context, ignoreWarnings);
            if (attrDef != null && attrDef.getType() == MetaTypeFactory.PID_TYPE) {
                return evaluateReference(reference.getId(), attrDef, context);
            } else {
                return evaluateReference(reference, context);
            }
        } else if (rawValue instanceof ConfigElement) {
            return convertConfigElementToSingleValue((ConfigElement) rawValue, attrDef, context, index, ignoreWarnings);
        } else {
            throw new IllegalStateException("Unsupported type: " + rawValue.getClass());
        }
    }
529714
public static KeyValue getReferenceKeyValue(byte[] rowkey, String propertyName,
            String schemaName, List<BeanId> refs, UniqueIds uids) {
        final byte[] pid = uids.getUsid().getId(propertyName);
        final byte[] sid = uids.getUsid().getId(schemaName);
        final byte[] qual = new byte[] { sid[0], sid[1], pid[0], pid[1] };
        final byte[] iids = getIids2(refs, uids);
        return new KeyValue(rowkey, REF_COLUMN_FAMILY, qual, iids);
    }
542470
private function loadReferences()
    {

        // References defined in pg_catalog
        $sql = new Raw('SELECT * FROM dev."vAttributeReferences" WHERE "isInherited" = false');
        $sql = new Raw( <<<SQL
-- Based on. http://code.google.com/p/pgutils/ but very heavily modified
-- Potentially inheritance aware/compensating. Be careful. Use the unit tests.
WITH "vRelationDescendants" as (
    SELECT
        c.oid,
        c.relname,
        (
            WITH RECURSIVE
            q( oid ) AS
            (
                SELECT
                    crd.oid
                FROM
                    pg_class crd
                WHERE
                    crd.oid = c.oid

                UNION ALL

                SELECT i.inhrelid FROM q INNER JOIN pg_inherits i ON q.oid = i.inhparent
            )
            SELECT oid FROM q WHERE oid = c.oid
        ) as childoid
    FROM
        pg_class c
    INNER JOIN
        pg_namespace n ON n.oid = c.relnamespace
    ORDER BY
        n.nspname, c.relname
), "vAttributeReferences"  as (
    SELECT
        fkr.oid <> fkrd.oid AS "isInheritedSource",
        pkr.oid <> pkrd.oid AS "isInheritedTarget",
        ( fkr.oid <> fkrd.oid OR pkr.oid <> pkrd.oid ) as "isInherited",

        fkn.nspname AS fk_namespace,
        fkr.relname AS fk_relation,
        fkr.oid AS fk_oid,
        fka.attname AS fk_column,
        fka.attnum as "fk_attnum",

        -- initByData
        fkr.oid::text || '.' || fka.attnum::text AS fk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = fkr.oid AND pg_index.indkey[0] = fka.attnum
            )
        ) AS fk_indexed,
        pkn.nspname AS pk_namespace,
        pkr.relname AS pk_relation,
        pkr.oid AS pk_oid,
        pka.attname AS pk_column,
        pka.attnum as "pk_attnum",

        -- initByData
        pkr.oid::text || '.' || pka.attnum::text AS pk_key,

        (
            EXISTS (
                SELECT
                    pg_index.indexrelid,
                    pg_index.indrelid,
                    pg_index.indkey,
                    pg_index.indclass,
                    pg_index.indnatts,
                    pg_index.indisunique,
                    pg_index.indisprimary,
                    pg_index.indisclustered,
                    pg_index.indexprs,
                    pg_index.indpred
                FROM
                    pg_index
                WHERE
                    pg_index.indrelid = pkr.oid AND
                    pg_index.indkey[0] = pka.attnum
            )
        ) AS pk_indexed,
        c.confupdtype::text || c.confdeltype::text AS ud,
        cn.nspname AS c_namespace,
        c.conname AS c_name
    FROM (
        (
            (
                (
                    (
                        (
                            (
                                pg_constraint c
                                    JOIN
                                pg_namespace cn ON cn.oid = c.connamespace
                            )
                            INNER JOIN
                                "vRelationDescendants" as fkrd ON c.conrelid = fkrd.oid
                            INNER JOIN
                                pg_class fkr ON fkr.oid = fkrd.childoid
                        )
                        JOIN
                            pg_namespace fkn ON fkn.oid = fkr.relnamespace
                    )
                    JOIN
                        pg_attribute fka ON fka.attrelid = c.conrelid AND fka.attnum = ANY (c.conkey)
                )
                INNER JOIN
                    "vRelationDescendants" as pkrd ON c.confrelid = pkrd.oid
                INNER JOIN
                    pg_class pkr ON pkr.oid = pkrd.childoid
            )
            JOIN
                pg_namespace pkn ON pkn.oid = pkr.relnamespace
        )
        JOIN
            pg_attribute pka ON pka.attrelid = c.confrelid AND pka.attnum = ANY (c.confkey)
    )
    WHERE
        c.contype = 'f'::"char" AND
        fkn.nspname = ANY( current_schemas(false) ) AND
        pkn.nspname = ANY( current_schemas(false) )
)
SELECT * FROM "vAttributeReferences" WHERE "isInherited" = false
SQL
        );

        $relationships = $this->db->query($sql);

        foreach( $relationships as $relationship ) {

            $fk = $this->pgAttributes->findOneByKey($relationship['fk_key']);
            $pk = $this->pgAttributes->findOneByKey($relationship['pk_key']);

            if( !$fk or !$pk ) {
                d_pr( $relationship );
                die();
            }

            $fk->addReference($pk);

        }

        // look for normality defined relationships
        $profiler = new Profiler( __FUNCTION__ );
        $profiler->log();

        foreach( $this->pgClasses as $relation ) {

            $tags = $relation->getTags();

            if( isset( $tags['references'] ) ) {

                foreach( $tags['references'] as $reference ) {

                    $reference = array_map( 'trim', explode( '=', $reference) );
                    $reference[1] = explode( '.', $reference[1] );

                    $fk = $relation->getAttributeByName($reference[0]);

                    // referencing
                    $pkTable = $this->pgClasses->findOneByName($reference[1][0]);
                    $pk = $pkTable->getAttributeByName($reference[1][1]);

                    $fk->addReference($pk);

                }

            }

        }

//        echo $profiler->log()->output();

    }
948616
def _set_backreferences(self, context, items, **kwargs):
        

        # Don't set any references during initialization.
        # This might cause a recursion error when calling `getRaw` to fetch the
        # current set UIDs!
        initializing = kwargs.get('_initializing_', False)
        if initializing:
            return

        # UID of the current object
        uid = api.get_uid(context)
        # current set UIDs
        raw = self.getRaw(context) or []
        # handle single reference fields
        if isinstance(raw, basestring):
            raw = [raw, ]
        cur = set(raw)
        # UIDs to be set
        new = set(map(api.get_uid, items))
        # removed UIDs
        removed = cur.difference(new)

        # Unlink removed UIDs from the source
        for uid in removed:
            source = api.get_object_by_uid(uid, None)
            if source is None:
                logger.warn("UID {} does not exist anymore".format(uid))
                continue
            self.unlink_reference(source, context)

        # Link backrefs
        for item in items:
            self.link_reference(item, context)
27472
def makename2refdct(commdct):
    """"""
    refdct = {}
    for comm in commdct: # commdct is a list of dict
        try:
            idfobj = comm[0]['idfobj'].upper()
            field1 = comm[1]
            if 'Name' in field1['field']:
                references = field1['reference']
                refdct[idfobj] = references
        except (KeyError, IndexError) as e:
            continue # not the expected pattern for reference
    return refdct
329575
def _convert_epoch_anchor(cls, reading):
        """"""

        delta = datetime.timedelta(seconds=reading.value)
        return cls._EpochReference + delta
376228
function _shallowCopyAttrs(src, dst) {
    if (Object.prototype.toString.call(src) !== '[object Object]') {
      throw new Error("Attributes are not an object: " + src);
    }
    for (var k in src) {
      dst[k] = src[k];
    }
  }
861
def transformToRef(self):
        
        if 'refxyunits' in self.pars and self.pars['refxyunits'] == 'pixels':
            log.info('Creating RA/Dec positions for reference sources...')
            self.outxy = np.column_stack([self.all_radec[0][:,np.newaxis],self.all_radec[1][:,np.newaxis]])
            skypos = self.wcs.wcs_pix2world(self.all_radec[0],self.all_radec[1],self.origin)
            self.all_radec[0] = skypos[0]
            self.all_radec[1] = skypos[1]
        else:
            log.info('Converting RA/Dec positions of reference sources from "%s" to '%self.name+
                        'X,Y positions in reference WCS...')
            self.refWCS = self.wcs
            outxy = self.wcs.wcs_world2pix(self.all_radec[0],self.all_radec[1],self.origin)
            # convert outxy list to a Nx2 array
            self.outxy = np.column_stack([outxy[0][:,np.newaxis],outxy[1][:,np.newaxis]])
110876
def _get_relative_reference(self, cursor, ref_key):
        

        magics = ["X", "Y", "Z"]

        # mapper takes magic, key, ref_key to build string
        def get_rel_key_ele(cursor_ele, ref_key_ele):
            """Returns relative key suffix for given key and reference key"""

            # cursor is current cursor position
            # ref_key is absolute target position

            diff_key_ele = ref_key_ele - cursor_ele

            if diff_key_ele == 0:
                return u""

            elif diff_key_ele < 0:
                return u"-" + str(abs(diff_key_ele))

            elif diff_key_ele > 0:
                return u"+" + str(diff_key_ele)

            else:
                msg = _("{key} seems to be no Integer")
                msg = msg.format(key=diff_key_ele)
                raise ValueError(msg)

        key_strings = []

        for magic, cursor_ele, ref_key_ele in zip(magics, cursor, ref_key):
            key_strings.append(magic +
                               get_rel_key_ele(cursor_ele, ref_key_ele))

        key_string = u", ".join(key_strings)

        return u"S[" + key_string + u"]"
110408
def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints):
    """"""
    referenced_types = set()
    for graphql_type in graphql_types.values():
        if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)):
            for _, field in graphql_type.fields.items():
                if isinstance(field.type, GraphQLList):
                    referenced_types.add(field.type.of_type.name)
    return {
        original: union
        for original, union in type_equivalence_hints.items()
        if union.name in referenced_types
    }
267918
def _ConvertToCanonicalSqlDict(self, schema, raw_dict, prefix=""):
    """"""
    flattened_dict = {}
    for k, v in iteritems(raw_dict):
      if isinstance(v, dict):
        flattened_dict.update(
            self._ConvertToCanonicalSqlDict(
                schema, v, prefix="%s%s." % (prefix, k)))
      else:
        field_name = prefix + k
        flattened_dict[field_name] = schema[field_name].convert_fn(v)
    return flattened_dict
598462
def projection(self, plain_src_name):
        """"""
        mapped = self.lookup(plain_src_name)
        if not mapped:
            return None
        fields = mapped.include_fields or mapped.exclude_fields
        if fields:
            include = 1 if mapped.include_fields else 0
            return dict((field, include) for field in fields)
        return None
1221437
def _make_key(relation):
    
    return _ReferenceKey(_lower(relation.database),
                         _lower(relation.schema),
                         _lower(relation.identifier))
1189465
def store_relation(self, src, name, dst):
        '''  '''
        self.__require_string__(name)
        #print('storing relation', src, name, dst)
        # make sure both items are stored
        self.store_item(src)
        self.store_item(dst)
        with self._write_lock:
            #print(locals())
            # run the insertion
            self._execute(
                'insert into relations select ob1.id, ?, ob2.id from objects as ob1, objects as ob2 where ob1.code=? and ob2.code=?;',
                (name, self.serialize(src), self.serialize(dst))
            )
            self.autocommit()