Transforms long address field columns into shorter aliases.

This is used in field_handlers.feature for testing if lengthy field:column
combinations can be shortened to more human friendly aliases.

@Transform table:name,mail,street,city,postcode,country
558679
public function castUsersTable(TableNode $user_table) {
    $aliases = array(
      'country' => 'field_post_address:country',
      'city' => 'field_post_address:locality',
      'street' => 'field_post_address:thoroughfare',
      'postcode' => 'field_post_address:postal_code',
    );

    // The first row of the table contains the field names.
    $table = $user_table->getTable();
    reset($table);
    $first_row = key($table);

    // Replace the aliased field names with the actual ones.
    foreach ($table[$first_row] as $key => $alias) {
      if (array_key_exists($alias, $aliases)) {
        $table[$first_row][$key] = $aliases[$alias];
      }
    }

    return new TableNode($table);
  }
1105176
def to_s(with_title=false)
      lines = [liner_note]
      (self.addresses || {}).each_pair do |address,rules|
        lines << "%18s -> %s" % [address.to_s, rules.collect { |p| p.to_s}.join(', ')]
      end
      lines.join($/)
    end
1188557
def address_inline(request, prefix="", country_code=None, template_name="postal/form.html"):
    
    
    country_prefix = "country"
    prefix = request.POST.get('prefix', prefix)
    
    if prefix:
        country_prefix = prefix + '-country'
    
    country_code = request.POST.get(country_prefix, country_code)
    form_class = form_factory(country_code=country_code)
    
    if request.method == "POST":
        data = {}
        for (key, val) in request.POST.items():
            if val is not None and len(val) > 0:
                data[key] = val
        data.update({country_prefix: country_code})
        
        form = form_class(prefix=prefix, initial=data)
    else:
        form = form_class(prefix=prefix)
        
    return render_to_string(template_name, RequestContext(request, {
        "form": form,
        "prefix": prefix,
    }))
304108
def fill_addressfields(self, row, obj):
        
        addresses = {}
        for add_type in ['Physical', 'Postal', 'Billing', 'CountryState']:
            addresses[add_type] = {}
            for key in ['Address', 'City', 'State', 'District', 'Zip', 'Country']:
                addresses[add_type][key.lower()] = str(row.get("%s_%s" % (add_type, key), ''))

        if addresses['CountryState']['country'] == '' \
            and addresses['CountryState']['state'] == '':
            addresses['CountryState']['country'] = addresses['Physical']['country']
            addresses['CountryState']['state'] = addresses['Physical']['state']

        if hasattr(obj, 'setPhysicalAddress'):
            obj.setPhysicalAddress(addresses['Physical'])
        if hasattr(obj, 'setPostalAddress'):
            obj.setPostalAddress(addresses['Postal'])
        if hasattr(obj, 'setCountryState'):
            obj.setCountryState(addresses['CountryState'])
        if hasattr(obj, 'setBillingAddress'):
            obj.setBillingAddress(addresses['Billing'])
610236
def address(self, street, city=None, state=None, zipcode=None, **kwargs):
        ''''''
        fields = {
            'street': street,
            'city': city,
            'state': state,
            'zip': zipcode,
        }

        return self._fetch('address', fields, **kwargs)
484663
private function removeAdditionalTableDuplicateFields()
    {
        $columns = $this->getSelect()->getPart(\Zend_Db_Select::COLUMNS);

        foreach ($columns as $idx => $column) {
            if ($column[0] == 'additional_table' && $column[1] == "*") {
                unset($columns[$idx]);
            }
        }

        $this->getSelect()->setPart(\Zend_Db_Select::COLUMNS, $columns);

        foreach ($this->getAdditionalTableFields() as $fieldName) {
            $this->getSelect()->columns([$fieldName => sprintf("additional_table.%s", $fieldName)]);
        }

        return $this;
    }
39059
def _replace(self, **kwds):
        ''
        result = self._make(map(kwds.pop, self._fields, self))
        
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        
        return result
