This calls the Windows QueryValueEx function in a Unicode safe way.
494755
def QueryValueEx(key, value_name):
  """"""
  regqueryvalueex = advapi32["RegQueryValueExW"]
  regqueryvalueex.restype = ctypes.c_long
  regqueryvalueex.argtypes = [
      ctypes.c_void_p, ctypes.c_wchar_p, LPDWORD, LPDWORD, LPBYTE, LPDWORD
  ]

  size = 256
  data_type = ctypes.wintypes.DWORD()
  while True:
    tmp_size = ctypes.wintypes.DWORD(size)
    buf = ctypes.create_string_buffer(size)
    rc = regqueryvalueex(key.handle, value_name, LPDWORD(),
                         ctypes.byref(data_type), ctypes.cast(buf, LPBYTE),
                         ctypes.byref(tmp_size))
    if rc != ERROR_MORE_DATA:
      break

    # We limit the size here to ~10 MB so the response doesn't get too big.
    if size > 10 * 1024 * 1024:
      raise OSError("Value too big to be read by GRR.")

    size *= 2

  if rc != ERROR_SUCCESS:
    raise ctypes.WinError(2)

  return _Reg2Py(buf, tmp_size.value, data_type.value), data_type.value
1201687
def do_urlencode(value):
    
    itemiter = None
    if isinstance(value, dict):
        itemiter = iteritems(value)
    elif not isinstance(value, string_types):
        try:
            itemiter = iter(value)
        except TypeError:
            pass
    if itemiter is None:
        return unicode_urlencode(value)
    return u'&'.join(unicode_urlencode(k) + '=' +
                     unicode_urlencode(v, for_qs=True)
                     for k, v in itemiter)
979219
def safely_encode(unicode_or_str, encoding='utf-8'):
  '''  '''
  if isinstance(unicode_or_str, unicode):
    rstr = unicode_or_str.encode(encoding, 'replace')
  elif isinstance(unicode_or_str, str):
    rstr = unicode_or_str
  else:
    raise Exception(u'Not of type unicode or str')

  return rstr
631945
function normalizeValue(value) {
		if (value.charAt(0) == '-' && !/^\-[\.\d]/.test(value)) {
			value = value.replace(/^\-+/, '');
		}
		
		var ch = value.charAt(0);
		if (ch == '#') {
			return normalizeHexColor(value);
		}

		if (ch == '$') {
			return utils.escapeText(value);
		}

		return getKeyword(value);
	}
1279970
def _value_wrapper(self, value):
        '''  
        '''
        if isinstance(value, (int, float,)):
            return '=%s' % value
        elif isinstance(value, (str, unicode)):
            value = value.strip()
            # LIKE
            if RE_LIKE.match(value):
                return ' LIKE %s' % repr(RE_LIKE.match(value).group('RE_LIKE'))
            # REGEXP
            elif RE_REGEXP.match(value):
                return ' REGEXP %s' % repr(RE_REGEXP.search(value).group('RE_REGEXP'))
            else:            
                return '=%s' % repr(value)
        elif value is None:
            return ' ISNULL'
773060
def force_unicode(s, encoding='utf-8', errors='strict'):
    
    # Handle the common case first, saves 30-40% when s is an instance of
    # six.text_type. This function gets called often in that setting.
    if isinstance(s, six.text_type):
        return s
    if not isinstance(s, six.string_types):
        if six.PY3:
            if isinstance(s, bytes):
                s = six.text_type(s, encoding, errors)
            else:
                s = six.text_type(s)
        else:
            s = six.text_type(bytes(s), encoding, errors)
    else:
        # Note: We use .decode() here, instead of six.text_type(s,
        # encoding, errors), so that if s is a SafeBytes, it ends up being
        # a SafeText at the end.
        s = s.decode(encoding, errors)
    return s
294091
def process_bind_param(self, value: Optional[List[str]],
                           dialect: Dialect) -> str:
        """"""
        retval = self._strlist_to_dbstr(value)
        return retval
551426
private void addEncodedValue(final StringBuilder urlBuilder,
            final String name, String value) {
        if (value != null) {
            String encodedValue;
            if (!"to".equals(name) && !urlBuilder.toString().endsWith("?")) {
                urlBuilder.append('&');
            }
            try {
                encodedValue =
                        URLEncoder.encode(value, "utf-8").replace("+", "%20");
            } catch (UnsupportedEncodingException e) {
                LOG.error("UTF-8 encoding not supported during encoding "
                        + value, e);
                encodedValue = value;
            }
            if (!"to".equals(name)) {
                urlBuilder.append(name).append('=');
            }
            urlBuilder.append(encodedValue);
        }
    }
157931
def force_ascii(value):
    
    if not isinstance(value, (str, unicode)):
        return unicode(value)
    if isinstance(value, unicode):
        return unidecode.unidecode(value)
    else:
        return unidecode.unidecode(force_unicode(value))
