Safequote restbase title possibly having slash in title
428969
def safequote_restbase(title):
    
    try:
        return quote(title.encode('utf-8'), safe='')
    except UnicodeDecodeError:
        return quote(title, safe='')
859167
def quote_from_bytes(bs, safe='/'):
    
    if not isinstance(bs, (bytes, bytearray)):
        raise TypeError("quote_from_bytes() expected bytes")
    if not bs:
        return str('')
    ### For Python-Future:
    bs = bytes(bs)
    ###
    if isinstance(safe, str):
        # Normalize 'safe' by converting to bytes and removing non-ASCII chars
        safe = str(safe).encode('ascii', 'ignore')
    else:
        ### For Python-Future:
        safe = bytes(safe)
        ###
        safe = bytes([c for c in safe if c < 128])
    if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
        return bs.decode()
    try:
        quoter = _safe_quoters[safe]
    except KeyError:
        _safe_quoters[safe] = quoter = Quoter(safe).__getitem__
    return str('').join([quoter(char) for char in bs])
987124
function() {
  var title = this.match(reLinkTitle);
  if (title) {
    // chop off quotes from title and unescape:
    return unescape(title.substr(1, title.length - 2));
  } else {
    return null;
  }
}
86014
static String safeName(String name) {
      if (name == null) {
        return null;
      }
      boolean prevCharIsUnderscore = false;
      StringBuilder safeNameBuilder = new StringBuilder(name.length());
      if (!name.isEmpty() && Character.isDigit(name.charAt(0))) {
        // prevent a numeric prefix.
        safeNameBuilder.append("_");
      }
      for (char nameChar : name.toCharArray()) {
        boolean isUnsafeChar = !JmxCollector.isLegalCharacter(nameChar);
        if ((isUnsafeChar || nameChar == '_')) {
          if (prevCharIsUnderscore) {
            continue;
          } else {
            safeNameBuilder.append("_");
            prevCharIsUnderscore = true;
          }
        } else {
          safeNameBuilder.append(nameChar);
          prevCharIsUnderscore = false;
        }
      }

      return safeNameBuilder.toString();
    }
469804
def _urlquote(string, safe=''):
    

    if string is None or string == '':
        return None

    # Anything already hex quoted is pulled out of the URL and unquoted if
    # possible
    escapes = []
    if re.search('%[0-9a-fA-F]{2}', string):
        # Try to unquote any percent values, restoring them if they are not
        # valid UTF-8. Also, requote any safe chars since encoded versions of
        # those are functionally different than the unquoted ones.
        def _try_unescape(match):
            byte_string = unquote_to_bytes(match.group(0))
            unicode_string = byte_string.decode('utf-8', 'iriutf8')
            for safe_char in list(safe):
                unicode_string = unicode_string.replace(safe_char, '%%%02x' % ord(safe_char))
            return unicode_string
        string = re.sub('(?:%[0-9a-fA-F]{2})+', _try_unescape, string)

        # Once we have the minimal set of hex quoted values, removed them from
        # the string so that they are not double quoted
        def _extract_escape(match):
            escapes.append(match.group(0).encode('ascii'))
            return '\x00'
        string = re.sub('%[0-9a-fA-F]{2}', _extract_escape, string)

    output = urlquote(string.encode('utf-8'), safe=safe.encode('utf-8'))
    if not isinstance(output, byte_cls):
        output = output.encode('ascii')

    # Restore the existing quoted values that we extracted
    if len(escapes) > 0:
        def _return_escape(_):
            return escapes.pop(0)
        output = re.sub(b'%00', _return_escape, output)

    return output
1199111
def quote(value):
    
    if value == None:
        output = ""
    elif is_text(value):
        output = encode_basestring(value)
    else:
        output = _json.dumps(value)
    return output
