Clean up and apply standard formatting to variable names.
557046
def fix_var_name(var_name):
    """"""
    name = var_name.strip()
    for char in '(). /#,':
        name = name.replace(char, '_')
    name = name.replace('+', 'pos_')
    name = name.replace('-', 'neg_')
    if name.endswith('_'):
        name = name[:-1]
    return name
519058
private String replaceVariablesWithPatterns(String pattern) {
        int group = 0;
        Matcher findVariablesMatcher = variablePattern.matcher(pattern);
        while(findVariablesMatcher.find()) {
            String variable = findVariablesMatcher.group(0);
            pattern = pattern.replaceFirst(variable, "(.+)");
            variableToGroupNumber.put(variable, ++group);
        }
        return pattern;
    }
1015127
private void restoreNestedVariables() {
	if (nestedVars != null) {
	    Iterator iter = nestedVars.iterator();
	    while (iter.hasNext()) {
		String varName = (String) iter.next();
		varName = findAlias(varName);
		Object obj = originalNestedVars.get(varName);
		if (obj != null) {
		    invokingJspCtxt.setAttribute(varName, obj);
		} else {
		    invokingJspCtxt.removeAttribute(varName, PAGE_SCOPE);
		}
	    }
	}
    }
977385
def clean(self, value):
        """"""

        if not isinstance(value, six.string_types):
            raise ParameterNotValidError

        try:
            source, value = value.split('://', 1)
        except ValueError:
            raise ParameterNotValidError

        if source == 'service':
            if '@' in value:
                value, timestamp = value.split('@', 1)

                try:
                    service_time = timestamp_to_date(int(timestamp))
                except ValueError:
                    raise ParameterNotValidError
            else:
                service_time = None

            if ':' in value:
                service_name, variable_name = value.split(':', 1)
            else:
                service_name = value
                variable_name = None

            try:
                self.service = Service.objects.get(name=service_name)
            except ObjectDoesNotExist:
                raise ParameterNotValidError("Service '{}' not found".format(service_name))

            if variable_name:
                try:
                    variable = self.service.variable_set.all().get(variable=variable_name)
                except ObjectDoesNotExist:
                    raise ParameterNotValidError("Variable '{}' not found".format(variable_name))

                if service_time is not None:
                    time_index = best_fit(variable.time_stops, service_time)
                else:
                    time_index = None

                data = self.get_grid_for_variable(variable, time_index=time_index)
                return Raster(data, variable.full_extent, 1, 0, self.is_y_increasing(variable))
            else:
                return self.dataset
        else:
            raise ParameterNotValidError('Invalid source: {}'.format(source))
1037907
function replaceValuesWithVariableNames (variables, prefix) {
  const map = {}

  Object.keys(variables || {}).forEach((variableName) => {
    map[variableName] = `var(${formatVariableName(variableName, prefix)})`
  })

  return map
}
1216263
def normalize(rendered):
    """"""
    out = ''.join([line.strip()
                   for line in rendered.splitlines()
                   if line.strip()])
    out = out.replace(', ', ',')
    return out
1139144
def clean_float(v):
    """"""

    if v is None or not str(v).strip():
        return None

    return float(str(v).replace(',', ''))
867765
private static void formatNames(Iterable<List<String>> names) {
    if (names != null) {
      for (List<String> list : names) {
        String name = list.get(0);
        String[] components = new String[5];
        int start = 0;
        int end;
        int componentIndex = 0;
        while (componentIndex < components.length - 1 && (end = name.indexOf(';', start)) >= 0) {
          components[componentIndex] = name.substring(start, end);
          componentIndex++;
          start = end + 1;
        }
        components[componentIndex] = name.substring(start);
        StringBuilder newName = new StringBuilder(100);
        maybeAppendComponent(components, 3, newName);
        maybeAppendComponent(components, 1, newName);
        maybeAppendComponent(components, 2, newName);
        maybeAppendComponent(components, 0, newName);
        maybeAppendComponent(components, 4, newName);
        list.set(0, newName.toString().trim());
      }
    }
  }
1176960
def clean(mapping, bind, values):
    
    categories = {'C': ' '}
    for value in values:
        if isinstance(value, six.string_types):
            value = normality.normalize(value, lowercase=False, collapse=True,
                                        decompose=False,
                                        replace_categories=categories)
        yield value
937370
def _clean_java_out(version_str):
    
    out = []
    for line in version_str.decode().split("\n"):
        if line.startswith("Picked up"):
            pass
        if line.find("setlocale") > 0:
            pass
        else:
            out.append(line)
    return "\n".join(out)
