sanitize a name/namespace record before returning it.
        * canonicalize it
        * remove quirk fields
555302
def sanitize_rec(self, rec):
        
        opcode = rec['opcode']
        canonical_op = op_canonicalize(opcode, rec)

        # don't return internally-used quirk fields
        quirk_fields = op_get_quirk_fields(opcode)
        for f in quirk_fields:
            if f in canonical_op:
                del canonical_op[f]

        # if we have a 'token_fee', make it a string
        if 'token_fee' in canonical_op:
            canonical_op['token_fee'] = str(canonical_op['token_fee'])

        canonical_op['opcode'] = opcode
        return canonical_op
481751
def sanitize(func):
    

    def wrapper(*args, **kwargs):
        return normalize('NFC', func(*args, **kwargs))
    return wrapper
1175735
def CleanName(name):
        """"""
        name = re.sub('[^_A-Za-z0-9]', '_', name)
        if name[0].isdigit():
            name = '_%s' % name
        while keyword.iskeyword(name):
            name = '%s_' % name
        # If we end up with __ as a prefix, we'll run afoul of python
        # field renaming, so we manually correct for it.
        if name.startswith('__'):
            name = 'f%s' % name
        return name
983435
def sanitize(meta, diagnostics=False):
    
    bad_encodings, bad_fields = set(), set()

    def sane_encoding(field, text):
        "Transcoding helper."
        for encoding in ('utf-8', meta.get('encoding', None), 'cp1252'):
            if encoding:
                try:
                    u8_text = text.decode(encoding).encode("utf-8")
                    if encoding != 'utf-8':
                        bad_encodings.add(encoding)
                        bad_fields.add(field)
                    return u8_text
                except UnicodeError:
                    continue
        else:
            # Broken beyond anything reasonable
            bad_encodings.add('UNKNOWN/EXOTIC')
            bad_fields.add(field)
            return str(text, 'utf-8', 'replace').replace('\ufffd', '_').encode("utf-8")

    # Go through all string fields and check them
    for field in ("comment", "created by"):
        if field in meta:
            meta[field] = sane_encoding(field, meta[field])

    meta["info"]["name"] = sane_encoding('info name', meta["info"]["name"])

    for entry in meta["info"].get("files", []):
        entry["path"] = [sane_encoding('file path', i) for i in entry["path"]]

    return (meta, bad_encodings, bad_fields) if diagnostics else meta
663589
def sanitize(self):
        '''
        
        '''
        super(MapReferralMessage, self).sanitize()

        # WARNING: http://tools.ietf.org/html/draft-ietf-lisp-ddt-00
        # does not define this field so the description is taken from
        # http://tools.ietf.org/html/draft-ietf-lisp-24
        #
        # Nonce: An 8-octet random value created by the sender of the Map-
        # Request.  This nonce will be returned in the Map-Reply.  The
        # security of the LISP mapping protocol depends critically on the
        # strength of the nonce in the Map-Request message.  The nonce
        # SHOULD be generated by a properly seeded pseudo-random (or strong
        # random) source.  See [RFC4086] for advice on generating security-
        # sensitive random data.
        if len(bytes(self.nonce)) != 8:
            raise ValueError('Invalid nonce')

        # Map-Referral Records:  When the M bit is set, this field is the size
        # of a single "Record" in the Map-Reply format.  This Map-Reply record
        # contains the EID-to-RLOC mapping entry associated with the Source
        # EID.  This allows the ETR which will receive this Map-Request to
        # cache the data if it chooses to do so.
        for record in self.records:
            if not isinstance(record, MapReferralRecord):
                raise ValueError('Invalid record')

            record.sanitize()
743884
def _sanitizer(self, obj):
        """"""
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()
        if hasattr(obj, "to_dict"):
            return obj.to_dict()
        return obj
843620
def normalize_header(name)
      return name if name =~ CANONICAL_NAME_RE

      normalized = name.split(/[\-_]/).each(&:capitalize!).join("-")

      return normalized if normalized =~ COMPLIANT_NAME_RE

      raise HeaderError, "Invalid HTTP header field name: #{name.inspect}"
    end
