Python builtins.str() Examples

The following are 30 code examples of builtins.str(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module builtins , or try the search function .
Example #1
Source File: graph.py    From dcc with Apache License 2.0 7 votes vote down vote up
def draw(self, name, dname, draw_branches=True):
        from pydot import Dot, Edge,Node
        g = Dot()
        g.set_node_defaults(color='lightgray',
                            style='filled',
                            shape='box',
                            fontname='Courier',
                            fontsize='10')
        if len(self.nodes) == 1:
            g.add_node(Node(str(self.nodes[0])))
        else:
            for node in sorted(self.nodes, key=lambda x: x.num):
                for suc in self.sucs(node):
                    g.add_edge(Edge(str(node), str(suc), color='blue'))
                for except_node in self.catch_edges.get(node, []):
                    g.add_edge(Edge(str(node),
                                    str(except_node),
                                    color='black',
                                    style='dashed'))

        g.write_png('%s/%s.png' % (dname, name)) 
Example #2
Source File: BinViewMode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def draw(self, refresh=False, row=0, howMany=0):
        if self.dataModel.getOffset() in self.Paints:
            self.refresh = False
            self.qpix = QtGui.QPixmap(self.Paints[self.dataModel.getOffset()])
            self.drawAdditionals()
            return

        if self.refresh or refresh:
            qp = QtGui.QPainter()
            qp.begin(self.qpix)
            start = time()
            if not howMany:
                howMany = self.ROWS

            self.drawTextMode(qp, row=row, howMany=howMany)
            end = time() - start
            log.debug('draw Time ' + str(end))
            self.refresh = False
            qp.end()

        #        self.Paints[self.dataModel.getOffset()] = QtGui.QPixmap(self.qpix)
        self.drawAdditionals() 
Example #3
Source File: analysis.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_fake_method(self, name, descriptor):
        """
        Search for the given method name and descriptor
        and return a fake (ExternalMethod) if required.

        :param name: name of the method
        :param descriptor: descriptor of the method, for example `'(I I I)V'`
        :return: :class:`ExternalMethod`
        """
        if self.external:
            # An external class can only generate the methods on demand
            return self.orig_class.get_method(name, descriptor)

        # We are searching an unknown method in this class
        # It could be something that the class herits
        key = name + str(descriptor)
        if key not in self._inherits_methods:
            self._inherits_methods[key] = ExternalMethod(self.orig_class.get_name(), name, descriptor)
        return self._inherits_methods[key] 
Example #4
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def dump_value(self, endpoint_id, item_name, fname, fval):
        field_type = self._get_field_type(endpoint_id, item_name, fname)
        if field_type == '':
            return fval

        try:
            field_type = field_type.lower()
            if field_type == 'bool':
                return str(fval).lower()
            elif field_type == 'json':
                return json.dumps(fval)
            else:
                return fval
        except Exception as exc:
            msg = 'Fail to dump value of "{type_name}" - ' \
                  'endpoint={endpoint}, item={item}, field={field}' \
                  ''.format(type_name=field_type,
                            endpoint=endpoint_id,
                            item=item_name,
                            field=fname)
            log(msg, msgx=str(exc), level=logging.ERROR, need_tb=True)
            raise ConfigException(msg) 
Example #5
Source File: bytecode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def FormatDescriptorToPython(i):
    """
    Format a descriptor into a form which can be used as a python attribute

    example::

        >>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')
        'Ljava_lang_LongLjava_lang_LongZZV

    :param i: name to transform
    :rtype: str
    """

    i = i.replace("/", "_")
    i = i.replace(";", "")
    i = i.replace("[", "")
    i = i.replace("(", "")
    i = i.replace(")", "")
    i = i.replace(" ", "")
    i = i.replace("$", "")

    return i 
Example #6
Source File: bytecode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def FormatNameToPython(i):
    """
    Transform a (method) name into a form which can be used as a python
    attribute

    example::

        >>> FormatNameToPython('<clinit>')
        'clinit'

    :param i: name to transform
    :rtype: str
    """

    i = i.replace("<", "")
    i = i.replace(">", "")
    i = i.replace("$", "_")

    return i 
Example #7
Source File: ext.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _fix_microsecond_format(fmt, micros):
    """
    implement %Nf so that user can control the digital number of microsecond.
    If number of % is even, don't do replacement.
    If N is not in [1-6], don't do replacement.
    If time length m is less than N, convert it to 6 digitals and return N
    digitals.
    """
    micros = str(micros).zfill(6)

    def do_replacement(x, micros):
        if int(x.group(1)) in range(1, 7) and len(x.group()) % 2:
            return x.group().replace('%' + x.group(1) + 'f',
                                     micros[:min(int(x.group(1)), len(micros))])
        return x.group()

    return re.sub(r'%+([1-6])f', lambda x: do_replacement(x, micros), fmt) 
Example #8
Source File: decompile.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_class(self, class_name):
        """
        Return the :class:`DvClass` with the given name

        The name is partially matched against the known class names and the first result is returned.
        For example, the input `foobar` will match on Lfoobar/bla/foo;

        :param str class_name:
        :return: the class matching on the name
        :rtype: DvClass
        """
        for name, klass in self.classes.items():
            # TODO why use the name partially?
            if class_name in name:
                if isinstance(klass, DvClass):
                    return klass
                dvclass = self.classes[name] = DvClass(klass, self.vma)
                return dvclass 
Example #9
Source File: apk.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_elements(self, tag_name, attribute, with_namespace=True):
        """
        .. deprecated:: 3.3.5
            use :meth:`get_all_attribute_value` instead

        Return elements in xml files which match with the tag name and the specific attribute

        :param str tag_name: a string which specify the tag name
        :param str attribute: a string which specify the attribute
        """
        warnings.warn("This method is deprecated since 3.3.5.", DeprecationWarning)
        for i in self.xml:
            if self.xml[i] is None:
                continue
            for item in self.xml[i].findall('.//' + tag_name):
                if with_namespace:
                    value = item.get(self._ns(attribute))
                else:
                    value = item.get(attribute)
                # There might be an attribute without the namespace
                if value:
                    yield self._format_value(value) 
Example #10
Source File: decompile.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_field_ast(field):
    triple = field.get_class_name()[1:-1], field.get_name(
    ), field.get_descriptor()

    expr = None
    if field.init_value:
        val = field.init_value.value
        expr = dummy(str(val))

        if val is not None:
            if field.get_descriptor() == 'Ljava/lang/String;':
                expr = literal_string(val)
            elif field.proto == 'B':
                expr = literal_hex_int(struct.unpack('<b', struct.pack("B", val))[0])

    return {
        'triple': triple,
        'type': parse_descriptor(field.get_descriptor()),
        'flags': util.get_access_field(field.get_access_flags()),
        'expr': expr,
    } 
Example #11
Source File: bytecode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def FormatClassToPython(i):
    """
    Transform a typed class name into a form which can be used as a python
    attribute

    example::

        >>> FormatClassToPython('Lfoo/bar/foo/Barfoo$InnerClass;')
        'Lfoo_bar_foo_Barfoo_InnerClass'

    :param i: classname to transform
    :rtype: str
    """
    i = i[:-1]
    i = i.replace("/", "_")
    i = i.replace("$", "_")

    return i 
Example #12
Source File: BinViewMode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def handleEditMode(self, modifiers, key, event):
        if key in range(0, 256):
            offs = self.getCursorOffsetInPage()

            self.dataModel.setData_b(self.dataModel.getOffset() + offs, str(event.text()))

            z = self.dataModel.getOffset() + offs
            # TODO: sa nu se repete, tre original_transformengine
            self.transformationEngine = RangePen(self.original_textdecorator, z, z + 0,
                                                 QtGui.QPen(QtGui.QColor(218, 94, 242), 0, QtCore.Qt.SolidLine),
                                                 ignoreHighlights=True)

            self.moveCursor(Directions.Right)

            x, y = self.cursor.getPosition()

            self.draw(refresh=True, row=y, howMany=1) 
Example #13
Source File: apk.py    From dcc with Apache License 2.0 6 votes vote down vote up
def get_all_attribute_value(
        self, tag_name, attribute, format_value=True, **attribute_filter
    ):
        """
        Yields all the attribute values in xml files which match with the tag name and the specific attribute

        :param str tag_name: specify the tag name
        :param str attribute: specify the attribute
        :param bool format_value: specify if the value needs to be formatted with packagename
        """
        tags = self.find_tags(tag_name, **attribute_filter)
        for tag in tags:
            value = tag.get(attribute) or tag.get(self._ns(attribute))
            if value is not None:
                if format_value:
                    yield self._format_value(value)
                else:
                    yield value 
Example #14
Source File: credentials.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _update(self, name, str_to_encrypt):
        """
        Update the string for the name.
        :return: raise on failure
        """

        self.delete(name)

        if len(str_to_encrypt) <= SPLUNK_CRED_LEN_LIMIT:
            self._create(name, str_to_encrypt)
            return

        # split the str_to_encrypt when len > 255
        length = SPLUNK_CRED_LEN_LIMIT
        i = 0
        while length < len(str_to_encrypt) + SPLUNK_CRED_LEN_LIMIT:
            curr_str = str_to_encrypt[length - SPLUNK_CRED_LEN_LIMIT:length]
            length += SPLUNK_CRED_LEN_LIMIT

            stanza_name = self._sep.join((name, str(i)))
            self._create(stanza_name, curr_str)
            i += 1 
Example #15
Source File: bytecode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def object_to_bytes(obj):
    """
    Convert a object to a bytearray or call get_raw() of the object
    if no useful type was found.
    """
    if isinstance(obj, str):
        return bytearray(obj, "UTF-8")
    elif isinstance(obj, bool):
        return bytearray()
    elif isinstance(obj, int):
        return pack("<L", obj)
    elif obj is None:
        return bytearray()
    elif isinstance(obj, bytearray):
        return obj
    else:
        return obj.get_raw() 
Example #16
Source File: rest_helper.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def send_http_request(self, url, method, parameters=None, payload=None, headers=None, cookies=None, verify=True,
                          cert=None, timeout=None, proxy_uri=None):
        if self.http_session is None:
            self._init_request_session(proxy_uri)
        requests_args = {'timeout': (10.0, 5.0), 'verify': verify}
        if parameters:
            requests_args['params'] = parameters
        if payload:
            if isinstance(payload, (dict, list)):
                requests_args['json'] = payload
            else:
                requests_args['data'] = str(payload)
        if headers:
            requests_args['headers'] = headers
        if cookies:
            requests_args['cookies'] = cookies
        if cert:
            requests_args['cert'] = cert
        if timeout is not None:
            requests_args['timeout'] = timeout
        if self.requests_proxy:
            requests_args['proxies'] = self.requests_proxy
        return self.http_session.request(method, url, **requests_args) 
Example #17
Source File: HexViewMode.py    From dcc with Apache License 2.0 6 votes vote down vote up
def eventFilter(self, watched, event):
        if event.type() == QtCore.QEvent.KeyPress:
            if event.key() == QtCore.Qt.Key_Delete:
                # get RVA column from treeView

                item = self.widget.currentItem()

                offset = item.getOffset()  # int(str(item.text(1)),0)
                size = item.getSize()  # int(str(item.text(2)),0)
                u = offset
                v = offset + size

                self.view.selector.removeSelection(u, v, TextSelection.SelectionType.PERMANENT)
                # TODO: remove tree!

                item.parent().removeChild(item)
                # self.widget.takeTopLevelItem(self.widget.indexOfTopLevelItem(item))
                # rva = self.widget.indexFromItem(item, 1).data().toString()

        return False 
Example #18
Source File: credentials.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def _update(self, name, str_to_encrypt):
        """
        Update the string for the name.
        :return: raise on failure
        """

        self.delete(name)

        if len(str_to_encrypt) <= SPLUNK_CRED_LEN_LIMIT:
            self._create(name, str_to_encrypt)
            return

        # split the str_to_encrypt when len > 255
        length = SPLUNK_CRED_LEN_LIMIT
        i = 0
        while length < len(str_to_encrypt) + SPLUNK_CRED_LEN_LIMIT:
            curr_str = str_to_encrypt[length - SPLUNK_CRED_LEN_LIMIT:length]
            length += SPLUNK_CRED_LEN_LIMIT

            stanza_name = self._sep.join((name, str(i)))
            self._create(stanza_name, curr_str)
            i += 1 
Example #19
Source File: apk.py    From dcc with Apache License 2.0 6 votes vote down vote up
def find_tags_from_xml(
        self, xml_name, tag_name, **attribute_filter
    ):
        """
        Return a list of all the matched tags in a specific xml
        w
        :param str xml_name: specify from which xml to pick the tag from
        :param str tag_name: specify the tag name
        """
        xml = self.xml[xml_name]
        if xml is None:
            return []
        if xml.tag == tag_name:
            if self.is_tag_matched(
                xml.tag, **attribute_filter
            ):
                return [xml]
            return []
        tags = xml.findall(".//" + tag_name)
        return [
            tag for tag in tags if self.is_tag_matched(
                tag, **attribute_filter
            )
        ] 
Example #20
Source File: xrefwindow.py    From dcc with Apache License 2.0 6 votes vote down vote up
def slotDoubleClicked(self, mi):
        mi = self.proxyModel.mapToSource(mi)
        row = mi.row()
        column = mi.column()

        if column == len(self.headers) - 1:
            data = mi.data()
            xref_method = None
            xref_class = None
            for xref in self.xrefs:
                if str(xref[-2]) == data:
                    xref_method = xref[-2]
                    xref_class = xref[-1]
                    break

            if xref_class and xref_method:
                self.mainwin.openSourceWindow(current_class=xref_class,
                                              method=xref_method)
                self.parent.close()
                return
            else:
                self.mainwin.showStatus("Impossible to find the xref ....")
                return 
Example #21
Source File: apk.py    From dcc with Apache License 2.0 6 votes vote down vote up
def __getstate__(self):
        """
        Function for pickling APK Objects.

        We remove the zip from the Object, as it is not pickable
        And it does not make any sense to pickle it anyways.

        :returns: the picklable APK Object without zip.
        """
        # Upon pickling, we need to remove the ZipFile
        x = self.__dict__
        x['axml'] = str(x['axml'])
        x['xml'] = str(x['xml'])
        del x['zip']

        return x 
Example #22
Source File: config.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def dump_value(self, endpoint_id, item_name, fname, fval):
        field_type = self._get_field_type(endpoint_id, item_name, fname)
        if field_type == '':
            return fval

        try:
            field_type = field_type.lower()
            if field_type == 'bool':
                return str(fval).lower()
            elif field_type == 'json':
                return json.dumps(fval)
            else:
                return fval
        except Exception as exc:
            msg = 'Fail to dump value of "{type_name}" - ' \
                  'endpoint={endpoint}, item={item}, field={field}' \
                  ''.format(type_name=field_type,
                            endpoint=endpoint_id,
                            item=item_name,
                            field=fname)
            log(msg, msgx=str(exc), level=logging.ERROR, need_tb=True)
            raise ConfigException(msg) 
Example #23
Source File: validator.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate(self, value, data):
        try:
            self._validator(
                value,
                data,
                *self._args,
                **self._kwargs
            )
        except ValidationFailed as exc:
            self.put_msg(str(exc))
            return False
        else:
            return True 
Example #24
Source File: graph.py    From dcc with Apache License 2.0 5 votes vote down vote up
def __repr__(self):
        return str(self.nodes) 
Example #25
Source File: apk.py    From dcc with Apache License 2.0 5 votes vote down vote up
def get_services(self):
        """
        Return the android:name attribute of all services

        :rtype: a list of str
        """
        return list(self.get_all_attribute_value("service", "name")) 
Example #26
Source File: analysis.py    From dcc with Apache License 2.0 5 votes vote down vote up
def get_method(self, name, descriptor):
        """
        Get the method by name and descriptor,
        or create a new one if the requested method does not exists.

        :param name: method name
        :param descriptor: method descriptor, for example `'(I)V'`
        :return: :class:`ExternalMethod`
        """
        key = name + str(descriptor)
        if key not in self.methods:
            self.methods[key] = ExternalMethod(self.name, name, descriptor)

        return self.methods[key] 
Example #27
Source File: bytecode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def save(self, filename):
        """
        Save the current buffer to `filename`

        Exisiting files with the same name will be overwritten.

        :param str filename: the name of the file to save to
        """
        with open(filename, "wb") as fd:
            fd.write(self.__buff) 
Example #28
Source File: bytecode.py    From dcc with Apache License 2.0 5 votes vote down vote up
def _Print(name, arg):
    buff = name + " "

    if type(arg).__name__ == 'int':
        buff += "0x%x" % arg
    elif type(arg).__name__ == 'long':
        buff += "0x%x" % arg
    elif type(arg).__name__ == 'str':
        buff += "%s" % arg
    elif isinstance(arg, SV):
        buff += "0x%x" % arg.get_value()
    elif isinstance(arg, SVs):
        buff += arg.get_value().__str__()

    print(buff) 
Example #29
Source File: apk.py    From dcc with Apache License 2.0 5 votes vote down vote up
def get_requested_aosp_permissions(self):
        """
        Returns requested permissions declared within AOSP project.

        This includes several other permissions as well, which are in the platform apps.

        :rtype: list of str
        """
        aosp_permissions = []
        all_permissions = self.get_permissions()
        for perm in all_permissions:
            if perm in list(self.permission_module.keys()):
                aosp_permissions.append(perm)
        return aosp_permissions 
Example #30
Source File: models.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def normalize_headers(self, context):
        """Normalize headers which must be a dict which keys and values are
        string."""
        header = self.header.render(context)
        return {k: str(v) for k, v in header.items()}