Replace variable names with placeholders (e.g. ':v1')
436307
def get_value(self, value):
        
        next_key = ":v%d" % self._next_value
        self._next_value += 1
        self._values[next_key] = value
        return next_key
393743
def substitute(self, text, subvars={},
                   checkmissing=None):
        ''''''

        if checkmissing is None:
            checkmissing = self.checkmissing

        while True:
            idx = text.find(self.start_var_token)
            if idx == -1:
                return text
            endidx = text[idx:].find(self.end_var_token)
            if endidx == -1:
                raise MAVSubstituteError('missing end of variable: %s' % text[idx:idx+10])
            varname = text[idx+2:idx+endidx]
            fullvar = varname

            # allow default value after a :
            def_value = None
            colon = varname.find(':')
            if colon != -1:
                def_value = varname[colon+1:]
                varname = varname[:colon]

            if varname in subvars:
                value = subvars[varname]
            elif def_value is not None:
                value = def_value
            elif checkmissing:
                raise MAVSubstituteError("unknown variable in '%s%s%s'" % (
                    self.start_var_token, varname, self.end_var_token))
            else:
                return text[0:idx+endidx] + self.substitute(text[idx+endidx:], subvars, checkmissing=False)
            text = text.replace("%s%s%s" % (self.start_var_token, fullvar, self.end_var_token), str(value))
        return text
685113
function(context) {
      var varName,
          localVars = [];
      for (varName in context) {
        localVars.push('var ' + varName + ' = context.' + varName + ';');
      }
      return localVars.join('\n');
    }
784338
function replaceVariables(localPath, variables) {
    return new Promise(function(resolve, reject) {
        // Read the file
        let body = fs.readFileSync(localPath, 'utf8');

        // Do the replacement for all of the variables
        const keys = Object.keys(variables);
        keys.forEach(function(key) {
            const value = variables[key];
            const re = new RegExp(`"\\$${key}"`, 'g');

            // Parse the value (to see if it is falsey)
            try {
                const parsed = JSON.parse(value);
                body = body.replace(re, parsed ? `"${parsed}"` : `null`);
            } catch (err) {
                // Not valid JSON, treat it as a string
                body = body.replace(re, `"${value}"`);
            }
        });

        console.log('Variables replaced', body);
        fs.writeFile(localPath, body, function(err) {
            if (err) return reject(err);
            resolve(localPath);
        });
    });
}
373283
def replace_symbols(script_name, *args)
    args_new = []
    args_copy = args.clone

    url = args[0].clone
    modifiers = args_copy[1]
    if modifiers.class == Hash
      modifiers.delete_if do |key, value|
        delete = url.include? (":" + key.to_s)
        if delete
          url.sub!( (":" + key.to_s), value.to_s )
        end
        delete
      end
    end

    i = 1
    result = [url]
    while args_copy[i]
      unless args_copy[i].empty?

        if args_copy[i].class == Array
          value = args_copy[i]
        else
          value = [args_copy[i]]
        end

        if args_copy[i] != '/?' && url =~ /\*/
          url.sub!("*", value.join(''))
        else
          result.concat(value)
        end

      end
      i+= 1
    end
    result
  end
991409
function replaceInString(string, variables) {
    const model = createModel(string);
    let offset = 0;
    let output = '';

    for (let i = 0, il = model.variables.length; i < il; i++) {
        const v = model.variables[i];
        let value = v.name in variables ? variables[v.name] : v.name;
        if (typeof value === 'function') {
            value = value(model.string, v, offset + v.location);
        }

        output += model.string.slice(offset, v.location) + value;
        offset = v.location + v.length;
    }

    return output + model.string.slice(offset);
}
819727
function variables(root, config, done) {
  var expression = /\$v\[(.+?)\]/g;
  each(Object.keys(root), function(key, next) {
    var value = root[key];
    if (typeof value === 'object') return variables(value, config, next);
    if (typeof value !== 'string') return next();
    root[key] = value.replace(expression, function(match, matchKey) {
      return config[matchKey] || match;
    });
    next();
  }, done);
}
1156609
def __replace_base_variables(text, req_len, idx):
        
        return text \
            .replace("{i}", str(idx + 1)) \
            .replace("{n}", str(req_len))
895663
function envReplace(str, vars) {
  return str.replace(/\$?\$\{([A-Za-z0-9_]+)(:-(.*?))?\}/g, function (varStr, varName, _, defValue) {
    // Handle escaping:
    if (varStr.indexOf('$$') === 0) {
      return varStr;
    }
    // Handle simple variable replacement:
    if (vars.hasOwnProperty(varName)) {
      log.debug(`${varName} replaced in configuration file`);
      return vars[varName];
    }
    // Handle default values:
    if (defValue) {
      log.debug(`${varName} replaced with default value in configuration file`);
      return defValue;
    }
    log.warn(`Unknown variable: ${varName}. Returning null.`);
    return null;
  });
}
1367721
def format_vars(args):
    """'"""
    variables = []
    for key, value in args.items():
        if value:
            variables += ['{0}={1}'.format(key, value)]
    return variables