639752
function sanitizeKey(obj) {
  if (typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) return obj;
  if (obj === null) return null;
  if (obj instanceof Boolean) return obj;
  if (obj instanceof Number) return obj;
  if (obj instanceof Buffer) return obj.toString();
  for (const k in obj) {
    const escapedK = sjs(k);
    if (escapedK !== k) {
      obj[escapedK] = sanitizeKey(obj[k]);
      obj[k] = undefined;
    } else {
      obj[k] = sanitizeKey(obj[k]);
    }
  }
  return obj;
}
823588
def sanitize_attributes(*args, &block)
      if (args.last && args.last.is_a?(Hash))
        options = args.pop
      end
      options ||= {}
      unless @sanitize_hook_already_defined
        include InstanceMethods
        extend ClassMethods

        if options[:before_validation]
          before_validation :sanitize!
        else
          before_save :sanitize!
        end

        cattr_accessor :sanitizable_attribute_hash
        cattr_accessor :sanitization_block_array
        self.sanitizable_attribute_hash ||= {}
        self.sanitization_block_array ||= []

        @sanitize_hook_already_defined = true
      end

      if block
        self.sanitization_block_array << block
        block = self.sanitization_block_array.index(block)
      else
        block = nil
      end

      args.each do |attr|
        self.sanitizable_attribute_hash[attr] = block
      end

      true
    end
678841
def _sanitize_field_name(self, field_name):
        
        field_name = field_name.replace(self._field_prefix, '')
        return field_name.replace('.', '_').replace('-', '_').lower()
185078
def normalize_name(s):
    
    # Normalize the string into a byte string form
    s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore')
    # Remove the byte string and quotes from the string
    s = str(s)[2:-1]
    return s
578390
def cleanup_key(name):
    
    name = name.lstrip('+')
    is_keypad = name.startswith('KP_')
    for mod in ('Meta_', 'Control_', 'dead_', 'KP_'):
        if name.startswith(mod):
            name = name[len(mod):]

    # Dumpkeys is weird like that.
    if name == 'Remove':
        name = 'Delete'
    elif name == 'Delete':
        name = 'Backspace'

    if name.endswith('_r'):
        name = 'right ' + name[:-2]
    if name.endswith('_l'):
        name = 'left ' + name[:-2]


    return normalize_name(name), is_keypad
463712
function SanitizeCtx(ctx) {
  let r = {};
  for (const key in ctx) {
    if (!key.startsWith('_')) {
      r[key] = ctx[key];
    }
  }
  return r;
}
428252
def sanitize_metadata(self, metadata, replace_hyphen_with="-"):
        """"""
        return {str(k).replace("-", replace_hyphen_with): str(v)
                for k, v in (metadata or {}).items() if v is not None}
10415
private function sanitize($name)
  {
    switch ( strtolower($this->quoting) )
    {
      case 'none':
        $ldelim = $rdelim = '';
        break;
      case 'mysql':
        $ldelim = $rdelim = '`';
        break;
      case 'sql':
      case 'sqlite':
        $ldelim = $rdelim = '"';
        break;
      case 'mssql':
        $ldelim = '[';
        $rdelim = ']';
        break;
    }
    
    // If the argument is an SQL-function like SUM(), COUNT() we need to extract field name from it
    if ( false !== strpos($name, '(') )
    {
      // $matches[0]=>original string, [1]=>first substitution(SQL-function), [2]=>SQL-function arg, [3]=>')'
      preg_match('/^(.+\()(.+)(\))$/', $name, $matches);
      $field = $matches[2];
    }
    else
      $field = $name;

    $valueArr = explode('.', $field, 2);
    foreach ($valueArr as $key => $subValue)
      $valueArr[$key] = trim($subValue) == '*' ? $subValue : $ldelim . trim($subValue) . $rdelim;

    $result = implode('.', $valueArr);
    if ( isset($matches) )
      return $matches[1] . $result . $matches[3];

    return $result;
  }
1000150
def sanitize(value):
    """"""

    value = unicodedata.normalize('NFKD', value)
    value = value.strip()
    value = re.sub('[^./\w\s-]', '', value)
    value = re.sub('[-\s]+', '-', value)

    return value
1075021
def _clean_name(self, prefix, obj):
        """"""
        return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))