Flatten a structured projection (structure projections support for
        projections of (to be) dereferenced fields.
17088
def _flatten_projection(cls, projection):
        

        # If `projection` is empty return a full projection based on `_fields`
        if not projection:
            return {f: True for f in cls._fields}, {}, {}

        # Flatten the projection
        flat_projection = {}
        references = {}
        subs = {}
        inclusive = True
        for key, value in deepcopy(projection).items():
            if isinstance(value, dict):

                # Build the projection value for the field (allowing for
                # special mongo directives).
                project_value = {
                    k: v for k, v in value.items()
                    if k.startswith('$') and k not in ['$ref', '$sub', '$sub.']
                }
                if len(project_value) == 0:
                    project_value = True
                else:
                    inclusive = False

                # Store a reference/sub-frame projection
                if '$ref' in value:
                    references[key] = value

                elif '$sub' in value or '$sub.' in value:
                    subs[key] = value

                    if '$sub' in value:
                        sub_frame = value['$sub']

                    if '$sub.' in value:
                        sub_frame = value['$sub.']

                    project_value = sub_frame._projection_to_paths(key, value)

                if isinstance(project_value, dict):
                    flat_projection.update(project_value)

                else:
                    flat_projection[key] = project_value

            elif key == '$ref':
                # Strip any $ref key
                continue

            elif key == '$sub' or key == '$sub.':
                # Strip any $sub key
                continue

            else:
                # Store the root projection value
                flat_projection[key] = value
                inclusive = False

        # If only references and sub-frames where specified in the projection
        # then return a full projection based on `_fields`.
        if inclusive:
            flat_projection = {f: True for f in cls._fields}

        return flat_projection, references, subs
65706
def to_representation(self, value):
        """"""
        value = apply_subfield_projection(self, value, deep=True)
        return super().to_representation(value)
1185377
def reshape_z(z, dim_z, ndim):
    

    z = np.atleast_2d(z)
    if z.shape[1] == dim_z:
        z = z.T

    if z.shape != (dim_z, 1):
        raise ValueError('z must be convertible to shape ({}, 1)'.format(dim_z))

    if ndim == 1:
        z = z[:, 0]

    if ndim == 0:
        z = z[0, 0]

    return z
956015
protected void setUpTransform(SingularValueDecomposition svd)
    {
        Vec diag = new DenseVector(dimensions);
        
        double[] s = svd.getSingularValues();
        
        for(int i = 0; i < dimensions; i++)
            diag.set(i, 1.0/Math.sqrt(s[i]+regularization));
        
        transform = new SubMatrix(svd.getU().transpose(), 0, 0, dimensions, s.length).clone();
        
        Matrix.diagMult(diag, transform);
    }
612568
def reorient_z(structure):
    
    struct = structure.copy()
    sop = get_rot(struct)
    struct.apply_operation(sop)
    return struct
576669
function flatten(matrix) {
    const res = [];

    // If the given matrix is not a matrix but a scalar.
    if (!Array.isArray(matrix)) {
        matrix = [
            [matrix]
        ];
    }

    matrix.forEach((row) => {
        // If the given matrix is a vector.
        if (!Array.isArray(row)) {
            row = [row];
        }

        row.forEach((elem) => {
            res.push(elem.real);
            res.push(elem.imag);
        });
    });
    return res;
}
528413
def _dereference(cls, documents, references):
        """"""

        # Dereference each reference
        for path, projection in references.items():

            # Check there is a $ref in the projection, else skip it
            if '$ref' not in projection:
                continue

            # Collect Ids of documents to dereference
            ids = set()
            for document in documents:
                value = cls._path_to_value(path, document)
                if not value:
                    continue

                if isinstance(value, list):
                    ids.update(value)

                elif isinstance(value, dict):
                    ids.update(value.values())

                else:
                    ids.add(value)

            # Find the referenced documents
            ref = projection.pop('$ref')
            frames = ref.many(
                {'_id': {'$in': list(ids)}},
                projection=projection
                )
            frames = {f._id: f for f in frames}

            # Add dereferenced frames to the document
            for document in documents:
                value = cls._path_to_value(path, document)
                if not value:
                    continue

                if isinstance(value, list):
                    # List of references
                    value = [frames[id] for id in value if id in frames]

                elif isinstance(value, dict):
                    # Dictionary of references
                    value = {key: frames.get(id) for key, id in value.items()}

                else:
                    value = frames.get(value, None)

                child_document = document
                keys = cls._path_to_keys(path)
                for key in keys[:-1]:
                    child_document = child_document[key]
                child_document[keys[-1]] = value
163245
def _translate_struct(inner_dict):
    """"""
    try:
        optional = inner_dict['optional'].items()
        required = inner_dict['required'].items()
    except KeyError as ex:
        raise DeserializationError("Missing key: {}".format(ex))
    except AttributeError as ex:
        raise DeserializationError(
            "Invalid Structure: {}".format(inner_dict))

    val_dict = {k: _translate(v) for k, v in required}
    val_dict.update({Optional(k): _translate(v) for k, v in optional})
    return val_dict
842921
def reshape(attrs, inputs, proto_obj):
    """"""
    if len(inputs) == 1:
        return 'reshape', attrs, inputs[0]
    reshape_shape = list(proto_obj._params[inputs[1].name].asnumpy())
    reshape_shape = [int(i) for i in reshape_shape]
    new_attrs = {'shape': reshape_shape}
    return 'reshape', new_attrs, inputs[:1]
1096026
def flatten_all_but_last(a):
  """"""
  ret = tf.reshape(a, [-1, tf.shape(a)[-1]])
  if not tf.executing_eagerly():
    ret.set_shape([None] + a.get_shape().as_list()[-1:])
  return ret
164087
def _reduction_output_shape(x, output_shape, reduced_dim):
  """"""
  if output_shape is None:
    if reduced_dim is None:
      return Shape([])
    else:
      if reduced_dim not in x.shape.dims:
        raise ValueError(
            "reduced_dim=%s not in x.shape.dims=%s" % (reduced_dim, x.shape))
      return x.shape - reduced_dim
  if reduced_dim is not None:
    if [reduced_dim] != [d for d in x.shape.dims if d not in output_shape.dims]:
      raise ValueError(
          "reduced_dim contradicts output_shape:"
          "x=%s output_shape=%s reduced_dim=%s" %
          (x, output_shape, reduced_dim))
  return output_shape
1133372
def apply_transformation(self, structure):
        
        new_structure = structure.copy()
        for prop in self.site_properties.keys():
            new_structure.add_site_property(prop, self.site_properties[prop])
        return new_structure
339943
def _flatten(n):
    """"""
    if isinstance(n, collections.Sequence):
        for x in n:
            for y in _flatten(x):
                yield y
    else:
        yield n
887153
def flatten(self) -> bk.BKTensor:
        """"""
        N = self.qubit_nb
        R = self.rank
        return bk.reshape(self.tensor, [2**N]*R)
1318119
def _flatten_projection(cls, projection):
        

        # If `projection` is empty return a full projection
        if not projection:
            return {'__': False}, {}, {}

        # Flatten the projection
        flat_projection = {}
        references = {}
        subs = {}
        inclusive = True
        for key, value in deepcopy(projection).items():
            if isinstance(value, dict):
                # Store a reference/SubFrame projection
                if '$ref' in value:
                    references[key] = value
                elif '$sub' in value or '$sub.' in value:
                    subs[key] = value
                flat_projection[key] = True

            elif key == '$ref':
                # Strip any `$ref` key
                continue

            elif key == '$sub' or key == '$sub.':
                # Strip any `$sub` key
                continue

            else:
                # Store the root projection value
                flat_projection[key] = value
                inclusive = False

        # If only references and `SubFrames` were specified in the projection
        # then return a full projection.
        if inclusive:
            flat_projection = {'__': False}

        return flat_projection, references, subs
1101032
def _flatten_dict(self, dict_):
        
        flattened_dict = {}
        for (key, value) in dict_.iteritems():
            if isinstance(value, dict):
                flattened_dict.update(self._flatten_dict(value))
            else:
                flattened_dict[key] = value
        return flattened_dict
1102412
private static Map<String, Type> flatten(Schema schema) throws SchemaConversionException {
    Map<String, Type> flattened = new LinkedHashMap<>();
    Schema recordSchema = determineType(schema);

    Preconditions.checkArgument(Type.RECORD.equals(recordSchema.getType()), "%s is expected. Schema: %s",
        Type.RECORD, recordSchema);

    for (Field f : recordSchema.getFields()) {
      produceFlattenedHelper(f, flattened);
    }
    return flattened;
  }