Render an object into a unicode string if possible
557783
def obj_to_string(obj):
    ''''''
    if not obj:
        return None
    elif isinstance(obj, bytes):
        return obj.decode('utf-8')
    elif isinstance(obj, basestring):
        return obj
    elif is_lazy_string(obj):
        return obj.value
    elif hasattr(obj, '__html__'):
        return obj.__html__()
    else:
        return str(obj)
595777
def _sanitize_to_unicode(obj):
        
        if isinstance(obj, dict):
            return dict((BaseGELFHandler._sanitize_to_unicode(k), BaseGELFHandler._sanitize_to_unicode(v)) for k, v in obj.items())
        if isinstance(obj, (list, tuple)):
            return obj.__class__([BaseGELFHandler._sanitize_to_unicode(i) for i in obj])
        if isinstance(obj, data):
            obj = obj.decode('utf-8', errors='replace')
        return obj
1195360
function renderObject(obj, namespace) {
  return Object.keys(obj).map(function(key){
    var val = obj[key];
    return namespace + '["' + key + '"] = ' + string(val) + ';';
  }).join('\n');
}
976597
def obj2str(obj):
    """"""
    if isinstance(obj, str_types):
        return obj.encode("utf-8")
    elif isinstance(obj, pathlib.Path):
        return obj2str(str(obj))
    elif isinstance(obj, (bool, int, float)):
        return str(obj).encode("utf-8")
    elif obj is None:
        return b"none"
    elif isinstance(obj, np.ndarray):
        return obj.tostring()
    elif isinstance(obj, tuple):
        return obj2str(list(obj))
    elif isinstance(obj, list):
        return b"".join(obj2str(o) for o in obj)
    elif isinstance(obj, dict):
        return obj2str(list(obj.items()))
    elif hasattr(obj, "identifier"):
        return obj2str(obj.identifier)
    elif isinstance(obj, h5py.Dataset):
        return obj2str(obj[0])
    else:
        raise ValueError("No rule to convert object '{}' to string.".
                         format(obj.__class__))
1340330
def render(self, datestring):
        """"""
        formats = ["%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S.%f",
                   "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"]
        if datestring:
            for format in formats:
                try:
                    parsed = datetime.strptime(datestring, format)
                    if not timezone.is_aware(parsed):
                        parsed = timezone.make_aware(parsed, timezone.utc)
                    return parsed
                except Exception:
                    pass
        return None
965373
def value_to_string(self, obj):
        """"""
        try:
            return force_unicode(self.__get__(obj))
        except TypeError:
            return str(self.__get__(obj))
1124451
def render(self, is_unicode=False, **kwargs):
        """"""
        self.setup(**kwargs)
        svg = self.svg.render(
            is_unicode=is_unicode, pretty_print=self.pretty_print
        )
        self.teardown()
        return svg
1063190
def get_unicode_str(obj):
    """"""
    if isinstance(obj, six.text_type):
        return obj
    if isinstance(obj, six.binary_type):
        return obj.decode("utf-8", errors="ignore")
    return six.text_type(obj)
317706
def render(self, is_unicode=False, pretty_print=False):
        """"""
        for f in self.graph.xml_filters:
            self.root = f(self.root)
        args = {'encoding': 'utf-8'}

        svg = b''
        if etree.lxml:
            args['pretty_print'] = pretty_print

        if not self.graph.disable_xml_declaration:
            svg = b"<?xml version='1.0' encoding='utf-8'?>\n"

        if not self.graph.disable_xml_declaration:
            svg += b'\n'.join([
                etree.tostring(pi, **args)
                for pi in self.processing_instructions
            ])

        svg += etree.tostring(self.root, **args)

        if self.graph.disable_xml_declaration or is_unicode:
            svg = svg.decode('utf-8')
        return svg
49307
def _unicode_to_native(s):
  """"""
  if six.PY2:
    return s.encode("utf-8") if isinstance(s, unicode) else s
  else:
    return s
612657
def to_unicode(value):
  
  if isinstance(value, str):
    return value.decode('utf-8')

  assert isinstance(value, unicode)
  return value
1080785
def utf16_to_utf8(obj)
      str = obj[2, obj.size]
      str = str.unpack("n*").pack("U*")
      str.force_encoding("utf-8")
      str
    end
1364142
function obj2str(obj) {
  return Object.getOwnPropertyNames(obj).map(function (key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
  }).join('&');
}
990749
def prettify_object(obj):
    """"""

    try:
        return pprint.pformat(str(obj))
    except UnicodeDecodeError as e:
        raise
    except Exception as e:
        return "[could not display: <%s: %s>]" % (e.__class__.__name__, str(e))
4213
def to_unicode(data, encoding='UTF-8'):
    """"""
    if isinstance(data, unicode_type):
        return data

    if isinstance(data, bytes):
        return unicode_type(data, encoding=encoding)

    if hasattr(data, '__iter__'):
        try:
            dict(data)
        except TypeError:
            pass
        except ValueError:
            # Assume it's a one dimensional data structure
            return (to_unicode(i, encoding) for i in data)
        else:
            # We support 2.6 which lacks dict comprehensions
            if hasattr(data, 'items'):
                data = data.items()
            return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data))

    return data
1037830
def safe_str(obj):
    
    try:
        return str(obj)
    except UnicodeEncodeError:
        # obj is unicode
        try:
            return unicode(obj).encode('unicode_escape')  # noqa for undefined-variable
        except NameError:
            # This is Python 3, just return the obj as it's already unicode
            return obj
39910
def format_item(item, template, name='item'):
    """"""
    ctx = {name: item}
    return render_template_to_string(template, **ctx)