265941
def escape(self, value):
        """"""
        value = soft_unicode(value)

        if self._engine._escape is None:  # pylint: disable=protected-access
            return value

        return self._engine._escape(value)
957132
def safe_eval(value):
    
    if not isinstance(value, (str, unicode)):
        return value

    try:
        return CONSTANT_EVALS[value]
    except KeyError:
        try:
            return ast.literal_eval(value)
        except StandardError:
            return value
98445
def safestr(value):
    ''''''
    if not value or isinstance(value, (int, float, bool, long)):
        return value
    elif isinstance(value, (date, datetime)):
        return value.isoformat()
    else:
        return unicode(value)
66650
private final void validateChar(int value)
        throws XMLStreamException
    {
        /* 24-Jan-2006, TSa: Ok, "high" Unicode chars are problematic,
         *   need to be reported by a surrogate pair..
         */
        if (value >= 0xD800) {
            if (value < 0xE000) { // no surrogates via entity expansion
                reportIllegalChar(value);
            }
            if (value > 0xFFFF) {
                // Within valid range at all?
                if (value > MAX_UNICODE_CHAR) {
                    reportUnicodeOverflow();
                }
            } else if (value >= 0xFFFE) { // 0xFFFE and 0xFFFF are illegal too
                reportIllegalChar(value);
            }
            // Ok, fine as is
        } else if (value < 32) {
            if (value == 0) {
                throwParseError("Invalid character reference: null character not allowed in XML content.");
            }
            // XML 1.1 allows most other chars; 1.0 does not:
            if (!mXml11 && !mAllowXml11EscapedCharsInXml10
                && (value != 0x9 && value != 0xA && value != 0xD)) {
                reportIllegalChar(value);
            }
        }
    }
612657
def to_unicode(value):
  
  if isinstance(value, str):
    return value.decode('utf-8')

  assert isinstance(value, unicode)
  return value
579102
function () {
    var parts;

    if (!this.queryString) return;

    parts = this.queryString.replace('?','').split('&');

    each(parts, function (part) {
      var key = decodeURIComponent( part.split('=')[0] ),
          val = decodeURIComponent( part.split('=')[1] );

      if ( part.indexOf( '=' ) === -1 ) return;
      this._applyQueryParam( key, val );

    }, this);

  }
217541
def encode(cls, value):
        
        coerced = unicode(value)
        if coerced == value:
            return coerced.encode(cls._encoding)

        raise InvalidValue('not text')
1001085
function matchQueryPart(obj, queryKey, queryValue, treatObjAsValue) {
  var objValue = getDotValue(obj, queryKey),
    i,
    keys,
    firstChars,
    dollarFirstChars;

  // Check if the value is an array if we don't force a treatment as value
  if (util.isArray(objValue) && !treatObjAsValue) {
    // If the queryValue is an array, try to perform an exact match
    if (util.isArray(queryValue)) {
      return matchQueryPart(obj, queryKey, queryValue, true);
    }

    // Check if we are using an array-specific comparison function
    if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue)) {
      keys = Object.keys(queryValue);
      for (i = 0; i < keys.length; i += 1) {
        if (arrayComparisonFunctions[keys[i]]) {
          return matchQueryPart(obj, queryKey, queryValue, true);
        }
      }
    }

    // If not, treat it as an array of { obj, query } where there needs to be at least one match
    for (i = 0; i < objValue.length; i += 1) {
      if (matchQueryPart({ k: objValue[i] }, 'k', queryValue)) {
        return true;
      } // k here could be any string
    }
    return false;
  }

  // queryValue is an actual object. Determine whether it contains comparison operators
  // or only normal fields. Mixed objects are not allowed
  if (
    queryValue !== null &&
    typeof queryValue === 'object' &&
    !util.isRegExp(queryValue) &&
    !util.isArray(queryValue)
  ) {
    keys = Object.keys(queryValue);
    firstChars = _.map(keys, function(item) {
      return item[0];
    });
    dollarFirstChars = _.filter(firstChars, function(c) {
      return c === '$';
    });

    if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
      throw new Error('You cannot mix operators and normal fields');
    }

    // queryValue is an object of this form: { $comparisonOperator1: value1, ... }
    if (dollarFirstChars.length > 0) {
      for (i = 0; i < keys.length; i += 1) {
        if (!comparisonFunctions[keys[i]]) {
          throw new Error('Unknown comparison function ' + keys[i]);
        }

        if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) {
          return false;
        }
      }
      return true;
    }
  }

  // Using regular expressions with basic querying
  if (util.isRegExp(queryValue)) {
    return comparisonFunctions.$regex(objValue, queryValue);
  }

  // queryValue is either a native value or a normal object
  // Basic matching is possible
  if (!areThingsEqual(objValue, queryValue)) {
    return false;
  }

  return true;
}