466552
def _normalize_rename(self, mapping, schema, field):
        
        if 'rename' in schema[field]:
            mapping[schema[field]['rename']] = mapping[field]
            del mapping[field]
501132
static public function formatQueryTableAlias($data=null, $table_alias=null, $in_fields=null)
    {
        if ($data && isset($table_alias)) {
            if (is_array($data)) {
                foreach ($data as $k => $v) {
                    if (!is_numeric($k) && strpos($k, '.') === false) {
                        if(isset($in_fields) && !in_array($k, $in_fields)) continue;
                        
                        $data[$table_alias . '.' . $k] = $v;
                        unset($data[$k]);
                    }
                }
            } elseif (strpos($data, ',')) {
                $data = explode(',', $data);
                foreach ($data as $k => $v) {
                    $v = trim($v);
                    if(isset($in_fields) && !in_array($v, $in_fields)) continue;
                    
                    $data[$k] = $table_alias . '.' . $v;
                }
                $data = implode(',', $data);
            } elseif (strpos($data, '.') === false) {
                $data = trim($data);
                if(isset($in_fields) && in_array($data, $in_fields)) {
                    $data = $table_alias . '.' . $data;
                }
            }
        }
        
        return $data;
    }
280299
def transform(fields, function, *tables):
    ""

    new_table = Table(fields=fields)

    for table in tables:
        for row in filter(bool, map(lambda row: function(row, table), table)):
            new_table.append(row)

    return new_table
511084
def change_column_length(table: Table, column: Column, length: int, engine: Engine) -> None:
    
    if column.type.length < length:
        print("Changing length of {} from {} to {}".format(column, column.type.length, length))
        column.type.length = length
        column_name = column.name
        column_type = column.type.compile(engine.dialect)
        engine.execute('ALTER TABLE {table} ALTER COLUMN {column_name} TYPE {column_type}'.format(**locals()))
626458
def range_for column_name, field_name
      column = @@bitfields[column_name]
      raise ArgumentError, "Unknown column for bitfield: #{column_name}" if column.nil?
      return column[field_name] if column[field_name]
      raise ArugmentError, "Unknown field: #{field_name} for column #{column_name}"
    end
571893
def leaves(self, column_name):
        
        clean_name = unnest_path(column_name)

        if clean_name != column_name:
            clean_name = column_name
            cleaner = lambda x: x
        else:
            cleaner = unnest_path


        columns = self.columns
        # TODO: '.' IMPLIES ALL FIELDS FROM ABSOLUTE PERPECTIVE, ALL OTHERS ARE A RELATIVE PERSPECTIVE
        # TODO: HOW TO REFER TO FIELDS THAT MAY BE SHADOWED BY A RELATIVE NAME?
        for path in reversed(self.query_path) if clean_name == '.' else self.query_path:
            output = [
                c
                for c in columns
                if (
                    (c.name != "_id" or clean_name == "_id") and
                    (
                        (c.jx_type == EXISTS and column_name.endswith("." + EXISTS_TYPE)) or
                        c.jx_type not in OBJECTS or
                        (clean_name == '.' and c.cardinality == 0)
                    ) and
                    startswith_field(cleaner(relative_field(c.name, path)), clean_name)
                )
            ]
            if output:
                return set(output)
        return set()
1355848
def normalize(self, address, **kwargs):
        """"""
        # TODO: normalize well-known parts like "Street", "Road", etc.
        # TODO: consider using https://github.com/openvenues/pypostal
        addresses = super(AddressType, self).normalize(address, **kwargs)
        return addresses
719179
def onelineaddress(self, address, **kwargs):
        '''
        '''
        fields = {
            'address': address,
        }

        return self._fetch('onelineaddress', fields, **kwargs)
1363678
def alias_field(model, field):
    
    for part in field.split(LOOKUP_SEP)[:-1]:
        model = associate_model(model,part)
    return model.__name__ + "-" + field.split(LOOKUP_SEP)[-1]
99647
def alts_columns_used(self):
        
        return list(tz.unique(tz.concat(
            m.alts_columns_used() for m in self.models.values())))