520350
def _transform(self, var):
        '''  '''
        self.collection.variables.pop(var.name)
        return var.values
1282982
def replace_path_variables(template_path, plugin_info)
      path = template_path.dup

      loop do
        replacement_variable_regexp = /%([\w\-]*)%/
        match = replacement_variable_regexp.match(path)

        break unless match

        replacement_value = plugin_info.send(match[1].to_sym)
        path.gsub!(replacement_variable_regexp, replacement_value)
      end

      path
    end
1290413
def override_env_variables():
    """"""
    env_vars = ("LOGNAME", "USER", "LNAME", "USERNAME")
    old = [os.environ[v] if v in os.environ else None for v in env_vars]

    for v in env_vars:
        os.environ[v] = "test"
    yield

    for i, v in enumerate(env_vars):
        if old[i]:
            os.environ[v] = old[i]
1093876
def replaceVariables(path, datetime=None, pathvars=None):
    """"""

    if datetime is None:
        datetime = time.gmtime()

    # if path variables are not given, set as empty list
    if pathvars is None:
        pathvars = [ ]

    # create an init path list to loop through
    if isinstance(path, list):
        path_list = path
    else:
        path_list = [ path ]

    # Set up the regex to search for variables
    regex = re.compile('\$\{(.*?)\}')

    # create a newpath list that will hold the 'cleaned' paths
    # with variables and strftime format directives replaced
    newpath_list = [ ]

    for p in path_list:
        # create temppath_list to be used a we work through the
        newpath_list.append(p)

        # Variable replacement
        # Find all the variables in path using the regex
        for k in regex.findall(p):
            # Check if the key is in path variables map
            if k in pathvars:
                # get the str or list of values
                v = pathvars[k]

                # Check value of variable must be in (string, integer, list)
                if type(v) is dict:
                    msg = "Path variable must refer to string, integer, or list"
                    raise TypeError(msg)

                # get the list of possible variable values
                value_list = v if type(v) is list else [ v ]


                # create temp_list for now
                temp_list = []

                # loop through the most recent newpath list
                # need to do this every time in order to account for all possible
                # combinations
                # replace the variables
                # loop through the list of values and replace the variables
                for v in value_list:
                    for newpath in newpath_list:
                        # remove the path from newpath_list
                        temp_list.append(newpath.replace('${%s}' % k, str(v)))

                # replace newpath_list
                newpath_list = temp_list

        # strftime translation
        # Loop through newpath_list to do strftime translation
        for index, newpath in enumerate(newpath_list):
            # Apply strftime translation
            newpath_list[index] = time.strftime(newpath, datetime)

    return newpath_list
832840
private static Pattern replacePlaceHolders(String s) {
    s = Pattern.quote(s);
    return Pattern.compile(s.replaceAll("\\{\\d+\\}", "\\\\E.*\\\\Q"));
  }
683357
function variableReplacementBuilder(v) {
        var pattern,
            name = v.name,
            from = v.from,
            to = v.to;

        if (util.isUndefined(to)) {
            grunt.log.error().error('"to" must be defined in a variable replacement instruction');
            return false;
        }

        if (util.isUndefined(name) && util.isUndefined(from)) {
            grunt.log.error().error('one of "name" or "from" must be defined in a variable replacement instruction');
            return false;
        }

        if (!util.isUndefined(name) && !util.isString(name) && !util.isRegex(name)) {
            grunt.log.error().error('"name" must be a string or a regex in a variable replacement instruction');
            return false;
        }

        if (!util.isUndefined(from) && !util.isString(from) && !util.isNumber(from) && !util.isBoolean(from)) {
            grunt.log.error().error('"from" must be a string, a number or a boolean in a variable replacement instruction');
            return false;
        }

        if (!util.isString(to) && !util.isNumber(to) && !util.isBoolean(to)) {
            grunt.log.error().error('"to" must be a string, a number or a boolean in a variable replacement instruction');
            return false;
        }

        pattern = buildVariableReplacementPattern(name, from, to);

        return {
            pattern: pattern,
            replacement: function (match, p1, p2, p3) {
                grunt.log
                    .debug('matching variable replacement'.bold)
                    .debug(('match=' + match).cyan)
                    .debug(('captured groups=' + grunt.log.wordlist([p1, p2, p3])).cyan);

                return p1 + to + p3;
            }
        };
    }
498783
def substitute_vars(template, replacements):
    
    result = template
    for (key, value) in replacements:
        result = result.replace('${' + key + '}' , value)
    if '${' in result:
        logging.warning("A variable was not replaced in '%s'.", result)
    return result