Return a unicode object with the Gremlin representation of this expression.
178834
def to_gremlin(self):
        """"""
        self.validate()

        mark_name, field_name = self.location.get_location_name()

        if field_name is not None:
            validate_safe_string(field_name)
            if '@' in field_name:
                template = u'm.{mark_name}[\'{field_name}\']'
            else:
                template = u'm.{mark_name}.{field_name}'
        else:
            template = u'm.{mark_name}'

        validate_safe_string(mark_name)

        return template.format(mark_name=mark_name, field_name=field_name)
173210
def get_named_unicode(self, i):
        """"""

        index = i.index
        value = []
        try:
            if next(i) != '{':
                raise SyntaxError("Named Unicode missing '{'' at %d!" % (i.index - 1))
            c = next(i)
            while c != '}':
                value.append(c)
                c = next(i)
        except StopIteration:
            raise SyntaxError("Unmatched '}' at %d!" % index)

        return ''.join(value)
709317
def to_unicode(value, encoding=None):
    
    if isinstance(value, text_type):
        return value
    elif isinstance(value, type(None)):
        return text_type(value)

    if not isinstance(value, bytes):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )

    if encoding is not None:
        return value.decode(encoding)
    else:
        try:
            value = value.decode('utf-8')
        except:
            try:
                value = value.decode('gbk')
            except:
                pass

        return value