805991
function normalizeName (name) {
  // Normalize directories as a single slash
  name = _(name).toString();
  if (_.isEmpty(name) || name === "/" || name === "//") {
    return "/";
  }

  // Add a leading slash
  if (!_.startsWith(name, "/")) {
    name = "/" + name;
  }

  // Don't allow slashes in the middle
  if (_.includes(name.substring(1, name.length - 1), "/")) {
    throw ono("Resource names cannot contain slashes");
  }

  return name;
}
26535
function _sanitizeStyle(value) {
    value = String(value).trim(); // Make sure it's actually a string.
    if (!value)
        return '';
    // Single url(...) values are supported, but only for URLs that sanitize cleanly. See above for
    // reasoning behind this.
    var urlMatch = value.match(URL_RE);
    if ((urlMatch && _sanitizeUrl(urlMatch[1]) === urlMatch[1]) ||
        value.match(SAFE_STYLE_VALUE) && hasBalancedQuotes(value)) {
        return value; // Safe style values.
    }
    if (isDevMode()) {
        console.warn("WARNING: sanitizing unsafe style value " + value + " (see http://g.co/ng/security#xss).");
    }
    return 'unsafe';
}
509854
function normalizeSeparators (p) {
  p = p || "";

  if (path.sep === "\\") {
    // Replace backslashes with forward slashes
    return p.replace(/\\/g, "/");
  }
  else {
    // Return the path as-is, since it should already have proper URL separators.
    // If it DOES contain backslashes, then they are treated as normal characters,
    // NOT as separators
    return p;
  }
}
1113600
private static String sanitizeSqlServerUrl(String jdbcUrl) {
    StringBuilder result = new StringBuilder();
    result.append(SQLSERVER_PREFIX);

    String host;
    if (jdbcUrl.contains(";")) {
      host = StringUtils.substringBetween(jdbcUrl, SQLSERVER_PREFIX, ";");
    } else {
      host = StringUtils.substringAfter(jdbcUrl, SQLSERVER_PREFIX);
    }

    String queryString = StringUtils.substringAfter(jdbcUrl, ";");
    Map<String, String> parameters = KeyValueFormat.parse(queryString);
    Optional<String> server = firstValue(parameters, "serverName", "servername", "server");
    if (server.isPresent()) {
      result.append(server.get());
    } else {
      result.append(StringUtils.substringBefore(host, ":"));
    }

    Optional<String> port = firstValue(parameters, "portNumber", "port");
    if (port.isPresent()) {
      result.append(':').append(port.get());
    } else if (host.contains(":")) {
      result.append(':').append(StringUtils.substringAfter(host, ":"));
    }

    Optional<String> database = firstValue(parameters, "databaseName", "database");
    database.ifPresent(s -> result.append('/').append(s));
    return result.toString();
  }
1369753
static function safeName($filename,$unsafeExtensions=null,$safeExtension="txt") {
		if ($unsafeExtensions===null) $unsafeExtensions=array("php","phtml","inc","php3","php4","php5");
		if ($filename[0] == '.') {
			$filename = substr($filename, 1);
		}
		$filename = str_replace(DIRECTORY_SEPARATOR, '-', $filename);
		$extension=self::extension($filename, "l");
		if (in_array($extension, $unsafeExtensions)) {
			$extension=$safeExtension;
		}
		$name=self::filenameWithoutExtension($filename);
		$name=Strings::safe($name, false);
		if (preg_match('~^(.*)[-_]+$~',$name,$partsName)) {
			$name=$partsName[1];
		}
		if (preg_match('~^[-_]+(.*)$~',$name,$partsName)) {
			$name=$partsName[1];
		}
		$ret=$name;
		if ($extension) $ret.=".".$extension;
		return $ret;
	}
1241237
static String buildVirtualPageTitle(Map<String, String> metadata) {
    checkNotNull(metadata);
    List<String> escapedMetadata = new ArrayList<>();
    for (Map.Entry<String, String> entry : metadata.entrySet()) {
      escapedMetadata.add(METADATA_ESCAPER.escape(entry.getKey()) + "="
          + METADATA_ESCAPER.escape(entry.getValue()));
    }
    return Joiner.on(",").join(escapedMetadata);
  }
280701
def _xml_escape_attr(attr, skip_single_quote=True):
    
    escaped = (attr
        .replace('&', '&amp;')
        .replace('"', '&quot;')
        .replace('<', '&lt;')
        .replace('>', '&gt;'))
    if not skip_single_quote:
        escaped = escaped.replace("'", "&#39;")
    return escaped
861988
def Title(self):
        
        field = self.getField("Name")
        field = field and field.get(self) or ""
        return safe_unicode(field).encode("utf-8")
646749
def __safe_name(self, method_name):
    """"""
    # Endpoints backend restricts what chars are allowed in a method name.
    safe_name = re.sub(r'[^\.a-zA-Z0-9_]', '', method_name)

    # Strip any number of leading underscores.
    safe_name = safe_name.lstrip('_')

    # Ensure the first character is lowercase.
    # Slice from 0:1 rather than indexing [0] in case safe_name is length 0.
    return safe_name[0:1].lower() + safe_name[1:]
750324
private static String sanitizeString(final String in) {
    String result = null;
    if (in != null) {
      result = in.replace(':', '_');
      result = result.replace('/', '_');
      result = result.replace('\\', '_');
    }
    return result;
  }
563895
def url_quote_plus(string, charset='utf-8', errors='strict', safe=''):
    
    return url_quote(string, charset, errors, safe + ' ').replace(' ', '+')