846438
def sanitizeString(name):
    """"""
    newString = name
    # string cleaning, pass 1
    replaceTable = [
        ('^', '^5e'),  # we need to do this one first
        ('"', '^22'),
        ('<', '^3c'),
        ('?', '^3f'),
        ('*', '^2a'),
        ('=', '^3d'),
        ('+', '^2b'),
        ('>', '^3e'),
        ('|', '^7c'),
        (',', '^2c'),
    ]

    #   "   hex 22           <   hex 3c           ?   hex 3f
    #   *   hex 2a           =   hex 3d           ^   hex 5e
    #   +   hex 2b           >   hex 3e           |   hex 7c
    #   ,   hex 2c

    for r in replaceTable:
        newString = newString.replace(r[0], r[1])
    # replace ascii 0-32
    for x in range(0, 33):
        # must add somewhat arbitrary num to avoid conflict at deSanitization
        # conflict example: is ^x1e supposed to be ^x1 (ascii 1) followed by
        # letter 'e' or really ^x1e (ascii 30)
        newString = newString.replace(
            chr(x), hex(x + sanitizerNum).replace('0x', '^'))

    replaceTable2 = [
        ("/", "="),
        (":", "+"),
        (".", ","),
    ]

    # / -> =
    # : -> +
    # . -> ,

    # string cleaning pass 2
    for r in replaceTable2:
        newString = newString.replace(r[0], r[1])
    return newString
671494
def clean(string):
    '''  '''
    # manual fixes in the source
    # 24/1.png
    # 9/1.png
    # 3/1.png
    #if ')' in string:  # fix in the source data
        #string = string.split(')')[0] + ')'  # remove trailing garbage
    return (string
            .replace('_', '')
            .replace('-', '')
            .replace('—', '')
            .replace('.', '')
            .replace('=', '')
            .replace('\u2018',"'")  # LEFT SINGLE QUOTATION MARK
            .replace('\u2019', "'")  # RIGHT SINGLE QUOTATION MARK
            .strip())
639356
def __str_cleanup(line):
        
        if '#' in line:
            line = line.replace("#", "")
            line = line.strip()
        if '-----------' in line:
            line = ''
        return line
459683
def _variable(lexer):
    """"""
    names = _names(lexer)

    tok = next(lexer)
    # NAMES '[' ... ']'
    if isinstance(tok, LBRACK):
        indices = _indices(lexer)
        _expect_token(lexer, {RBRACK})
    # NAMES
    else:
        lexer.unpop_token(tok)
        indices = tuple()

    return ('var', names, indices)
584020
def clean_names(lines, ensure_unique_names=False, strip_prefix=False,
                make_database_safe=False):
    
    names = {}

    for row in lines:
        if strip_prefix:
            row['name'] = row['name'][row['name'].find('-') + 1:]

            if row['indexed_by'] is not None:
                row['indexed_by'] = row['indexed_by'][row['indexed_by'].find(
                    '-') + 1:]

        if ensure_unique_names:
            i = 1
            while (row['name'] if i == 1 else
                   row['name'] + "-" + str(i)) in names:
                i += 1

            names[row['name'] if i == 1 else row['name'] + "-" + str(i)] = 1

            if i > 1:
                row['name'] = row['name'] + "-" + str(i)

        if make_database_safe:
            row['name'] = row['name'].replace("-", "_")
    return lines
613490
def sanitize(self, name, valid_fn):
        ""
        invalid = {'\a':'a','\b':'b', '\v':'v','\f':'f','\r':'r'}
        for cc in filter(lambda el: el in name, invalid.keys()):
            raise Exception("Please use a raw string or escape control code '\%s'"
                            % invalid[cc])
        sanitized, chars = [], ''
        for split in name.split():
            for c in split:
                if valid_fn(c): chars += str(c) if c=='_' else c
                else:
                    short = self.shortened_character_name(c, self.eliminations,
                                                         self.substitutions,
                                                         self.transforms)
                    sanitized.extend([chars] if chars else [])
                    if short != '':
                       sanitized.append(short)
                    chars = ''
            if chars:
                sanitized.extend([chars])
                chars=''
        return self._process_underscores(sanitized + ([chars] if chars else []))
328453
def format_unix_var(text):
    
    text = text.strip()
    if len(text) == 0:  # if empty string, return it
        raise ValueError("can not be empty string!")
    else:
        if text[0] in string.digits:
            raise ValueError("variable can not start with digits!")
        text = text.lower()
        # delete redundant empty space
        words = list()
        word = list()
        for char in text:
            if char in ALPHA_DIGITS:
                word.append(char)
            else:
                if len(word):
                    words.append("".join(word))
                    word = list()
        if len(word):
            words.append("".join(word))

        return "_".join(words)