558310
def code_to_unicode(code):
    """
    def utf32chr(n):
        """utf32char for narrow build python"""
        return eval("u\'\\U%08X\'" % n)
    def lazy_unichr(n):
        try:
            return unichr(n)
        except ValueError:
            warnings.warn("Your python it built as narrow python. Make with "
                "'--enable-unicode=ucs4' configure option to build wide python")
            return utf32chr(n)
    if code and isinstance(code, basestring):
        clean_code = code.replace('>', '')
        if clean_code:
            return u''.join([lazy_unichr(int(code_char, 16)) for code_char in clean_code.split('+') if code_char])
    return None
625723
def to_gremlin(self):
        """"""
        self.validate()
        if len(self.start_class) == 1:
            # The official Gremlin documentation claims that this approach
            # is generally faster than the one below, since it makes using indexes easier.
            # http://gremlindocs.spmallette.documentup.com/#filter/has
            start_class = list(self.start_class)[0]
            return u'g.V({}, {})'.format('\'@class\'', safe_quoted_string(start_class))
        else:
            start_classes_list = ','.join(safe_quoted_string(x) for x in self.start_class)
            return u'g.V.has(\'@class\', T.in, [{}])'.format(start_classes_list)
869218
def po_to_unicode(po_obj):
    
    po_text = po_obj.__str__()
    if type(po_text) != types.UnicodeType:
        po_text = po_text.decode('utf-8')
    
    return po_text
790470
def _to_output_code(self):
        """"""
        # All supported Literal objects serialize to identical strings both in Gremlin and MATCH.
        self.validate()
        if self.value is None:
            return u'null'
        elif self.value is True:
            return u'true'
        elif self.value is False:
            return u'false'
        elif isinstance(self.value, six.string_types):
            return safe_quoted_string(self.value)
        elif isinstance(self.value, int):
            return six.text_type(self.value)
        elif isinstance(self.value, list):
            if len(self.value) == 0:
                return '[]'
            elif all(isinstance(x, six.string_types) for x in self.value):
                list_contents = ', '.join(safe_quoted_string(x) for x in sorted(self.value))
                return '[' + list_contents + ']'
        else:
            pass  # Fall through to assertion error below.
        raise AssertionError(u'Unreachable state reached: {}'.format(self))
486475
def convert(self, string, preprocess = None):
        
        string = unicode(preprocess(string) if preprocess else string, encoding="utf-8")
        if self.regex:
            return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode('utf-8')
        else:
            return string
1108228
def _to_unicode(instr):
    '''
    
    '''
    if instr is None or isinstance(instr, six.text_type):
        return instr
    else:
        return six.text_type(instr, 'utf8')
1331638
def _safe_gremlin_string(value):
    """"""
    if not isinstance(value, six.string_types):
        if isinstance(value, bytes):  # should only happen in py3
            value = value.decode('utf-8')
        else:
            raise GraphQLInvalidArgumentError(u'Attempting to convert a non-string into a string: '
                                              u'{}'.format(value))

    # Using JSON encoding means that all unicode literals and special chars
    # (e.g. newlines and backslashes) are replaced by appropriate escape sequences.
    # However, the quoted result is wrapped in double quotes, and $ signs are not escaped,
    # so that would allow arbitrary code execution in Gremlin.
    # We will therefore turn the double-quoted string into a single-quoted one to avoid this risk.
    escaped_and_quoted = json.dumps(value)

    # Double-quoted string literals in Gremlin/Groovy allow
    # arbitrary code execution via string interpolation and closures.
    # To avoid this, we perform the following steps:
    #   - we strip the wrapping double quotes;
    #   - we un-escape any double-quotes in the string, by replacing \" with ";
    #   - we escape any single-quotes in the string, by replacing ' with \';
    #   - finally, we wrap the string in single quotes.
    # http://www.groovy-lang.org/syntax.html#_double_quoted_string
    if not escaped_and_quoted[0] == escaped_and_quoted[-1] == '"':
        raise AssertionError(u'Unreachable state reached: {} {}'.format(value, escaped_and_quoted))
    no_quotes = escaped_and_quoted[1:-1]
    re_escaped = no_quotes.replace('\\"', '"').replace('\'', '\\\'')

    final_escaped_value = '\'' + re_escaped + '\''
    return final_escaped_value
456237
def proper_repr(value: Any) -> str:
    """"""

    if isinstance(value, sympy.Basic):
        result = sympy.srepr(value)

        # HACK: work around https://github.com/sympy/sympy/issues/16074
        # (only handles a few cases)
        fixed_tokens = [
            'Symbol', 'pi', 'Mul', 'Add', 'Mod', 'Integer', 'Float', 'Rational'
        ]
        for token in fixed_tokens:
            result = result.replace(token, 'sympy.' + token)

        return result

    if isinstance(value, np.ndarray):
        return 'np.array({!r})'.format(value.tolist())
    return repr(value)
518301
def to_gremlin(self):
        """"""
        self.validate()

        mark_name, field_name = self.location.get_location_name()
        validate_safe_string(mark_name)
        validate_safe_string(field_name)

        if '@' in field_name:
            template = u'm.{mark_name}[\'{field_name}\']'
        else:
            template = u'm.{mark_name}.{field_name}'

        format_value = None
        stripped_field_type = strip_non_null_from_type(self.field_type)
        if GraphQLDate.is_same_type(stripped_field_type):
            template += '.format("{format}")'
            format_value = STANDARD_DATE_FORMAT
        elif GraphQLDateTime.is_same_type(stripped_field_type):
            template += '.format("{format}")'
            format_value = STANDARD_DATETIME_FORMAT

        return template.format(mark_name=mark_name, field_name=field_name,
                               format=format_value)
285689
def to_unicode(value):
    
    if isinstance(value, _TO_UNICODE_TYPES):
        return value
    if not isinstance(value, bytes_type):
        raise TypeError(
            "Expected bytes, unicode, or None; got %r" % type(value)
        )
    return value.decode("utf-8")
1250686
def to_python(self, value):
        
        if isinstance(value, type(re.compile(''))):
            return value
        else:
            if value is None and self.null:
                return None
            else:
                try:
                    return self.get_compiled_regex(value)
                except:
                    raise ValidationError('Invalid regex {0}'.format(value))
478532
def safe_unicode(obj, *args):
    
    try:
        return unicode(obj, *args)  # noqa for undefined-variable
    except UnicodeDecodeError:
        # obj is byte string
        ascii_text = str(obj).encode('string_escape')
        try:
            return unicode(ascii_text)  # noqa for undefined-variable
        except NameError:
            # This is Python 3, just return the obj as it's already unicode
            return obj
    except NameError:
        # This is Python 3, just return the obj as it's already unicode
        return obj
598135
def to_unicode(text):
    
    if not isinstance(text, str):
        tmpl = 'expected unicode string, got %s value %s'
        raise TypeError(tmpl % (type(text), text))
    return text
652960
def unicoder(p):
    
    if isinstance(p, unicode):
        return p
    if isinstance(p, str):
        return decoder(p)
    else:
        return unicode(decoder(p))