id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
236,100
square/pylink
pylink/jlink.py
JLink.breakpoint_set
def breakpoint_set(self, addr, thumb=False, arm=False): """Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode Returns: An integer specifying the breakpoint handle. This handle should be retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ flags = enums.JLinkBreakpoint.ANY if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Breakpoint could not be set.') return handle
python
def breakpoint_set(self, addr, thumb=False, arm=False): """Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode Returns: An integer specifying the breakpoint handle. This handle should be retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ flags = enums.JLinkBreakpoint.ANY if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Breakpoint could not be set.') return handle
[ "def", "breakpoint_set", "(", "self", ",", "addr", ",", "thumb", "=", "False", ",", "arm", "=", "False", ")", ":", "flags", "=", "enums", ".", "JLinkBreakpoint", ".", "ANY", "if", "thumb", ":", "flags", "=", "flags", "|", "enums", ".", "JLinkBreakpoint", ".", "THUMB", "elif", "arm", ":", "flags", "=", "flags", "|", "enums", ".", "JLinkBreakpoint", ".", "ARM", "handle", "=", "self", ".", "_dll", ".", "JLINKARM_SetBPEx", "(", "int", "(", "addr", ")", ",", "flags", ")", "if", "handle", "<=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Breakpoint could not be set.'", ")", "return", "handle" ]
Sets a breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode Returns: An integer specifying the breakpoint handle. This handle should be retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set.
[ "Sets", "a", "breakpoint", "at", "the", "specified", "address", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3510-L3542
236,101
square/pylink
pylink/jlink.py
JLink.software_breakpoint_set
def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False): """Sets a software breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. If ``flash`` is ``True``, the breakpoint is set in flash, otherwise if ``ram`` is ``True``, the breakpoint is set in RAM. If both are ``True`` or both are ``False``, then the best option is chosen for setting the breakpoint in software. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode flash (bool): boolean indicating to set the breakpoint in flash ram (bool): boolean indicating to set the breakpoint in RAM Returns: An integer specifying the breakpoint handle. This handle should sbe retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ if flash and not ram: flags = enums.JLinkBreakpoint.SW_FLASH elif not flash and ram: flags = enums.JLinkBreakpoint.SW_RAM else: flags = enums.JLinkBreakpoint.SW if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Software breakpoint could not be set.') return handle
python
def software_breakpoint_set(self, addr, thumb=False, arm=False, flash=False, ram=False): """Sets a software breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. If ``flash`` is ``True``, the breakpoint is set in flash, otherwise if ``ram`` is ``True``, the breakpoint is set in RAM. If both are ``True`` or both are ``False``, then the best option is chosen for setting the breakpoint in software. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode flash (bool): boolean indicating to set the breakpoint in flash ram (bool): boolean indicating to set the breakpoint in RAM Returns: An integer specifying the breakpoint handle. This handle should sbe retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set. """ if flash and not ram: flags = enums.JLinkBreakpoint.SW_FLASH elif not flash and ram: flags = enums.JLinkBreakpoint.SW_RAM else: flags = enums.JLinkBreakpoint.SW if thumb: flags = flags | enums.JLinkBreakpoint.THUMB elif arm: flags = flags | enums.JLinkBreakpoint.ARM handle = self._dll.JLINKARM_SetBPEx(int(addr), flags) if handle <= 0: raise errors.JLinkException('Software breakpoint could not be set.') return handle
[ "def", "software_breakpoint_set", "(", "self", ",", "addr", ",", "thumb", "=", "False", ",", "arm", "=", "False", ",", "flash", "=", "False", ",", "ram", "=", "False", ")", ":", "if", "flash", "and", "not", "ram", ":", "flags", "=", "enums", ".", "JLinkBreakpoint", ".", "SW_FLASH", "elif", "not", "flash", "and", "ram", ":", "flags", "=", "enums", ".", "JLinkBreakpoint", ".", "SW_RAM", "else", ":", "flags", "=", "enums", ".", "JLinkBreakpoint", ".", "SW", "if", "thumb", ":", "flags", "=", "flags", "|", "enums", ".", "JLinkBreakpoint", ".", "THUMB", "elif", "arm", ":", "flags", "=", "flags", "|", "enums", ".", "JLinkBreakpoint", ".", "ARM", "handle", "=", "self", ".", "_dll", ".", "JLINKARM_SetBPEx", "(", "int", "(", "addr", ")", ",", "flags", ")", "if", "handle", "<=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Software breakpoint could not be set.'", ")", "return", "handle" ]
Sets a software breakpoint at the specified address. If ``thumb`` is ``True``, the breakpoint is set in THUMB-mode, while if ``arm`` is ``True``, the breakpoint is set in ARM-mode, otherwise a normal breakpoint is set. If ``flash`` is ``True``, the breakpoint is set in flash, otherwise if ``ram`` is ``True``, the breakpoint is set in RAM. If both are ``True`` or both are ``False``, then the best option is chosen for setting the breakpoint in software. Args: self (JLink): the ``JLink`` instance addr (int): the address where the breakpoint will be set thumb (bool): boolean indicating to set the breakpoint in THUMB mode arm (bool): boolean indicating to set the breakpoint in ARM mode flash (bool): boolean indicating to set the breakpoint in flash ram (bool): boolean indicating to set the breakpoint in RAM Returns: An integer specifying the breakpoint handle. This handle should sbe retained for future breakpoint operations. Raises: TypeError: if the given address is not an integer. JLinkException: if the breakpoint could not be set.
[ "Sets", "a", "software", "breakpoint", "at", "the", "specified", "address", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3545-L3589
236,102
square/pylink
pylink/jlink.py
JLink.watchpoint_info
def watchpoint_info(self, handle=0, index=-1): """Returns information about the specified watchpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): optional handle of a valid watchpoint. index (int): optional index of a watchpoint. Returns: An instance of ``JLinkWatchpointInfo`` specifying information about the watchpoint if the watchpoint was found, otherwise ``None``. Raises: JLinkException: on error. ValueError: if both handle and index are invalid. """ if index < 0 and handle == 0: raise ValueError('Handle must be provided if index is not set.') wp = structs.JLinkWatchpointInfo() res = self._dll.JLINKARM_GetWPInfoEx(index, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') for i in range(res): res = self._dll.JLINKARM_GetWPInfoEx(i, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') elif wp.Handle == handle or wp.WPUnit == index: return wp return None
python
def watchpoint_info(self, handle=0, index=-1): """Returns information about the specified watchpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): optional handle of a valid watchpoint. index (int): optional index of a watchpoint. Returns: An instance of ``JLinkWatchpointInfo`` specifying information about the watchpoint if the watchpoint was found, otherwise ``None``. Raises: JLinkException: on error. ValueError: if both handle and index are invalid. """ if index < 0 and handle == 0: raise ValueError('Handle must be provided if index is not set.') wp = structs.JLinkWatchpointInfo() res = self._dll.JLINKARM_GetWPInfoEx(index, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') for i in range(res): res = self._dll.JLINKARM_GetWPInfoEx(i, ctypes.byref(wp)) if res < 0: raise errors.JLinkException('Failed to get watchpoint info.') elif wp.Handle == handle or wp.WPUnit == index: return wp return None
[ "def", "watchpoint_info", "(", "self", ",", "handle", "=", "0", ",", "index", "=", "-", "1", ")", ":", "if", "index", "<", "0", "and", "handle", "==", "0", ":", "raise", "ValueError", "(", "'Handle must be provided if index is not set.'", ")", "wp", "=", "structs", ".", "JLinkWatchpointInfo", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_GetWPInfoEx", "(", "index", ",", "ctypes", ".", "byref", "(", "wp", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get watchpoint info.'", ")", "for", "i", "in", "range", "(", "res", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_GetWPInfoEx", "(", "i", ",", "ctypes", ".", "byref", "(", "wp", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get watchpoint info.'", ")", "elif", "wp", ".", "Handle", "==", "handle", "or", "wp", ".", "WPUnit", "==", "index", ":", "return", "wp", "return", "None" ]
Returns information about the specified watchpoint. Note: Either ``handle`` or ``index`` can be specified. If the ``index`` is not provided, the ``handle`` must be set, and vice-versa. If both ``index`` and ``handle`` are provided, the ``index`` overrides the provided ``handle``. Args: self (JLink): the ``JLink`` instance handle (int): optional handle of a valid watchpoint. index (int): optional index of a watchpoint. Returns: An instance of ``JLinkWatchpointInfo`` specifying information about the watchpoint if the watchpoint was found, otherwise ``None``. Raises: JLinkException: on error. ValueError: if both handle and index are invalid.
[ "Returns", "information", "about", "the", "specified", "watchpoint", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3677-L3714
236,103
square/pylink
pylink/jlink.py
JLink.watchpoint_set
def watchpoint_set(self, addr, addr_mask=0x0, data=0x0, data_mask=0x0, access_size=None, read=False, write=False, privileged=False): """Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on specific access size events, reads, writes, or privileged accesses. Both ``addr_mask`` and ``data_mask`` are used to specify ranges. Bits set to ``1`` are masked out and not taken into consideration when comparison against an address or data value. E.g. an ``addr_mask`` with a value of ``0x1`` and ``addr`` with value ``0xdeadbeef`` means that the watchpoint will be set on addresses ``0xdeadbeef`` and ``0xdeadbeee``. If the ``data`` was ``0x11223340`` and the given ``data_mask`` has a value of ``0x0000000F``, then the watchpoint would trigger for data matching ``0x11223340 - 0x1122334F``. Note: If both ``read`` and ``write`` are specified, then the watchpoint will trigger on both read and write events to the given address. Args: self (JLink): the ``JLink`` instance addr_mask (int): optional mask to use for determining which address the watchpoint should be set on data (int): optional data to set the watchpoint on in order to have the watchpoint triggered when the value at the specified address matches the given ``data`` data_mask (int): optional mask to use for determining the range of data on which the watchpoint should be triggered access_size (int): if specified, this must be one of ``{8, 16, 32}`` and determines the access size for which the watchpoint should trigger read (bool): if ``True``, triggers the watchpoint on read events write (bool): if ``True``, triggers the watchpoint on write events privileged (bool): if ``True``, triggers the watchpoint on privileged accesses Returns: The handle of the created watchpoint. Raises: ValueError: if an invalid access size is given. JLinkException: if the watchpoint fails to be set. """ access_flags = 0x0 access_mask_flags = 0x0 # If an access size is not specified, we must specify that the size of # the access does not matter by specifying the access mask flags. if access_size is None: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.SIZE elif access_size == 8: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_8BIT elif access_size == 16: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_16BIT elif access_size == 32: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_32BIT else: raise ValueError('Invalid access size given: %d' % access_size) # The read and write access flags cannot be specified together, so if # the user specifies that they want read and write access, then the # access mask flag must be set. if read and write: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.DIR elif read: access_flags = access_flags | enums.JLinkAccessFlags.READ elif write: access_flags = access_flags | enums.JLinkAccessFlags.WRITE # If privileged is not specified, then there is no specification level # on which kinds of writes should be accessed, in which case we must # specify that flag. if privileged: access_flags = access_flags | enums.JLinkAccessFlags.PRIV else: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.PRIV # Populate the Data event to configure how the watchpoint is triggered. wp = structs.JLinkDataEvent() wp.Addr = addr wp.AddrMask = addr_mask wp.Data = data wp.DataMask = data_mask wp.Access = access_flags wp.AccessMask = access_mask_flags # Return value of the function is <= 0 in the event of an error, # otherwise the watchpoint was set successfully. handle = ctypes.c_uint32() res = self._dll.JLINKARM_SetDataEvent(ctypes.pointer(wp), ctypes.pointer(handle)) if res < 0: raise errors.JLinkDataException(res) return handle.value
python
def watchpoint_set(self, addr, addr_mask=0x0, data=0x0, data_mask=0x0, access_size=None, read=False, write=False, privileged=False): """Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on specific access size events, reads, writes, or privileged accesses. Both ``addr_mask`` and ``data_mask`` are used to specify ranges. Bits set to ``1`` are masked out and not taken into consideration when comparison against an address or data value. E.g. an ``addr_mask`` with a value of ``0x1`` and ``addr`` with value ``0xdeadbeef`` means that the watchpoint will be set on addresses ``0xdeadbeef`` and ``0xdeadbeee``. If the ``data`` was ``0x11223340`` and the given ``data_mask`` has a value of ``0x0000000F``, then the watchpoint would trigger for data matching ``0x11223340 - 0x1122334F``. Note: If both ``read`` and ``write`` are specified, then the watchpoint will trigger on both read and write events to the given address. Args: self (JLink): the ``JLink`` instance addr_mask (int): optional mask to use for determining which address the watchpoint should be set on data (int): optional data to set the watchpoint on in order to have the watchpoint triggered when the value at the specified address matches the given ``data`` data_mask (int): optional mask to use for determining the range of data on which the watchpoint should be triggered access_size (int): if specified, this must be one of ``{8, 16, 32}`` and determines the access size for which the watchpoint should trigger read (bool): if ``True``, triggers the watchpoint on read events write (bool): if ``True``, triggers the watchpoint on write events privileged (bool): if ``True``, triggers the watchpoint on privileged accesses Returns: The handle of the created watchpoint. Raises: ValueError: if an invalid access size is given. JLinkException: if the watchpoint fails to be set. """ access_flags = 0x0 access_mask_flags = 0x0 # If an access size is not specified, we must specify that the size of # the access does not matter by specifying the access mask flags. if access_size is None: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.SIZE elif access_size == 8: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_8BIT elif access_size == 16: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_16BIT elif access_size == 32: access_flags = access_flags | enums.JLinkAccessFlags.SIZE_32BIT else: raise ValueError('Invalid access size given: %d' % access_size) # The read and write access flags cannot be specified together, so if # the user specifies that they want read and write access, then the # access mask flag must be set. if read and write: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.DIR elif read: access_flags = access_flags | enums.JLinkAccessFlags.READ elif write: access_flags = access_flags | enums.JLinkAccessFlags.WRITE # If privileged is not specified, then there is no specification level # on which kinds of writes should be accessed, in which case we must # specify that flag. if privileged: access_flags = access_flags | enums.JLinkAccessFlags.PRIV else: access_mask_flags = access_mask_flags | enums.JLinkAccessMaskFlags.PRIV # Populate the Data event to configure how the watchpoint is triggered. wp = structs.JLinkDataEvent() wp.Addr = addr wp.AddrMask = addr_mask wp.Data = data wp.DataMask = data_mask wp.Access = access_flags wp.AccessMask = access_mask_flags # Return value of the function is <= 0 in the event of an error, # otherwise the watchpoint was set successfully. handle = ctypes.c_uint32() res = self._dll.JLINKARM_SetDataEvent(ctypes.pointer(wp), ctypes.pointer(handle)) if res < 0: raise errors.JLinkDataException(res) return handle.value
[ "def", "watchpoint_set", "(", "self", ",", "addr", ",", "addr_mask", "=", "0x0", ",", "data", "=", "0x0", ",", "data_mask", "=", "0x0", ",", "access_size", "=", "None", ",", "read", "=", "False", ",", "write", "=", "False", ",", "privileged", "=", "False", ")", ":", "access_flags", "=", "0x0", "access_mask_flags", "=", "0x0", "# If an access size is not specified, we must specify that the size of", "# the access does not matter by specifying the access mask flags.", "if", "access_size", "is", "None", ":", "access_mask_flags", "=", "access_mask_flags", "|", "enums", ".", "JLinkAccessMaskFlags", ".", "SIZE", "elif", "access_size", "==", "8", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "SIZE_8BIT", "elif", "access_size", "==", "16", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "SIZE_16BIT", "elif", "access_size", "==", "32", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "SIZE_32BIT", "else", ":", "raise", "ValueError", "(", "'Invalid access size given: %d'", "%", "access_size", ")", "# The read and write access flags cannot be specified together, so if", "# the user specifies that they want read and write access, then the", "# access mask flag must be set.", "if", "read", "and", "write", ":", "access_mask_flags", "=", "access_mask_flags", "|", "enums", ".", "JLinkAccessMaskFlags", ".", "DIR", "elif", "read", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "READ", "elif", "write", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "WRITE", "# If privileged is not specified, then there is no specification level", "# on which kinds of writes should be accessed, in which case we must", "# specify that flag.", "if", "privileged", ":", "access_flags", "=", "access_flags", "|", "enums", ".", "JLinkAccessFlags", ".", "PRIV", "else", ":", "access_mask_flags", "=", "access_mask_flags", "|", "enums", ".", "JLinkAccessMaskFlags", ".", "PRIV", "# Populate the Data event to configure how the watchpoint is triggered.", "wp", "=", "structs", ".", "JLinkDataEvent", "(", ")", "wp", ".", "Addr", "=", "addr", "wp", ".", "AddrMask", "=", "addr_mask", "wp", ".", "Data", "=", "data", "wp", ".", "DataMask", "=", "data_mask", "wp", ".", "Access", "=", "access_flags", "wp", ".", "AccessMask", "=", "access_mask_flags", "# Return value of the function is <= 0 in the event of an error,", "# otherwise the watchpoint was set successfully.", "handle", "=", "ctypes", ".", "c_uint32", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SetDataEvent", "(", "ctypes", ".", "pointer", "(", "wp", ")", ",", "ctypes", ".", "pointer", "(", "handle", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkDataException", "(", "res", ")", "return", "handle", ".", "value" ]
Sets a watchpoint at the given address. This method allows for a watchpoint to be set on an given address or range of addresses. The watchpoint can then be triggered if the data at the given address matches the specified ``data`` or range of data as determined by ``data_mask``, on specific access size events, reads, writes, or privileged accesses. Both ``addr_mask`` and ``data_mask`` are used to specify ranges. Bits set to ``1`` are masked out and not taken into consideration when comparison against an address or data value. E.g. an ``addr_mask`` with a value of ``0x1`` and ``addr`` with value ``0xdeadbeef`` means that the watchpoint will be set on addresses ``0xdeadbeef`` and ``0xdeadbeee``. If the ``data`` was ``0x11223340`` and the given ``data_mask`` has a value of ``0x0000000F``, then the watchpoint would trigger for data matching ``0x11223340 - 0x1122334F``. Note: If both ``read`` and ``write`` are specified, then the watchpoint will trigger on both read and write events to the given address. Args: self (JLink): the ``JLink`` instance addr_mask (int): optional mask to use for determining which address the watchpoint should be set on data (int): optional data to set the watchpoint on in order to have the watchpoint triggered when the value at the specified address matches the given ``data`` data_mask (int): optional mask to use for determining the range of data on which the watchpoint should be triggered access_size (int): if specified, this must be one of ``{8, 16, 32}`` and determines the access size for which the watchpoint should trigger read (bool): if ``True``, triggers the watchpoint on read events write (bool): if ``True``, triggers the watchpoint on write events privileged (bool): if ``True``, triggers the watchpoint on privileged accesses Returns: The handle of the created watchpoint. Raises: ValueError: if an invalid access size is given. JLinkException: if the watchpoint fails to be set.
[ "Sets", "a", "watchpoint", "at", "the", "given", "address", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3717-L3821
236,104
square/pylink
pylink/jlink.py
JLink.disassemble_instruction
def disassemble_instruction(self, instruction): """Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number. """ if not util.is_integer(instruction): raise TypeError('Expected instruction to be an integer.') buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction) if res < 0: raise errors.JLinkException('Failed to disassemble instruction.') return ctypes.string_at(buf).decode()
python
def disassemble_instruction(self, instruction): """Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number. """ if not util.is_integer(instruction): raise TypeError('Expected instruction to be an integer.') buf_size = self.MAX_BUF_SIZE buf = (ctypes.c_char * buf_size)() res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction) if res < 0: raise errors.JLinkException('Failed to disassemble instruction.') return ctypes.string_at(buf).decode()
[ "def", "disassemble_instruction", "(", "self", ",", "instruction", ")", ":", "if", "not", "util", ".", "is_integer", "(", "instruction", ")", ":", "raise", "TypeError", "(", "'Expected instruction to be an integer.'", ")", "buf_size", "=", "self", ".", "MAX_BUF_SIZE", "buf", "=", "(", "ctypes", ".", "c_char", "*", "buf_size", ")", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_DisassembleInst", "(", "ctypes", ".", "byref", "(", "buf", ")", ",", "buf_size", ",", "instruction", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to disassemble instruction.'", ")", "return", "ctypes", ".", "string_at", "(", "buf", ")", ".", "decode", "(", ")" ]
Disassembles and returns the assembly instruction string. Args: self (JLink): the ``JLink`` instance. instruction (int): the instruction address. Returns: A string corresponding to the assembly instruction string at the given instruction address. Raises: JLinkException: on error. TypeError: if ``instruction`` is not a number.
[ "Disassembles", "and", "returns", "the", "assembly", "instruction", "string", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3848-L3872
236,105
square/pylink
pylink/jlink.py
JLink.strace_configure
def strace_configure(self, port_width): """Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error. """ if port_width not in [1, 2, 4]: raise ValueError('Invalid port width: %s' % str(port_width)) config_string = 'PortWidth=%d' % port_width res = self._dll.JLINK_STRACE_Config(config_string.encode()) if res < 0: raise errors.JLinkException('Failed to configure STRACE port') return None
python
def strace_configure(self, port_width): """Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error. """ if port_width not in [1, 2, 4]: raise ValueError('Invalid port width: %s' % str(port_width)) config_string = 'PortWidth=%d' % port_width res = self._dll.JLINK_STRACE_Config(config_string.encode()) if res < 0: raise errors.JLinkException('Failed to configure STRACE port') return None
[ "def", "strace_configure", "(", "self", ",", "port_width", ")", ":", "if", "port_width", "not", "in", "[", "1", ",", "2", ",", "4", "]", ":", "raise", "ValueError", "(", "'Invalid port width: %s'", "%", "str", "(", "port_width", ")", ")", "config_string", "=", "'PortWidth=%d'", "%", "port_width", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Config", "(", "config_string", ".", "encode", "(", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to configure STRACE port'", ")", "return", "None" ]
Configures the trace port width for tracing. Note that configuration cannot occur while STRACE is running. Args: self (JLink): the ``JLink`` instance port_width (int): the trace port width to use. Returns: ``None`` Raises: ValueError: if ``port_width`` is not ``1``, ``2``, or ``4``. JLinkException: on error.
[ "Configures", "the", "trace", "port", "width", "for", "tracing", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3881-L3905
236,106
square/pylink
pylink/jlink.py
JLink.strace_read
def strace_read(self, num_instructions): """Reads and returns a number of instructions captured by STRACE. The number of instructions must be a non-negative value of at most ``0x10000`` (``65536``). Args: self (JLink): the ``JLink`` instance. num_instructions (int): number of instructions to fetch. Returns: A list of instruction addresses in order from most recently executed to oldest executed instructions. Note that the number of instructions returned can be less than the number of instructions requested in the case that there are not ``num_instructions`` in the trace buffer. Raises: JLinkException: on error. ValueError: if ``num_instructions < 0`` or ``num_instructions > 0x10000``. """ if num_instructions < 0 or num_instructions > 0x10000: raise ValueError('Invalid instruction count.') buf = (ctypes.c_uint32 * num_instructions)() buf_size = num_instructions res = self._dll.JLINK_STRACE_Read(ctypes.byref(buf), buf_size) if res < 0: raise errors.JLinkException('Failed to read from STRACE buffer.') return list(buf)[:res]
python
def strace_read(self, num_instructions): """Reads and returns a number of instructions captured by STRACE. The number of instructions must be a non-negative value of at most ``0x10000`` (``65536``). Args: self (JLink): the ``JLink`` instance. num_instructions (int): number of instructions to fetch. Returns: A list of instruction addresses in order from most recently executed to oldest executed instructions. Note that the number of instructions returned can be less than the number of instructions requested in the case that there are not ``num_instructions`` in the trace buffer. Raises: JLinkException: on error. ValueError: if ``num_instructions < 0`` or ``num_instructions > 0x10000``. """ if num_instructions < 0 or num_instructions > 0x10000: raise ValueError('Invalid instruction count.') buf = (ctypes.c_uint32 * num_instructions)() buf_size = num_instructions res = self._dll.JLINK_STRACE_Read(ctypes.byref(buf), buf_size) if res < 0: raise errors.JLinkException('Failed to read from STRACE buffer.') return list(buf)[:res]
[ "def", "strace_read", "(", "self", ",", "num_instructions", ")", ":", "if", "num_instructions", "<", "0", "or", "num_instructions", ">", "0x10000", ":", "raise", "ValueError", "(", "'Invalid instruction count.'", ")", "buf", "=", "(", "ctypes", ".", "c_uint32", "*", "num_instructions", ")", "(", ")", "buf_size", "=", "num_instructions", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Read", "(", "ctypes", ".", "byref", "(", "buf", ")", ",", "buf_size", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to read from STRACE buffer.'", ")", "return", "list", "(", "buf", ")", "[", ":", "res", "]" ]
Reads and returns a number of instructions captured by STRACE. The number of instructions must be a non-negative value of at most ``0x10000`` (``65536``). Args: self (JLink): the ``JLink`` instance. num_instructions (int): number of instructions to fetch. Returns: A list of instruction addresses in order from most recently executed to oldest executed instructions. Note that the number of instructions returned can be less than the number of instructions requested in the case that there are not ``num_instructions`` in the trace buffer. Raises: JLinkException: on error. ValueError: if ``num_instructions < 0`` or ``num_instructions > 0x10000``.
[ "Reads", "and", "returns", "a", "number", "of", "instructions", "captured", "by", "STRACE", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L3949-L3980
236,107
square/pylink
pylink/jlink.py
JLink.strace_data_access_event
def strace_data_access_event(self, operation, address, data, data_mask=None, access_width=4, address_range=0): """Sets an event to trigger trace logic when data access is made. Data access corresponds to either a read or write. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the load/store data. data (int): the data to be compared the event data to. data_mask (int): optional bitmask specifying bits to ignore in comparison. acess_width (int): optional access width for the data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_ACCESS event_info.Op = operation event_info.AccessSize = int(access_width) event_info.Addr = int(address) event_info.Data = int(data) event_info.DataMask = int(data_mask or 0) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
python
def strace_data_access_event(self, operation, address, data, data_mask=None, access_width=4, address_range=0): """Sets an event to trigger trace logic when data access is made. Data access corresponds to either a read or write. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the load/store data. data (int): the data to be compared the event data to. data_mask (int): optional bitmask specifying bits to ignore in comparison. acess_width (int): optional access width for the data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_ACCESS event_info.Op = operation event_info.AccessSize = int(access_width) event_info.Addr = int(address) event_info.Data = int(data) event_info.DataMask = int(data_mask or 0) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
[ "def", "strace_data_access_event", "(", "self", ",", "operation", ",", "address", ",", "data", ",", "data_mask", "=", "None", ",", "access_width", "=", "4", ",", "address_range", "=", "0", ")", ":", "cmd", "=", "enums", ".", "JLinkStraceCommand", ".", "TRACE_EVENT_SET", "event_info", "=", "structs", ".", "JLinkStraceEventInfo", "(", ")", "event_info", ".", "Type", "=", "enums", ".", "JLinkStraceEvent", ".", "DATA_ACCESS", "event_info", ".", "Op", "=", "operation", "event_info", ".", "AccessSize", "=", "int", "(", "access_width", ")", "event_info", ".", "Addr", "=", "int", "(", "address", ")", "event_info", ".", "Data", "=", "int", "(", "data", ")", "event_info", ".", "DataMask", "=", "int", "(", "data_mask", "or", "0", ")", "event_info", ".", "AddrRangeSize", "=", "int", "(", "address_range", ")", "handle", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "event_info", ")", ")", "if", "handle", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "handle", ")", "return", "handle" ]
Sets an event to trigger trace logic when data access is made. Data access corresponds to either a read or write. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the load/store data. data (int): the data to be compared the event data to. data_mask (int): optional bitmask specifying bits to ignore in comparison. acess_width (int): optional access width for the data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error.
[ "Sets", "an", "event", "to", "trigger", "trace", "logic", "when", "data", "access", "is", "made", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4012-L4053
236,108
square/pylink
pylink/jlink.py
JLink.strace_data_store_event
def strace_data_store_event(self, operation, address, address_range=0): """Sets an event to trigger trace logic when data write access is made. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the store data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_STORE event_info.Op = operation event_info.Addr = int(address) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
python
def strace_data_store_event(self, operation, address, address_range=0): """Sets an event to trigger trace logic when data write access is made. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the store data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error. """ cmd = enums.JLinkStraceCommand.TRACE_EVENT_SET event_info = structs.JLinkStraceEventInfo() event_info.Type = enums.JLinkStraceEvent.DATA_STORE event_info.Op = operation event_info.Addr = int(address) event_info.AddrRangeSize = int(address_range) handle = self._dll.JLINK_STRACE_Control(cmd, ctypes.byref(event_info)) if handle < 0: raise errors.JLinkException(handle) return handle
[ "def", "strace_data_store_event", "(", "self", ",", "operation", ",", "address", ",", "address_range", "=", "0", ")", ":", "cmd", "=", "enums", ".", "JLinkStraceCommand", ".", "TRACE_EVENT_SET", "event_info", "=", "structs", ".", "JLinkStraceEventInfo", "(", ")", "event_info", ".", "Type", "=", "enums", ".", "JLinkStraceEvent", ".", "DATA_STORE", "event_info", ".", "Op", "=", "operation", "event_info", ".", "Addr", "=", "int", "(", "address", ")", "event_info", ".", "AddrRangeSize", "=", "int", "(", "address_range", ")", "handle", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "event_info", ")", ")", "if", "handle", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "handle", ")", "return", "handle" ]
Sets an event to trigger trace logic when data write access is made. Args: self (JLink): the ``JLink`` instance. operation (int): one of the operations in ``JLinkStraceOperation``. address (int): the address of the store data. address_range (int): optional range of address to trigger event on. Returns: An integer specifying the trace event handle. This handle should be retained in order to clear the event at a later time. Raises: JLinkException: on error.
[ "Sets", "an", "event", "to", "trigger", "trace", "logic", "when", "data", "write", "access", "is", "made", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4085-L4111
236,109
square/pylink
pylink/jlink.py
JLink.strace_clear
def strace_clear(self, handle): """Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error. """ data = ctypes.c_int(handle) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR, ctypes.byref(data)) if res < 0: raise errors.JLinkException('Failed to clear STRACE event.') return None
python
def strace_clear(self, handle): """Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error. """ data = ctypes.c_int(handle) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR, ctypes.byref(data)) if res < 0: raise errors.JLinkException('Failed to clear STRACE event.') return None
[ "def", "strace_clear", "(", "self", ",", "handle", ")", ":", "data", "=", "ctypes", ".", "c_int", "(", "handle", ")", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "enums", ".", "JLinkStraceCommand", ".", "TRACE_EVENT_CLR", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to clear STRACE event.'", ")", "return", "None" ]
Clears the trace event specified by the given handle. Args: self (JLink): the ``JLink`` instance. handle (int): handle of the trace event. Returns: ``None`` Raises: JLinkException: on error.
[ "Clears", "the", "trace", "event", "specified", "by", "the", "given", "handle", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4114-L4132
236,110
square/pylink
pylink/jlink.py
JLink.strace_clear_all
def strace_clear_all(self): """Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ data = 0 res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR_ALL, data) if res < 0: raise errors.JLinkException('Failed to clear all STRACE events.') return None
python
def strace_clear_all(self): """Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ data = 0 res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.TRACE_EVENT_CLR_ALL, data) if res < 0: raise errors.JLinkException('Failed to clear all STRACE events.') return None
[ "def", "strace_clear_all", "(", "self", ")", ":", "data", "=", "0", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "enums", ".", "JLinkStraceCommand", ".", "TRACE_EVENT_CLR_ALL", ",", "data", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to clear all STRACE events.'", ")", "return", "None" ]
Clears all STRACE events. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
[ "Clears", "all", "STRACE", "events", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4135-L4152
236,111
square/pylink
pylink/jlink.py
JLink.strace_set_buffer_size
def strace_set_buffer_size(self, size): """Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ size = ctypes.c_uint32(size) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.SET_BUFFER_SIZE, size) if res < 0: raise errors.JLinkException('Failed to set the STRACE buffer size.') return None
python
def strace_set_buffer_size(self, size): """Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error. """ size = ctypes.c_uint32(size) res = self._dll.JLINK_STRACE_Control(enums.JLinkStraceCommand.SET_BUFFER_SIZE, size) if res < 0: raise errors.JLinkException('Failed to set the STRACE buffer size.') return None
[ "def", "strace_set_buffer_size", "(", "self", ",", "size", ")", ":", "size", "=", "ctypes", ".", "c_uint32", "(", "size", ")", "res", "=", "self", ".", "_dll", ".", "JLINK_STRACE_Control", "(", "enums", ".", "JLinkStraceCommand", ".", "SET_BUFFER_SIZE", ",", "size", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to set the STRACE buffer size.'", ")", "return", "None" ]
Sets the STRACE buffer size. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` Raises: JLinkException: on error.
[ "Sets", "the", "STRACE", "buffer", "size", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4155-L4172
236,112
square/pylink
pylink/jlink.py
JLink.trace_start
def trace_start(self): """Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.START res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to start trace.') return None
python
def trace_start(self): """Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.START res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to start trace.') return None
[ "def", "trace_start", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "START", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "0", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to start trace.'", ")", "return", "None" ]
Starts collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
[ "Starts", "collecting", "trace", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4181-L4194
236,113
square/pylink
pylink/jlink.py
JLink.trace_stop
def trace_stop(self): """Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.STOP res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to stop trace.') return None
python
def trace_stop(self): """Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.STOP res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to stop trace.') return None
[ "def", "trace_stop", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "STOP", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "0", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to stop trace.'", ")", "return", "None" ]
Stops collecting trace data. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
[ "Stops", "collecting", "trace", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4197-L4210
236,114
square/pylink
pylink/jlink.py
JLink.trace_flush
def trace_flush(self): """Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.FLUSH res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to flush the trace buffer.') return None
python
def trace_flush(self): """Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.FLUSH res = self._dll.JLINKARM_TRACE_Control(cmd, 0) if (res == 1): raise errors.JLinkException('Failed to flush the trace buffer.') return None
[ "def", "trace_flush", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "FLUSH", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "0", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to flush the trace buffer.'", ")", "return", "None" ]
Flushes the trace buffer. After this method is called, the trace buffer is empty. This method is best called when the device is reset. Args: self (JLink): the ``JLink`` instance. Returns: ``None``
[ "Flushes", "the", "trace", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4213-L4229
236,115
square/pylink
pylink/jlink.py
JLink.trace_buffer_capacity
def trace_buffer_capacity(self): """Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with. """ cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace buffer size.') return data.value
python
def trace_buffer_capacity(self): """Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with. """ cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace buffer size.') return data.value
[ "def", "trace_buffer_capacity", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_CONF_CAPACITY", "data", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get trace buffer size.'", ")", "return", "data", ".", "value" ]
Retrieves the trace buffer's current capacity. Args: self (JLink): the ``JLink`` instance. Returns: The current capacity of the trace buffer. This is not necessarily the maximum possible size the buffer could be configured with.
[ "Retrieves", "the", "trace", "buffer", "s", "current", "capacity", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4249-L4264
236,116
square/pylink
pylink/jlink.py
JLink.trace_set_buffer_capacity
def trace_set_buffer_capacity(self, size): """Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_CAPACITY data = ctypes.c_uint32(size) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace buffer size.') return None
python
def trace_set_buffer_capacity(self, size): """Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_CAPACITY data = ctypes.c_uint32(size) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace buffer size.') return None
[ "def", "trace_set_buffer_capacity", "(", "self", ",", "size", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "SET_CAPACITY", "data", "=", "ctypes", ".", "c_uint32", "(", "size", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to set trace buffer size.'", ")", "return", "None" ]
Sets the capacity for the trace buffer. Args: self (JLink): the ``JLink`` instance. size (int): the new capacity for the trace buffer. Returns: ``None``
[ "Sets", "the", "capacity", "for", "the", "trace", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4267-L4282
236,117
square/pylink
pylink/jlink.py
JLink.trace_min_buffer_capacity
def trace_min_buffer_capacity(self): """Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MIN_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get min trace buffer size.') return data.value
python
def trace_min_buffer_capacity(self): """Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MIN_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get min trace buffer size.') return data.value
[ "def", "trace_min_buffer_capacity", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_MIN_CAPACITY", "data", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get min trace buffer size.'", ")", "return", "data", ".", "value" ]
Retrieves the minimum capacity the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The minimum configurable capacity for the trace buffer.
[ "Retrieves", "the", "minimum", "capacity", "the", "trace", "buffer", "can", "be", "configured", "with", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4285-L4299
236,118
square/pylink
pylink/jlink.py
JLink.trace_max_buffer_capacity
def trace_max_buffer_capacity(self): """Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MAX_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get max trace buffer size.') return data.value
python
def trace_max_buffer_capacity(self): """Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer. """ cmd = enums.JLinkTraceCommand.GET_MAX_CAPACITY data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get max trace buffer size.') return data.value
[ "def", "trace_max_buffer_capacity", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_MAX_CAPACITY", "data", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get max trace buffer size.'", ")", "return", "data", ".", "value" ]
Retrieves the maximum size the trace buffer can be configured with. Args: self (JLink): the ``JLink`` instance. Returns: The maximum configurable capacity for the trace buffer.
[ "Retrieves", "the", "maximum", "size", "the", "trace", "buffer", "can", "be", "configured", "with", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4302-L4316
236,119
square/pylink
pylink/jlink.py
JLink.trace_set_format
def trace_set_format(self, fmt): """Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_FORMAT data = ctypes.c_uint32(fmt) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace format.') return None
python
def trace_set_format(self, fmt): """Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None`` """ cmd = enums.JLinkTraceCommand.SET_FORMAT data = ctypes.c_uint32(fmt) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to set trace format.') return None
[ "def", "trace_set_format", "(", "self", ",", "fmt", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "SET_FORMAT", "data", "=", "ctypes", ".", "c_uint32", "(", "fmt", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to set trace format.'", ")", "return", "None" ]
Sets the format for the trace buffer to use. Args: self (JLink): the ``JLink`` instance. fmt (int): format for the trace buffer; this is one of the attributes of ``JLinkTraceFormat``. Returns: ``None``
[ "Sets", "the", "format", "for", "the", "trace", "buffer", "to", "use", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4319-L4335
236,120
square/pylink
pylink/jlink.py
JLink.trace_format
def trace_format(self): """Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``. """ cmd = enums.JLinkTraceCommand.GET_FORMAT data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace format.') return data.value
python
def trace_format(self): """Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``. """ cmd = enums.JLinkTraceCommand.GET_FORMAT data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace format.') return data.value
[ "def", "trace_format", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_FORMAT", "data", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get trace format.'", ")", "return", "data", ".", "value" ]
Retrieves the current format the trace buffer is using. Args: self (JLink): the ``JLink`` instance. Returns: The current format the trace buffer is using. This is one of the attributes of ``JLinkTraceFormat``.
[ "Retrieves", "the", "current", "format", "the", "trace", "buffer", "is", "using", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4338-L4353
236,121
square/pylink
pylink/jlink.py
JLink.trace_region_count
def trace_region_count(self): """Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions. """ cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace region count.') return data.value
python
def trace_region_count(self): """Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions. """ cmd = enums.JLinkTraceCommand.GET_NUM_REGIONS data = ctypes.c_uint32(0) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data)) if (res == 1): raise errors.JLinkException('Failed to get trace region count.') return data.value
[ "def", "trace_region_count", "(", "self", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_NUM_REGIONS", "data", "=", "ctypes", ".", "c_uint32", "(", "0", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "data", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get trace region count.'", ")", "return", "data", ".", "value" ]
Retrieves a count of the number of available trace regions. Args: self (JLink): the ``JLink`` instance. Returns: Count of the number of available trace regions.
[ "Retrieves", "a", "count", "of", "the", "number", "of", "available", "trace", "regions", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4356-L4370
236,122
square/pylink
pylink/jlink.py
JLink.trace_region
def trace_region(self, region_index): """Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region. """ cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX region = structs.JLinkTraceRegion() region.RegionIndex = int(region_index) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region)) if (res == 1): raise errors.JLinkException('Failed to get trace region.') return region
python
def trace_region(self, region_index): """Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region. """ cmd = enums.JLinkTraceCommand.GET_REGION_PROPS_EX region = structs.JLinkTraceRegion() region.RegionIndex = int(region_index) res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(region)) if (res == 1): raise errors.JLinkException('Failed to get trace region.') return region
[ "def", "trace_region", "(", "self", ",", "region_index", ")", ":", "cmd", "=", "enums", ".", "JLinkTraceCommand", ".", "GET_REGION_PROPS_EX", "region", "=", "structs", ".", "JLinkTraceRegion", "(", ")", "region", ".", "RegionIndex", "=", "int", "(", "region_index", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Control", "(", "cmd", ",", "ctypes", ".", "byref", "(", "region", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to get trace region.'", ")", "return", "region" ]
Retrieves the properties of a trace region. Args: self (JLink): the ``JLink`` instance. region_index (int): the trace region index. Returns: An instance of ``JLinkTraceRegion`` describing the specified region.
[ "Retrieves", "the", "properties", "of", "a", "trace", "region", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4373-L4389
236,123
square/pylink
pylink/jlink.py
JLink.trace_read
def trace_read(self, offset, num_items): """Reads data from the trace buffer and returns it. Args: self (JLink): the ``JLink`` instance. offset (int): the offset from which to start reading from the trace buffer. num_items (int): number of items to read from the trace buffer. Returns: A list of ``JLinkTraceData`` instances corresponding to the items read from the trace buffer. Note that this list may have size less than ``num_items`` in the event that there are not ``num_items`` items in the trace buffer. Raises: JLinkException: on error. """ buf_size = ctypes.c_uint32(num_items) buf = (structs.JLinkTraceData * num_items)() res = self._dll.JLINKARM_TRACE_Read(buf, int(offset), ctypes.byref(buf_size)) if (res == 1): raise errors.JLinkException('Failed to read from trace buffer.') return list(buf)[:int(buf_size.value)]
python
def trace_read(self, offset, num_items): """Reads data from the trace buffer and returns it. Args: self (JLink): the ``JLink`` instance. offset (int): the offset from which to start reading from the trace buffer. num_items (int): number of items to read from the trace buffer. Returns: A list of ``JLinkTraceData`` instances corresponding to the items read from the trace buffer. Note that this list may have size less than ``num_items`` in the event that there are not ``num_items`` items in the trace buffer. Raises: JLinkException: on error. """ buf_size = ctypes.c_uint32(num_items) buf = (structs.JLinkTraceData * num_items)() res = self._dll.JLINKARM_TRACE_Read(buf, int(offset), ctypes.byref(buf_size)) if (res == 1): raise errors.JLinkException('Failed to read from trace buffer.') return list(buf)[:int(buf_size.value)]
[ "def", "trace_read", "(", "self", ",", "offset", ",", "num_items", ")", ":", "buf_size", "=", "ctypes", ".", "c_uint32", "(", "num_items", ")", "buf", "=", "(", "structs", ".", "JLinkTraceData", "*", "num_items", ")", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_TRACE_Read", "(", "buf", ",", "int", "(", "offset", ")", ",", "ctypes", ".", "byref", "(", "buf_size", ")", ")", "if", "(", "res", "==", "1", ")", ":", "raise", "errors", ".", "JLinkException", "(", "'Failed to read from trace buffer.'", ")", "return", "list", "(", "buf", ")", "[", ":", "int", "(", "buf_size", ".", "value", ")", "]" ]
Reads data from the trace buffer and returns it. Args: self (JLink): the ``JLink`` instance. offset (int): the offset from which to start reading from the trace buffer. num_items (int): number of items to read from the trace buffer. Returns: A list of ``JLinkTraceData`` instances corresponding to the items read from the trace buffer. Note that this list may have size less than ``num_items`` in the event that there are not ``num_items`` items in the trace buffer. Raises: JLinkException: on error.
[ "Reads", "data", "from", "the", "trace", "buffer", "and", "returns", "it", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4392-L4415
236,124
square/pylink
pylink/jlink.py
JLink.swo_start
def swo_start(self, swo_speed=9600): """Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() info = structs.JLinkSWOStartInfo() info.Speed = swo_speed res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.START, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) self._swo_enabled = True return None
python
def swo_start(self, swo_speed=9600): """Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() info = structs.JLinkSWOStartInfo() info.Speed = swo_speed res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.START, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) self._swo_enabled = True return None
[ "def", "swo_start", "(", "self", ",", "swo_speed", "=", "9600", ")", ":", "if", "self", ".", "swo_enabled", "(", ")", ":", "self", ".", "swo_stop", "(", ")", "info", "=", "structs", ".", "JLinkSWOStartInfo", "(", ")", "info", ".", "Speed", "=", "swo_speed", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "START", ",", "ctypes", ".", "byref", "(", "info", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "self", ".", "_swo_enabled", "=", "True", "return", "None" ]
Starts collecting SWO data. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance swo_speed (int): the frequency in Hz used by the target to communicate Returns: ``None`` Raises: JLinkException: on error
[ "Starts", "collecting", "SWO", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4435-L4464
236,125
square/pylink
pylink/jlink.py
JLink.swo_stop
def swo_stop(self): """Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0) if res < 0: raise errors.JLinkException(res) return None
python
def swo_stop(self): """Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.STOP, 0) if res < 0: raise errors.JLinkException(res) return None
[ "def", "swo_stop", "(", "self", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "STOP", ",", "0", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Stops collecting SWO data. Args: self (JLink): the ``JLink`` instance Returns: ``None`` Raises: JLinkException: on error
[ "Stops", "collecting", "SWO", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4467-L4483
236,126
square/pylink
pylink/jlink.py
JLink.swo_enable
def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01): """Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target CPU frequency in Hz swo_speed (int): the frequency in Hz used by the target to communicate port_mask (int): port mask specifying which stimulus ports to enable Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed, swo_speed, enums.JLinkSWOInterfaces.UART, port_mask) if res != 0: raise errors.JLinkException(res) self._swo_enabled = True return None
python
def swo_enable(self, cpu_speed, swo_speed=9600, port_mask=0x01): """Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target CPU frequency in Hz swo_speed (int): the frequency in Hz used by the target to communicate port_mask (int): port mask specifying which stimulus ports to enable Returns: ``None`` Raises: JLinkException: on error """ if self.swo_enabled(): self.swo_stop() res = self._dll.JLINKARM_SWO_EnableTarget(cpu_speed, swo_speed, enums.JLinkSWOInterfaces.UART, port_mask) if res != 0: raise errors.JLinkException(res) self._swo_enabled = True return None
[ "def", "swo_enable", "(", "self", ",", "cpu_speed", ",", "swo_speed", "=", "9600", ",", "port_mask", "=", "0x01", ")", ":", "if", "self", ".", "swo_enabled", "(", ")", ":", "self", ".", "swo_stop", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_EnableTarget", "(", "cpu_speed", ",", "swo_speed", ",", "enums", ".", "JLinkSWOInterfaces", ".", "UART", ",", "port_mask", ")", "if", "res", "!=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "self", ".", "_swo_enabled", "=", "True", "return", "None" ]
Enables SWO output on the target device. Configures the output protocol, the SWO output speed, and enables any ITM & stimulus ports. This is equivalent to calling ``.swo_start()``. Note: If SWO is already enabled, it will first stop SWO before enabling it again. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target CPU frequency in Hz swo_speed (int): the frequency in Hz used by the target to communicate port_mask (int): port mask specifying which stimulus ports to enable Returns: ``None`` Raises: JLinkException: on error
[ "Enables", "SWO", "output", "on", "the", "target", "device", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4486-L4522
236,127
square/pylink
pylink/jlink.py
JLink.swo_disable
def swo_disable(self, port_mask): """Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_DisableTarget(port_mask) if res != 0: raise errors.JLinkException(res) return None
python
def swo_disable(self, port_mask): """Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_DisableTarget(port_mask) if res != 0: raise errors.JLinkException(res) return None
[ "def", "swo_disable", "(", "self", ",", "port_mask", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_DisableTarget", "(", "port_mask", ")", "if", "res", "!=", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Disables ITM & Stimulus ports. Args: self (JLink): the ``JLink`` instance port_mask (int): mask specifying which ports to disable Returns: ``None`` Raises: JLinkException: on error
[ "Disables", "ITM", "&", "Stimulus", "ports", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4525-L4541
236,128
square/pylink
pylink/jlink.py
JLink.swo_flush
def swo_flush(self, num_bytes=None): """Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error """ if num_bytes is None: num_bytes = self.swo_num_bytes() buf = ctypes.c_uint32(num_bytes) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
python
def swo_flush(self, num_bytes=None): """Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error """ if num_bytes is None: num_bytes = self.swo_num_bytes() buf = ctypes.c_uint32(num_bytes) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.FLUSH, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
[ "def", "swo_flush", "(", "self", ",", "num_bytes", "=", "None", ")", ":", "if", "num_bytes", "is", "None", ":", "num_bytes", "=", "self", ".", "swo_num_bytes", "(", ")", "buf", "=", "ctypes", ".", "c_uint32", "(", "num_bytes", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "FLUSH", ",", "ctypes", ".", "byref", "(", "buf", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Flushes data from the SWO buffer. After this method is called, the flushed part of the SWO buffer is empty. If ``num_bytes`` is not present, flushes all data currently in the SWO buffer. Args: self (JLink): the ``JLink`` instance num_bytes (int): the number of bytes to flush Returns: ``None`` Raises: JLinkException: on error
[ "Flushes", "data", "from", "the", "SWO", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4544-L4572
236,129
square/pylink
pylink/jlink.py
JLink.swo_speed_info
def swo_speed_info(self): """Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error """ info = structs.JLinkSWOSpeedInfo() res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) return info
python
def swo_speed_info(self): """Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error """ info = structs.JLinkSWOSpeedInfo() res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_SPEED_INFO, ctypes.byref(info)) if res < 0: raise errors.JLinkException(res) return info
[ "def", "swo_speed_info", "(", "self", ")", ":", "info", "=", "structs", ".", "JLinkSWOSpeedInfo", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "GET_SPEED_INFO", ",", "ctypes", ".", "byref", "(", "info", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "info" ]
Retrieves information about the supported SWO speeds. Args: self (JLink): the ``JLink`` instance Returns: A ``JLinkSWOSpeedInfo`` instance describing the target's supported SWO speeds. Raises: JLinkException: on error
[ "Retrieves", "information", "about", "the", "supported", "SWO", "speeds", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4575-L4594
236,130
square/pylink
pylink/jlink.py
JLink.swo_num_bytes
def swo_num_bytes(self): """Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_NUM_BYTES, 0) if res < 0: raise errors.JLinkException(res) return res
python
def swo_num_bytes(self): """Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error """ res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.GET_NUM_BYTES, 0) if res < 0: raise errors.JLinkException(res) return res
[ "def", "swo_num_bytes", "(", "self", ")", ":", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "GET_NUM_BYTES", ",", "0", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "res" ]
Retrives the number of bytes in the SWO buffer. Args: self (JLink): the ``JLink`` instance Returns: Number of bytes in the SWO buffer. Raises: JLinkException: on error
[ "Retrives", "the", "number", "of", "bytes", "in", "the", "SWO", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4597-L4614
236,131
square/pylink
pylink/jlink.py
JLink.swo_set_host_buffer_size
def swo_set_host_buffer_size(self, buf_size): """Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
python
def swo_set_host_buffer_size(self, buf_size): """Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_HOST, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
[ "def", "swo_set_host_buffer_size", "(", "self", ",", "buf_size", ")", ":", "buf", "=", "ctypes", ".", "c_uint32", "(", "buf_size", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "SET_BUFFERSIZE_HOST", ",", "ctypes", ".", "byref", "(", "buf", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Sets the size of the buffer used by the host to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the host buffer Returns: ``None`` Raises: JLinkException: on error
[ "Sets", "the", "size", "of", "the", "buffer", "used", "by", "the", "host", "to", "collect", "SWO", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4617-L4636
236,132
square/pylink
pylink/jlink.py
JLink.swo_set_emu_buffer_size
def swo_set_emu_buffer_size(self, buf_size): """Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
python
def swo_set_emu_buffer_size(self, buf_size): """Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error """ buf = ctypes.c_uint32(buf_size) res = self._dll.JLINKARM_SWO_Control(enums.JLinkSWOCommands.SET_BUFFERSIZE_EMU, ctypes.byref(buf)) if res < 0: raise errors.JLinkException(res) return None
[ "def", "swo_set_emu_buffer_size", "(", "self", ",", "buf_size", ")", ":", "buf", "=", "ctypes", ".", "c_uint32", "(", "buf_size", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_Control", "(", "enums", ".", "JLinkSWOCommands", ".", "SET_BUFFERSIZE_EMU", ",", "ctypes", ".", "byref", "(", "buf", ")", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "None" ]
Sets the size of the buffer used by the J-Link to collect SWO data. Args: self (JLink): the ``JLink`` instance buf_size (int): the new size of the emulator buffer Returns: ``None`` Raises: JLinkException: on error
[ "Sets", "the", "size", "of", "the", "buffer", "used", "by", "the", "J", "-", "Link", "to", "collect", "SWO", "data", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4639-L4658
236,133
square/pylink
pylink/jlink.py
JLink.swo_supported_speeds
def swo_supported_speeds(self, cpu_speed, num_speeds=3): """Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest. """ buf_size = num_speeds buf = (ctypes.c_uint32 * buf_size)() res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]
python
def swo_supported_speeds(self, cpu_speed, num_speeds=3): """Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest. """ buf_size = num_speeds buf = (ctypes.c_uint32 * buf_size)() res = self._dll.JLINKARM_SWO_GetCompatibleSpeeds(cpu_speed, 0, buf, buf_size) if res < 0: raise errors.JLinkException(res) return list(buf)[:res]
[ "def", "swo_supported_speeds", "(", "self", ",", "cpu_speed", ",", "num_speeds", "=", "3", ")", ":", "buf_size", "=", "num_speeds", "buf", "=", "(", "ctypes", ".", "c_uint32", "*", "buf_size", ")", "(", ")", "res", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_GetCompatibleSpeeds", "(", "cpu_speed", ",", "0", ",", "buf", ",", "buf_size", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkException", "(", "res", ")", "return", "list", "(", "buf", ")", "[", ":", "res", "]" ]
Retrives a list of SWO speeds supported by both the target and the connected J-Link. The supported speeds are returned in order from highest to lowest. Args: self (JLink): the ``JLink`` instance cpu_speed (int): the target's CPU speed in Hz num_speeds (int): the number of compatible speeds to return Returns: A list of compatible SWO speeds in Hz in order from highest to lowest.
[ "Retrives", "a", "list", "of", "SWO", "speeds", "supported", "by", "both", "the", "target", "and", "the", "connected", "J", "-", "Link", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4661-L4681
236,134
square/pylink
pylink/jlink.py
JLink.swo_read
def swo_read(self, offset, num_bytes, remove=False): """Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer. """ buf_size = ctypes.c_uint32(num_bytes) buf = (ctypes.c_uint8 * num_bytes)(0) self._dll.JLINKARM_SWO_Read(buf, offset, ctypes.byref(buf_size)) # After the call, ``buf_size`` has been modified to be the actual # number of bytes that was read. buf_size = buf_size.value if remove: self.swo_flush(buf_size) return list(buf)[:buf_size]
python
def swo_read(self, offset, num_bytes, remove=False): """Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer. """ buf_size = ctypes.c_uint32(num_bytes) buf = (ctypes.c_uint8 * num_bytes)(0) self._dll.JLINKARM_SWO_Read(buf, offset, ctypes.byref(buf_size)) # After the call, ``buf_size`` has been modified to be the actual # number of bytes that was read. buf_size = buf_size.value if remove: self.swo_flush(buf_size) return list(buf)[:buf_size]
[ "def", "swo_read", "(", "self", ",", "offset", ",", "num_bytes", ",", "remove", "=", "False", ")", ":", "buf_size", "=", "ctypes", ".", "c_uint32", "(", "num_bytes", ")", "buf", "=", "(", "ctypes", ".", "c_uint8", "*", "num_bytes", ")", "(", "0", ")", "self", ".", "_dll", ".", "JLINKARM_SWO_Read", "(", "buf", ",", "offset", ",", "ctypes", ".", "byref", "(", "buf_size", ")", ")", "# After the call, ``buf_size`` has been modified to be the actual", "# number of bytes that was read.", "buf_size", "=", "buf_size", ".", "value", "if", "remove", ":", "self", ".", "swo_flush", "(", "buf_size", ")", "return", "list", "(", "buf", ")", "[", ":", "buf_size", "]" ]
Reads data from the SWO buffer. The data read is not automatically removed from the SWO buffer after reading unless ``remove`` is ``True``. Otherwise the callee must explicitly remove the data by calling ``.swo_flush()``. Args: self (JLink): the ``JLink`` instance offset (int): offset of first byte to be retrieved num_bytes (int): number of bytes to read remove (bool): if data should be removed from buffer after read Returns: A list of bytes read from the SWO buffer.
[ "Reads", "data", "from", "the", "SWO", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4684-L4712
236,135
square/pylink
pylink/jlink.py
JLink.swo_read_stimulus
def swo_read_stimulus(self, port, num_bytes): """Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. Note: Stimulus port ``0`` is used for ``printf`` debugging. Args: self (JLink): the ``JLink`` instance port (int): the stimulus port to read from, ``0 - 31`` num_bytes (int): number of bytes to read Returns: A list of bytes read via SWO. Raises: ValueError: if ``port < 0`` or ``port > 31`` """ if port < 0 or port > 31: raise ValueError('Invalid port number: %s' % port) buf_size = num_bytes buf = (ctypes.c_uint8 * buf_size)() bytes_read = self._dll.JLINKARM_SWO_ReadStimulus(port, buf, buf_size) return list(buf)[:bytes_read]
python
def swo_read_stimulus(self, port, num_bytes): """Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. Note: Stimulus port ``0`` is used for ``printf`` debugging. Args: self (JLink): the ``JLink`` instance port (int): the stimulus port to read from, ``0 - 31`` num_bytes (int): number of bytes to read Returns: A list of bytes read via SWO. Raises: ValueError: if ``port < 0`` or ``port > 31`` """ if port < 0 or port > 31: raise ValueError('Invalid port number: %s' % port) buf_size = num_bytes buf = (ctypes.c_uint8 * buf_size)() bytes_read = self._dll.JLINKARM_SWO_ReadStimulus(port, buf, buf_size) return list(buf)[:bytes_read]
[ "def", "swo_read_stimulus", "(", "self", ",", "port", ",", "num_bytes", ")", ":", "if", "port", "<", "0", "or", "port", ">", "31", ":", "raise", "ValueError", "(", "'Invalid port number: %s'", "%", "port", ")", "buf_size", "=", "num_bytes", "buf", "=", "(", "ctypes", ".", "c_uint8", "*", "buf_size", ")", "(", ")", "bytes_read", "=", "self", ".", "_dll", ".", "JLINKARM_SWO_ReadStimulus", "(", "port", ",", "buf", ",", "buf_size", ")", "return", "list", "(", "buf", ")", "[", ":", "bytes_read", "]" ]
Reads the printable data via SWO. This method reads SWO for one stimulus port, which is all printable data. Note: Stimulus port ``0`` is used for ``printf`` debugging. Args: self (JLink): the ``JLink`` instance port (int): the stimulus port to read from, ``0 - 31`` num_bytes (int): number of bytes to read Returns: A list of bytes read via SWO. Raises: ValueError: if ``port < 0`` or ``port > 31``
[ "Reads", "the", "printable", "data", "via", "SWO", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4715-L4742
236,136
square/pylink
pylink/jlink.py
JLink.rtt_read
def rtt_read(self, buffer_index, num_bytes): """Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to read from num_bytes (int): the maximum number of bytes to read Returns: A list of bytes read from RTT. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails. """ buf = (ctypes.c_ubyte * num_bytes)() bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes) if bytes_read < 0: raise errors.JLinkRTTException(bytes_read) return list(buf)[:bytes_read]
python
def rtt_read(self, buffer_index, num_bytes): """Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to read from num_bytes (int): the maximum number of bytes to read Returns: A list of bytes read from RTT. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails. """ buf = (ctypes.c_ubyte * num_bytes)() bytes_read = self._dll.JLINK_RTTERMINAL_Read(buffer_index, buf, num_bytes) if bytes_read < 0: raise errors.JLinkRTTException(bytes_read) return list(buf)[:bytes_read]
[ "def", "rtt_read", "(", "self", ",", "buffer_index", ",", "num_bytes", ")", ":", "buf", "=", "(", "ctypes", ".", "c_ubyte", "*", "num_bytes", ")", "(", ")", "bytes_read", "=", "self", ".", "_dll", ".", "JLINK_RTTERMINAL_Read", "(", "buffer_index", ",", "buf", ",", "num_bytes", ")", "if", "bytes_read", "<", "0", ":", "raise", "errors", ".", "JLinkRTTException", "(", "bytes_read", ")", "return", "list", "(", "buf", ")", "[", ":", "bytes_read", "]" ]
Reads data from the RTT buffer. This method will read at most num_bytes bytes from the specified RTT buffer. The data is automatically removed from the RTT buffer. If there are not num_bytes bytes waiting in the RTT buffer, the entire contents of the RTT buffer will be read. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to read from num_bytes (int): the maximum number of bytes to read Returns: A list of bytes read from RTT. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Read call fails.
[ "Reads", "data", "from", "the", "RTT", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4805-L4830
236,137
square/pylink
pylink/jlink.py
JLink.rtt_write
def rtt_write(self, buffer_index, data): """Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to data (list): the list of bytes to write to the RTT buffer Returns: The number of bytes successfully written to the RTT buffer. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails. """ buf_size = len(data) buf = (ctypes.c_ubyte * buf_size)(*bytearray(data)) bytes_written = self._dll.JLINK_RTTERMINAL_Write(buffer_index, buf, buf_size) if bytes_written < 0: raise errors.JLinkRTTException(bytes_written) return bytes_written
python
def rtt_write(self, buffer_index, data): """Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to data (list): the list of bytes to write to the RTT buffer Returns: The number of bytes successfully written to the RTT buffer. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails. """ buf_size = len(data) buf = (ctypes.c_ubyte * buf_size)(*bytearray(data)) bytes_written = self._dll.JLINK_RTTERMINAL_Write(buffer_index, buf, buf_size) if bytes_written < 0: raise errors.JLinkRTTException(bytes_written) return bytes_written
[ "def", "rtt_write", "(", "self", ",", "buffer_index", ",", "data", ")", ":", "buf_size", "=", "len", "(", "data", ")", "buf", "=", "(", "ctypes", ".", "c_ubyte", "*", "buf_size", ")", "(", "*", "bytearray", "(", "data", ")", ")", "bytes_written", "=", "self", ".", "_dll", ".", "JLINK_RTTERMINAL_Write", "(", "buffer_index", ",", "buf", ",", "buf_size", ")", "if", "bytes_written", "<", "0", ":", "raise", "errors", ".", "JLinkRTTException", "(", "bytes_written", ")", "return", "bytes_written" ]
Writes data to the RTT buffer. This method will write at most len(data) bytes to the specified RTT buffer. Args: self (JLink): the ``JLink`` instance buffer_index (int): the index of the RTT buffer to write to data (list): the list of bytes to write to the RTT buffer Returns: The number of bytes successfully written to the RTT buffer. Raises: JLinkRTTException if the underlying JLINK_RTTERMINAL_Write call fails.
[ "Writes", "data", "to", "the", "RTT", "buffer", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4833-L4857
236,138
square/pylink
pylink/jlink.py
JLink.rtt_control
def rtt_control(self, command, config): """Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command. """ config_byref = ctypes.byref(config) if config is not None else None res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref) if res < 0: raise errors.JLinkRTTException(res) return res
python
def rtt_control(self, command, config): """Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command. """ config_byref = ctypes.byref(config) if config is not None else None res = self._dll.JLINK_RTTERMINAL_Control(command, config_byref) if res < 0: raise errors.JLinkRTTException(res) return res
[ "def", "rtt_control", "(", "self", ",", "command", ",", "config", ")", ":", "config_byref", "=", "ctypes", ".", "byref", "(", "config", ")", "if", "config", "is", "not", "None", "else", "None", "res", "=", "self", ".", "_dll", ".", "JLINK_RTTERMINAL_Control", "(", "command", ",", "config_byref", ")", "if", "res", "<", "0", ":", "raise", "errors", ".", "JLinkRTTException", "(", "res", ")", "return", "res" ]
Issues an RTT Control command. All RTT control is done through a single API call which expects specifically laid-out configuration structures. Args: self (JLink): the ``JLink`` instance command (int): the command to issue (see enums.JLinkRTTCommand) config (ctypes type): the configuration to pass by reference. Returns: An integer containing the result of the command.
[ "Issues", "an", "RTT", "Control", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/jlink.py#L4860-L4880
236,139
square/pylink
examples/rtt.py
main
def main(target_device): """Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error. """ jlink = pylink.JLink() print("connecting to JLink...") jlink.open() print("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) print("connected, starting RTT...") jlink.rtt_start() while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() print("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) try: thread.start_new_thread(read_rtt, (jlink,)) thread.start_new_thread(write_rtt, (jlink,)) while jlink.connected(): time.sleep(1) print("JLink disconnected, exiting...") except KeyboardInterrupt: print("ctrl-c detected, exiting...") pass
python
def main(target_device): """Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error. """ jlink = pylink.JLink() print("connecting to JLink...") jlink.open() print("connecting to %s..." % target_device) jlink.set_tif(pylink.enums.JLinkInterfaces.SWD) jlink.connect(target_device) print("connected, starting RTT...") jlink.rtt_start() while True: try: num_up = jlink.rtt_get_num_up_buffers() num_down = jlink.rtt_get_num_down_buffers() print("RTT started, %d up bufs, %d down bufs." % (num_up, num_down)) break except pylink.errors.JLinkRTTException: time.sleep(0.1) try: thread.start_new_thread(read_rtt, (jlink,)) thread.start_new_thread(write_rtt, (jlink,)) while jlink.connected(): time.sleep(1) print("JLink disconnected, exiting...") except KeyboardInterrupt: print("ctrl-c detected, exiting...") pass
[ "def", "main", "(", "target_device", ")", ":", "jlink", "=", "pylink", ".", "JLink", "(", ")", "print", "(", "\"connecting to JLink...\"", ")", "jlink", ".", "open", "(", ")", "print", "(", "\"connecting to %s...\"", "%", "target_device", ")", "jlink", ".", "set_tif", "(", "pylink", ".", "enums", ".", "JLinkInterfaces", ".", "SWD", ")", "jlink", ".", "connect", "(", "target_device", ")", "print", "(", "\"connected, starting RTT...\"", ")", "jlink", ".", "rtt_start", "(", ")", "while", "True", ":", "try", ":", "num_up", "=", "jlink", ".", "rtt_get_num_up_buffers", "(", ")", "num_down", "=", "jlink", ".", "rtt_get_num_down_buffers", "(", ")", "print", "(", "\"RTT started, %d up bufs, %d down bufs.\"", "%", "(", "num_up", ",", "num_down", ")", ")", "break", "except", "pylink", ".", "errors", ".", "JLinkRTTException", ":", "time", ".", "sleep", "(", "0.1", ")", "try", ":", "thread", ".", "start_new_thread", "(", "read_rtt", ",", "(", "jlink", ",", ")", ")", "thread", ".", "start_new_thread", "(", "write_rtt", ",", "(", "jlink", ",", ")", ")", "while", "jlink", ".", "connected", "(", ")", ":", "time", ".", "sleep", "(", "1", ")", "print", "(", "\"JLink disconnected, exiting...\"", ")", "except", "KeyboardInterrupt", ":", "print", "(", "\"ctrl-c detected, exiting...\"", ")", "pass" ]
Creates an interactive terminal to the target via RTT. The main loop opens a connection to the JLink, and then connects to the target device. RTT is started, the number of buffers is presented, and then two worker threads are spawned: one for read, and one for write. The main loops sleeps until the JLink is either disconnected or the user hits ctrl-c. Args: target_device (string): The target CPU to connect to. Returns: Always returns ``0`` or a JLinkException. Raises: JLinkException on error.
[ "Creates", "an", "interactive", "terminal", "to", "the", "target", "via", "RTT", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/examples/rtt.py#L93-L138
236,140
square/pylink
pylink/threads.py
ThreadReturn.run
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
python
def run(self): """Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None`` """ target = getattr(self, '_Thread__target', getattr(self, '_target', None)) args = getattr(self, '_Thread__args', getattr(self, '_args', None)) kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None)) if target is not None: self._return = target(*args, **kwargs) return None
[ "def", "run", "(", "self", ")", ":", "target", "=", "getattr", "(", "self", ",", "'_Thread__target'", ",", "getattr", "(", "self", ",", "'_target'", ",", "None", ")", ")", "args", "=", "getattr", "(", "self", ",", "'_Thread__args'", ",", "getattr", "(", "self", ",", "'_args'", ",", "None", ")", ")", "kwargs", "=", "getattr", "(", "self", ",", "'_Thread__kwargs'", ",", "getattr", "(", "self", ",", "'_kwargs'", ",", "None", ")", ")", "if", "target", "is", "not", "None", ":", "self", ".", "_return", "=", "target", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "None" ]
Runs the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance Returns: ``None``
[ "Runs", "the", "thread", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/threads.py#L41-L56
236,141
square/pylink
pylink/threads.py
ThreadReturn.join
def join(self, *args, **kwargs): """Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread. """ super(ThreadReturn, self).join(*args, **kwargs) return self._return
python
def join(self, *args, **kwargs): """Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread. """ super(ThreadReturn, self).join(*args, **kwargs) return self._return
[ "def", "join", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "ThreadReturn", ",", "self", ")", ".", "join", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "_return" ]
Joins the thread. Args: self (ThreadReturn): the ``ThreadReturn`` instance args: optional list of arguments kwargs: optional key-word arguments Returns: The return value of the exited thread.
[ "Joins", "the", "thread", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/threads.py#L58-L70
236,142
square/pylink
examples/windows_update.py
main
def main(): """Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages. """ windows_libraries = list(pylink.Library.find_library_windows()) latest_library = None for lib in windows_libraries: if os.path.dirname(lib).endswith('JLinkARM'): # Always use the one pointed to by the 'JLinkARM' directory. latest_library = lib break elif latest_library is None: latest_library = lib elif os.path.dirname(lib) > os.path.dirname(latest_library): latest_library = lib if latest_library is None: raise OSError('No J-Link library found.') library = pylink.Library(latest_library) jlink = pylink.JLink(lib=library) print('Found version: %s' % jlink.version) for emu in jlink.connected_emulators(): jlink.disable_dialog_boxes() jlink.open(serial_no=emu.SerialNumber) jlink.sync_firmware() print('Updated emulator with serial number %s' % emu.SerialNumber) return None
python
def main(): """Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages. """ windows_libraries = list(pylink.Library.find_library_windows()) latest_library = None for lib in windows_libraries: if os.path.dirname(lib).endswith('JLinkARM'): # Always use the one pointed to by the 'JLinkARM' directory. latest_library = lib break elif latest_library is None: latest_library = lib elif os.path.dirname(lib) > os.path.dirname(latest_library): latest_library = lib if latest_library is None: raise OSError('No J-Link library found.') library = pylink.Library(latest_library) jlink = pylink.JLink(lib=library) print('Found version: %s' % jlink.version) for emu in jlink.connected_emulators(): jlink.disable_dialog_boxes() jlink.open(serial_no=emu.SerialNumber) jlink.sync_firmware() print('Updated emulator with serial number %s' % emu.SerialNumber) return None
[ "def", "main", "(", ")", ":", "windows_libraries", "=", "list", "(", "pylink", ".", "Library", ".", "find_library_windows", "(", ")", ")", "latest_library", "=", "None", "for", "lib", "in", "windows_libraries", ":", "if", "os", ".", "path", ".", "dirname", "(", "lib", ")", ".", "endswith", "(", "'JLinkARM'", ")", ":", "# Always use the one pointed to by the 'JLinkARM' directory.", "latest_library", "=", "lib", "break", "elif", "latest_library", "is", "None", ":", "latest_library", "=", "lib", "elif", "os", ".", "path", ".", "dirname", "(", "lib", ")", ">", "os", ".", "path", ".", "dirname", "(", "latest_library", ")", ":", "latest_library", "=", "lib", "if", "latest_library", "is", "None", ":", "raise", "OSError", "(", "'No J-Link library found.'", ")", "library", "=", "pylink", ".", "Library", "(", "latest_library", ")", "jlink", "=", "pylink", ".", "JLink", "(", "lib", "=", "library", ")", "print", "(", "'Found version: %s'", "%", "jlink", ".", "version", ")", "for", "emu", "in", "jlink", ".", "connected_emulators", "(", ")", ":", "jlink", ".", "disable_dialog_boxes", "(", ")", "jlink", ".", "open", "(", "serial_no", "=", "emu", ".", "SerialNumber", ")", "jlink", ".", "sync_firmware", "(", ")", "print", "(", "'Updated emulator with serial number %s'", "%", "emu", ".", "SerialNumber", ")", "return", "None" ]
Upgrades the firmware of the J-Links connected to a Windows device. Returns: None. Raises: OSError: if there are no J-Link software packages.
[ "Upgrades", "the", "firmware", "of", "the", "J", "-", "Links", "connected", "to", "a", "Windows", "device", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/examples/windows_update.py#L35-L70
236,143
square/pylink
pylink/decorators.py
async_decorator
def async_decorator(func): """Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable """ @functools.wraps(func) def async_wrapper(*args, **kwargs): """Wraps up the call to ``func``, so that it is called from a separate thread. The callback, if given, will be called with two parameters, ``exception`` and ``result`` as ``callback(exception, result)``. If the thread ran to completion without error, ``exception`` will be ``None``, otherwise ``exception`` will be the generated exception that stopped the thread. Result is the result of the exected function. Args: callback (function): the callback to ultimately be called args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: A thread if the call is asynchronous, otherwise the the return value of the wrapped function. Raises: TypeError: if ``callback`` is not callable or is missing """ if 'callback' not in kwargs or not kwargs['callback']: return func(*args, **kwargs) callback = kwargs.pop('callback') if not callable(callback): raise TypeError('Expected \'callback\' is not callable.') def thread_func(*args, **kwargs): """Thread function on which the given ``func`` and ``callback`` are executed. Args: args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: Return value of the wrapped function. """ exception, res = None, None try: res = func(*args, **kwargs) except Exception as e: exception = e return callback(exception, res) thread = threads.ThreadReturn(target=thread_func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thread return async_wrapper
python
def async_decorator(func): """Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable """ @functools.wraps(func) def async_wrapper(*args, **kwargs): """Wraps up the call to ``func``, so that it is called from a separate thread. The callback, if given, will be called with two parameters, ``exception`` and ``result`` as ``callback(exception, result)``. If the thread ran to completion without error, ``exception`` will be ``None``, otherwise ``exception`` will be the generated exception that stopped the thread. Result is the result of the exected function. Args: callback (function): the callback to ultimately be called args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: A thread if the call is asynchronous, otherwise the the return value of the wrapped function. Raises: TypeError: if ``callback`` is not callable or is missing """ if 'callback' not in kwargs or not kwargs['callback']: return func(*args, **kwargs) callback = kwargs.pop('callback') if not callable(callback): raise TypeError('Expected \'callback\' is not callable.') def thread_func(*args, **kwargs): """Thread function on which the given ``func`` and ``callback`` are executed. Args: args: list of arguments to pass to ``func`` kwargs: key-word arguments dictionary to pass to ``func`` Returns: Return value of the wrapped function. """ exception, res = None, None try: res = func(*args, **kwargs) except Exception as e: exception = e return callback(exception, res) thread = threads.ThreadReturn(target=thread_func, args=args, kwargs=kwargs) thread.daemon = True thread.start() return thread return async_wrapper
[ "def", "async_decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "async_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wraps up the call to ``func``, so that it is called from a separate\n thread.\n\n The callback, if given, will be called with two parameters,\n ``exception`` and ``result`` as ``callback(exception, result)``. If\n the thread ran to completion without error, ``exception`` will be\n ``None``, otherwise ``exception`` will be the generated exception that\n stopped the thread. Result is the result of the exected function.\n\n Args:\n callback (function): the callback to ultimately be called\n args: list of arguments to pass to ``func``\n kwargs: key-word arguments dictionary to pass to ``func``\n\n Returns:\n A thread if the call is asynchronous, otherwise the the return value\n of the wrapped function.\n\n Raises:\n TypeError: if ``callback`` is not callable or is missing\n \"\"\"", "if", "'callback'", "not", "in", "kwargs", "or", "not", "kwargs", "[", "'callback'", "]", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ")", "if", "not", "callable", "(", "callback", ")", ":", "raise", "TypeError", "(", "'Expected \\'callback\\' is not callable.'", ")", "def", "thread_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Thread function on which the given ``func`` and ``callback``\n are executed.\n\n Args:\n args: list of arguments to pass to ``func``\n kwargs: key-word arguments dictionary to pass to ``func``\n\n Returns:\n Return value of the wrapped function.\n \"\"\"", "exception", ",", "res", "=", "None", ",", "None", "try", ":", "res", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "exception", "=", "e", "return", "callback", "(", "exception", ",", "res", ")", "thread", "=", "threads", ".", "ThreadReturn", "(", "target", "=", "thread_func", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "thread", ".", "daemon", "=", "True", "thread", ".", "start", "(", ")", "return", "thread", "return", "async_wrapper" ]
Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Raises: AttributeError: if ``func`` is not callable
[ "Asynchronous", "function", "decorator", ".", "Interprets", "the", "function", "as", "being", "asynchronous", "so", "returns", "a", "function", "that", "will", "handle", "calling", "the", "Function", "asynchronously", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/decorators.py#L20-L91
236,144
square/pylink
examples/strace.py
strace
def strace(device, trace_address, breakpoint_address): """Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None`` """ jlink = pylink.JLink() jlink.open() # Do the initial connection sequence. jlink.power_on() jlink.set_tif(pylink.JLinkInterfaces.SWD) jlink.connect(device) jlink.reset() # Clear any breakpoints that may exist as of now. jlink.breakpoint_clear_all() # Start the simple trace. op = pylink.JLinkStraceOperation.TRACE_START jlink.strace_clear_all() jlink.strace_start() # Set the breakpoint and trace events, then restart the CPU so that it # will execute. bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True) trhandle = jlink.strace_code_fetch_event(op, address=trace_address) jlink.restart() time.sleep(1) # Run until the CPU halts due to the breakpoint being hit. while True: if jlink.halted(): break # Print out all instructions that were captured by the trace. while True: instructions = jlink.strace_read(1) if len(instructions) == 0: break instruction = instructions[0] print(jlink.disassemble_instruction(instruction)) jlink.power_off() jlink.close()
python
def strace(device, trace_address, breakpoint_address): """Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None`` """ jlink = pylink.JLink() jlink.open() # Do the initial connection sequence. jlink.power_on() jlink.set_tif(pylink.JLinkInterfaces.SWD) jlink.connect(device) jlink.reset() # Clear any breakpoints that may exist as of now. jlink.breakpoint_clear_all() # Start the simple trace. op = pylink.JLinkStraceOperation.TRACE_START jlink.strace_clear_all() jlink.strace_start() # Set the breakpoint and trace events, then restart the CPU so that it # will execute. bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True) trhandle = jlink.strace_code_fetch_event(op, address=trace_address) jlink.restart() time.sleep(1) # Run until the CPU halts due to the breakpoint being hit. while True: if jlink.halted(): break # Print out all instructions that were captured by the trace. while True: instructions = jlink.strace_read(1) if len(instructions) == 0: break instruction = instructions[0] print(jlink.disassemble_instruction(instruction)) jlink.power_off() jlink.close()
[ "def", "strace", "(", "device", ",", "trace_address", ",", "breakpoint_address", ")", ":", "jlink", "=", "pylink", ".", "JLink", "(", ")", "jlink", ".", "open", "(", ")", "# Do the initial connection sequence.", "jlink", ".", "power_on", "(", ")", "jlink", ".", "set_tif", "(", "pylink", ".", "JLinkInterfaces", ".", "SWD", ")", "jlink", ".", "connect", "(", "device", ")", "jlink", ".", "reset", "(", ")", "# Clear any breakpoints that may exist as of now.", "jlink", ".", "breakpoint_clear_all", "(", ")", "# Start the simple trace.", "op", "=", "pylink", ".", "JLinkStraceOperation", ".", "TRACE_START", "jlink", ".", "strace_clear_all", "(", ")", "jlink", ".", "strace_start", "(", ")", "# Set the breakpoint and trace events, then restart the CPU so that it", "# will execute.", "bphandle", "=", "jlink", ".", "breakpoint_set", "(", "breakpoint_address", ",", "thumb", "=", "True", ")", "trhandle", "=", "jlink", ".", "strace_code_fetch_event", "(", "op", ",", "address", "=", "trace_address", ")", "jlink", ".", "restart", "(", ")", "time", ".", "sleep", "(", "1", ")", "# Run until the CPU halts due to the breakpoint being hit.", "while", "True", ":", "if", "jlink", ".", "halted", "(", ")", ":", "break", "# Print out all instructions that were captured by the trace.", "while", "True", ":", "instructions", "=", "jlink", ".", "strace_read", "(", "1", ")", "if", "len", "(", "instructions", ")", "==", "0", ":", "break", "instruction", "=", "instructions", "[", "0", "]", "print", "(", "jlink", ".", "disassemble_instruction", "(", "instruction", ")", ")", "jlink", ".", "power_off", "(", ")", "jlink", ".", "close", "(", ")" ]
Implements simple trace using the STrace API. Args: device (str): the device to connect to trace_address (int): address to begin tracing from breakpoint_address (int): address to breakpoint at Returns: ``None``
[ "Implements", "simple", "trace", "using", "the", "STrace", "API", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/examples/strace.py#L29-L78
236,145
square/pylink
pylink/__main__.py
create_parser
def create_parser(): """Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI. """ parser = argparse.ArgumentParser(prog=pylink.__title__, description=pylink.__description__, epilog=pylink.__copyright__) parser.add_argument('--version', action='version', version='%(prog)s ' + pylink.__version__) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase output verbosity') kwargs = {} kwargs['title'] = 'command' kwargs['description'] = 'specify subcommand to run' kwargs['help'] = 'subcommands' subparsers = parser.add_subparsers(**kwargs) for command in commands(): kwargs = {} kwargs['name'] = command.name kwargs['description'] = command.description kwargs['help'] = command.help subparser = subparsers.add_parser(**kwargs) subparser.set_defaults(command=command.run) command.add_arguments(subparser) return parser
python
def create_parser(): """Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI. """ parser = argparse.ArgumentParser(prog=pylink.__title__, description=pylink.__description__, epilog=pylink.__copyright__) parser.add_argument('--version', action='version', version='%(prog)s ' + pylink.__version__) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase output verbosity') kwargs = {} kwargs['title'] = 'command' kwargs['description'] = 'specify subcommand to run' kwargs['help'] = 'subcommands' subparsers = parser.add_subparsers(**kwargs) for command in commands(): kwargs = {} kwargs['name'] = command.name kwargs['description'] = command.description kwargs['help'] = command.help subparser = subparsers.add_parser(**kwargs) subparser.set_defaults(command=command.run) command.add_arguments(subparser) return parser
[ "def", "create_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "pylink", ".", "__title__", ",", "description", "=", "pylink", ".", "__description__", ",", "epilog", "=", "pylink", ".", "__copyright__", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'version'", ",", "version", "=", "'%(prog)s '", "+", "pylink", ".", "__version__", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--verbose'", ",", "action", "=", "'count'", ",", "default", "=", "0", ",", "help", "=", "'increase output verbosity'", ")", "kwargs", "=", "{", "}", "kwargs", "[", "'title'", "]", "=", "'command'", "kwargs", "[", "'description'", "]", "=", "'specify subcommand to run'", "kwargs", "[", "'help'", "]", "=", "'subcommands'", "subparsers", "=", "parser", ".", "add_subparsers", "(", "*", "*", "kwargs", ")", "for", "command", "in", "commands", "(", ")", ":", "kwargs", "=", "{", "}", "kwargs", "[", "'name'", "]", "=", "command", ".", "name", "kwargs", "[", "'description'", "]", "=", "command", ".", "description", "kwargs", "[", "'help'", "]", "=", "command", ".", "help", "subparser", "=", "subparsers", ".", "add_parser", "(", "*", "*", "kwargs", ")", "subparser", ".", "set_defaults", "(", "command", "=", "command", ".", "run", ")", "command", ".", "add_arguments", "(", "subparser", ")", "return", "parser" ]
Builds the command parser. This needs to be exported in order for Sphinx to document it correctly. Returns: An instance of an ``argparse.ArgumentParser`` that parses all the commands supported by the PyLink CLI.
[ "Builds", "the", "command", "parser", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L535-L567
236,146
square/pylink
pylink/__main__.py
main
def main(args=None): """Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise. """ if args is None: args = sys.argv[1:] parser = create_parser() args = parser.parse_args(args) if args.verbose >= 2: level = logging.DEBUG elif args.verbose >= 1: level = logging.INFO else: level = logging.WARNING logging.basicConfig(level=level) try: args.command(args) except pylink.JLinkException as e: sys.stderr.write('Error: %s%s' % (str(e), os.linesep)) return 1 return 0
python
def main(args=None): """Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise. """ if args is None: args = sys.argv[1:] parser = create_parser() args = parser.parse_args(args) if args.verbose >= 2: level = logging.DEBUG elif args.verbose >= 1: level = logging.INFO else: level = logging.WARNING logging.basicConfig(level=level) try: args.command(args) except pylink.JLinkException as e: sys.stderr.write('Error: %s%s' % (str(e), os.linesep)) return 1 return 0
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "args", ")", "if", "args", ".", "verbose", ">=", "2", ":", "level", "=", "logging", ".", "DEBUG", "elif", "args", ".", "verbose", ">=", "1", ":", "level", "=", "logging", ".", "INFO", "else", ":", "level", "=", "logging", ".", "WARNING", "logging", ".", "basicConfig", "(", "level", "=", "level", ")", "try", ":", "args", ".", "command", "(", "args", ")", "except", "pylink", ".", "JLinkException", "as", "e", ":", "sys", ".", "stderr", ".", "write", "(", "'Error: %s%s'", "%", "(", "str", "(", "e", ")", ",", "os", ".", "linesep", ")", ")", "return", "1", "return", "0" ]
Main command-line interface entrypoint. Runs the given subcommand or argument that were specified. If not given a ``args`` parameter, assumes the arguments are passed on the command-line. Args: args (list): list of command-line arguments Returns: Zero on success, non-zero otherwise.
[ "Main", "command", "-", "line", "interface", "entrypoint", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L570-L603
236,147
square/pylink
pylink/__main__.py
Command.create_jlink
def create_jlink(self, args): """Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``. """ jlink = pylink.JLink() jlink.open(args.serial_no, args.ip_addr) if hasattr(args, 'tif') and args.tif is not None: if args.tif.lower() == 'swd': jlink.set_tif(pylink.JLinkInterfaces.SWD) else: jlink.set_tif(pylink.JLinkInterfaces.JTAG) if hasattr(args, 'device') and args.device is not None: jlink.connect(args.device) return jlink
python
def create_jlink(self, args): """Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``. """ jlink = pylink.JLink() jlink.open(args.serial_no, args.ip_addr) if hasattr(args, 'tif') and args.tif is not None: if args.tif.lower() == 'swd': jlink.set_tif(pylink.JLinkInterfaces.SWD) else: jlink.set_tif(pylink.JLinkInterfaces.JTAG) if hasattr(args, 'device') and args.device is not None: jlink.connect(args.device) return jlink
[ "def", "create_jlink", "(", "self", ",", "args", ")", ":", "jlink", "=", "pylink", ".", "JLink", "(", ")", "jlink", ".", "open", "(", "args", ".", "serial_no", ",", "args", ".", "ip_addr", ")", "if", "hasattr", "(", "args", ",", "'tif'", ")", "and", "args", ".", "tif", "is", "not", "None", ":", "if", "args", ".", "tif", ".", "lower", "(", ")", "==", "'swd'", ":", "jlink", ".", "set_tif", "(", "pylink", ".", "JLinkInterfaces", ".", "SWD", ")", "else", ":", "jlink", ".", "set_tif", "(", "pylink", ".", "JLinkInterfaces", ".", "JTAG", ")", "if", "hasattr", "(", "args", ",", "'device'", ")", "and", "args", ".", "device", "is", "not", "None", ":", "jlink", ".", "connect", "(", "args", ".", "device", ")", "return", "jlink" ]
Creates an instance of a J-Link from the given arguments. Args: self (Command): the ``Command`` instance args (Namespace): arguments to construct the ``JLink`` instance from Returns: An instance of a ``JLink``.
[ "Creates", "an", "instance", "of", "a", "J", "-", "Link", "from", "the", "given", "arguments", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L66-L88
236,148
square/pylink
pylink/__main__.py
Command.add_common_arguments
def add_common_arguments(self, parser, has_device=False): """Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None`` """ if has_device: parser.add_argument('-t', '--tif', required=True, type=str.lower, choices=['jtag', 'swd'], help='target interface (JTAG | SWD)') parser.add_argument('-d', '--device', required=True, help='specify the target device name') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-s', '--serial', dest='serial_no', help='specify the J-Link serial number') group.add_argument('-i', '--ip_addr', dest='ip_addr', help='J-Link IP address') return None
python
def add_common_arguments(self, parser, has_device=False): """Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None`` """ if has_device: parser.add_argument('-t', '--tif', required=True, type=str.lower, choices=['jtag', 'swd'], help='target interface (JTAG | SWD)') parser.add_argument('-d', '--device', required=True, help='specify the target device name') group = parser.add_mutually_exclusive_group(required=False) group.add_argument('-s', '--serial', dest='serial_no', help='specify the J-Link serial number') group.add_argument('-i', '--ip_addr', dest='ip_addr', help='J-Link IP address') return None
[ "def", "add_common_arguments", "(", "self", ",", "parser", ",", "has_device", "=", "False", ")", ":", "if", "has_device", ":", "parser", ".", "add_argument", "(", "'-t'", ",", "'--tif'", ",", "required", "=", "True", ",", "type", "=", "str", ".", "lower", ",", "choices", "=", "[", "'jtag'", ",", "'swd'", "]", ",", "help", "=", "'target interface (JTAG | SWD)'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--device'", ",", "required", "=", "True", ",", "help", "=", "'specify the target device name'", ")", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", "required", "=", "False", ")", "group", ".", "add_argument", "(", "'-s'", ",", "'--serial'", ",", "dest", "=", "'serial_no'", ",", "help", "=", "'specify the J-Link serial number'", ")", "group", ".", "add_argument", "(", "'-i'", ",", "'--ip_addr'", ",", "dest", "=", "'ip_addr'", ",", "help", "=", "'J-Link IP address'", ")", "return", "None" ]
Adds common arguments to the given parser. Common arguments for a J-Link command are the target interface, and J-Link serial number or IP address. Args: self (Command): the ``Command`` instance parser (argparse.ArgumentParser): the parser to add the arguments to has_device (bool): boolean indicating if it has the device argument Returns: ``None``
[ "Adds", "common", "arguments", "to", "the", "given", "parser", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L90-L117
236,149
square/pylink
pylink/__main__.py
EraseCommand.run
def run(self, args): """Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) erased = jlink.erase() print('Bytes Erased: %d' % erased)
python
def run(self, args): """Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) erased = jlink.erase() print('Bytes Erased: %d' % erased)
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "erased", "=", "jlink", ".", "erase", "(", ")", "print", "(", "'Bytes Erased: %d'", "%", "erased", ")" ]
Erases the device connected to the J-Link. Args: self (EraseCommand): the ``EraseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
[ "Erases", "the", "device", "connected", "to", "the", "J", "-", "Link", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L172-L184
236,150
square/pylink
pylink/__main__.py
FlashCommand.run
def run(self, args): """Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ kwargs = {} kwargs['path'] = args.file[0] kwargs['addr'] = args.addr kwargs['on_progress'] = pylink.util.flash_progress_callback jlink = self.create_jlink(args) _ = jlink.flash_file(**kwargs) print('Flashed device successfully.')
python
def run(self, args): """Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ kwargs = {} kwargs['path'] = args.file[0] kwargs['addr'] = args.addr kwargs['on_progress'] = pylink.util.flash_progress_callback jlink = self.create_jlink(args) _ = jlink.flash_file(**kwargs) print('Flashed device successfully.')
[ "def", "run", "(", "self", ",", "args", ")", ":", "kwargs", "=", "{", "}", "kwargs", "[", "'path'", "]", "=", "args", ".", "file", "[", "0", "]", "kwargs", "[", "'addr'", "]", "=", "args", ".", "addr", "kwargs", "[", "'on_progress'", "]", "=", "pylink", ".", "util", ".", "flash_progress_callback", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "_", "=", "jlink", ".", "flash_file", "(", "*", "*", "kwargs", ")", "print", "(", "'Flashed device successfully.'", ")" ]
Flashes the device connected to the J-Link. Args: self (FlashCommand): the ``FlashCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
[ "Flashes", "the", "device", "connected", "to", "the", "J", "-", "Link", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L208-L225
236,151
square/pylink
pylink/__main__.py
UnlockCommand.add_arguments
def add_arguments(self, parser): """Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None`` """ parser.add_argument('name', nargs=1, choices=['kinetis'], help='name of MCU to unlock') return self.add_common_arguments(parser, True)
python
def add_arguments(self, parser): """Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None`` """ parser.add_argument('name', nargs=1, choices=['kinetis'], help='name of MCU to unlock') return self.add_common_arguments(parser, True)
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'name'", ",", "nargs", "=", "1", ",", "choices", "=", "[", "'kinetis'", "]", ",", "help", "=", "'name of MCU to unlock'", ")", "return", "self", ".", "add_common_arguments", "(", "parser", ",", "True", ")" ]
Adds the unlock command arguments to the parser. Args: self (UnlockCommand): the ``UnlockCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None``
[ "Adds", "the", "unlock", "command", "arguments", "to", "the", "parser", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L237-L249
236,152
square/pylink
pylink/__main__.py
UnlockCommand.run
def run(self, args): """Unlocks the target device. Args: self (UnlockCommand): the ``UnlockCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) mcu = args.name[0].lower() if pylink.unlock(jlink, mcu): print('Successfully unlocked device!') else: print('Failed to unlock device!')
python
def run(self, args): """Unlocks the target device. Args: self (UnlockCommand): the ``UnlockCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) mcu = args.name[0].lower() if pylink.unlock(jlink, mcu): print('Successfully unlocked device!') else: print('Failed to unlock device!')
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "mcu", "=", "args", ".", "name", "[", "0", "]", ".", "lower", "(", ")", "if", "pylink", ".", "unlock", "(", "jlink", ",", "mcu", ")", ":", "print", "(", "'Successfully unlocked device!'", ")", "else", ":", "print", "(", "'Failed to unlock device!'", ")" ]
Unlocks the target device. Args: self (UnlockCommand): the ``UnlockCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
[ "Unlocks", "the", "target", "device", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L251-L266
236,153
square/pylink
pylink/__main__.py
LicenseCommand.run
def run(self, args): """Runs the license command. Args: self (LicenseCommand): the ``LicenseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) if args.list: print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(','))) print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(','))) elif args.add is not None: if jlink.add_license(args.add): print('Successfully added license.') else: print('License already exists.') elif args.erase: if jlink.erase_licenses(): print('Successfully erased all custom licenses.') else: print('Failed to erase custom licenses.')
python
def run(self, args): """Runs the license command. Args: self (LicenseCommand): the ``LicenseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) if args.list: print('Built-in Licenses: %s' % ', '.join(jlink.licenses.split(','))) print('Custom Licenses: %s' % ', '.join(jlink.custom_licenses.split(','))) elif args.add is not None: if jlink.add_license(args.add): print('Successfully added license.') else: print('License already exists.') elif args.erase: if jlink.erase_licenses(): print('Successfully erased all custom licenses.') else: print('Failed to erase custom licenses.')
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "if", "args", ".", "list", ":", "print", "(", "'Built-in Licenses: %s'", "%", "', '", ".", "join", "(", "jlink", ".", "licenses", ".", "split", "(", "','", ")", ")", ")", "print", "(", "'Custom Licenses: %s'", "%", "', '", ".", "join", "(", "jlink", ".", "custom_licenses", ".", "split", "(", "','", ")", ")", ")", "elif", "args", ".", "add", "is", "not", "None", ":", "if", "jlink", ".", "add_license", "(", "args", ".", "add", ")", ":", "print", "(", "'Successfully added license.'", ")", "else", ":", "print", "(", "'License already exists.'", ")", "elif", "args", ".", "erase", ":", "if", "jlink", ".", "erase_licenses", "(", ")", ":", "print", "(", "'Successfully erased all custom licenses.'", ")", "else", ":", "print", "(", "'Failed to erase custom licenses.'", ")" ]
Runs the license command. Args: self (LicenseCommand): the ``LicenseCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
[ "Runs", "the", "license", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L294-L317
236,154
square/pylink
pylink/__main__.py
InfoCommand.add_arguments
def add_arguments(self, parser): """Adds the information commands to the parser. Args: self (InfoCommand): the ``InfoCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None`` """ parser.add_argument('-p', '--product', action='store_true', help='print the production information') parser.add_argument('-j', '--jtag', action='store_true', help='print the JTAG pin status') return self.add_common_arguments(parser, False)
python
def add_arguments(self, parser): """Adds the information commands to the parser. Args: self (InfoCommand): the ``InfoCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None`` """ parser.add_argument('-p', '--product', action='store_true', help='print the production information') parser.add_argument('-j', '--jtag', action='store_true', help='print the JTAG pin status') return self.add_common_arguments(parser, False)
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "parser", ".", "add_argument", "(", "'-p'", ",", "'--product'", ",", "action", "=", "'store_true'", ",", "help", "=", "'print the production information'", ")", "parser", ".", "add_argument", "(", "'-j'", ",", "'--jtag'", ",", "action", "=", "'store_true'", ",", "help", "=", "'print the JTAG pin status'", ")", "return", "self", ".", "add_common_arguments", "(", "parser", ",", "False", ")" ]
Adds the information commands to the parser. Args: self (InfoCommand): the ``InfoCommand`` instance parser (argparse.ArgumentParser): the parser to add the arguments to Returns: ``None``
[ "Adds", "the", "information", "commands", "to", "the", "parser", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L326-L340
236,155
square/pylink
pylink/__main__.py
InfoCommand.run
def run(self, args): """Runs the information command. Args: self (InfoCommand): the ``InfoCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) if args.product: print('Product: %s' % jlink.product_name) manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem print('Manufacturer: %s' % manufacturer) print('Hardware Version: %s' % jlink.hardware_version) print('Firmware: %s' % jlink.firmware_version) print('DLL Version: %s' % jlink.version) print('Features: %s' % ', '.join(jlink.features)) elif args.jtag: status = jlink.hardware_status print('TCK Pin Status: %d' % status.tck) print('TDI Pin Status: %d' % status.tdi) print('TDO Pin Status: %d' % status.tdo) print('TMS Pin Status: %d' % status.tms) print('TRES Pin Status: %d' % status.tres) print('TRST Pin Status: %d' % status.trst)
python
def run(self, args): """Runs the information command. Args: self (InfoCommand): the ``InfoCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None`` """ jlink = self.create_jlink(args) if args.product: print('Product: %s' % jlink.product_name) manufacturer = 'SEGGER' if jlink.oem is None else jlink.oem print('Manufacturer: %s' % manufacturer) print('Hardware Version: %s' % jlink.hardware_version) print('Firmware: %s' % jlink.firmware_version) print('DLL Version: %s' % jlink.version) print('Features: %s' % ', '.join(jlink.features)) elif args.jtag: status = jlink.hardware_status print('TCK Pin Status: %d' % status.tck) print('TDI Pin Status: %d' % status.tdi) print('TDO Pin Status: %d' % status.tdo) print('TMS Pin Status: %d' % status.tms) print('TRES Pin Status: %d' % status.tres) print('TRST Pin Status: %d' % status.trst)
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "if", "args", ".", "product", ":", "print", "(", "'Product: %s'", "%", "jlink", ".", "product_name", ")", "manufacturer", "=", "'SEGGER'", "if", "jlink", ".", "oem", "is", "None", "else", "jlink", ".", "oem", "print", "(", "'Manufacturer: %s'", "%", "manufacturer", ")", "print", "(", "'Hardware Version: %s'", "%", "jlink", ".", "hardware_version", ")", "print", "(", "'Firmware: %s'", "%", "jlink", ".", "firmware_version", ")", "print", "(", "'DLL Version: %s'", "%", "jlink", ".", "version", ")", "print", "(", "'Features: %s'", "%", "', '", ".", "join", "(", "jlink", ".", "features", ")", ")", "elif", "args", ".", "jtag", ":", "status", "=", "jlink", ".", "hardware_status", "print", "(", "'TCK Pin Status: %d'", "%", "status", ".", "tck", ")", "print", "(", "'TDI Pin Status: %d'", "%", "status", ".", "tdi", ")", "print", "(", "'TDO Pin Status: %d'", "%", "status", ".", "tdo", ")", "print", "(", "'TMS Pin Status: %d'", "%", "status", ".", "tms", ")", "print", "(", "'TRES Pin Status: %d'", "%", "status", ".", "tres", ")", "print", "(", "'TRST Pin Status: %d'", "%", "status", ".", "trst", ")" ]
Runs the information command. Args: self (InfoCommand): the ``InfoCommand`` instance args (Namespace): the arguments passed on the command-line Returns: ``None``
[ "Runs", "the", "information", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L342-L370
236,156
square/pylink
pylink/__main__.py
EmulatorCommand.add_arguments
def add_arguments(self, parser): """Adds the arguments for the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', nargs='?', type=str.lower, default='_', choices=['usb', 'ip'], help='list all the connected emulators') group.add_argument('-s', '--supported', nargs=1, help='query whether a device is supported') group.add_argument('-t', '--test', action='store_true', help='perform a self-test') return None
python
def add_arguments(self, parser): """Adds the arguments for the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', nargs='?', type=str.lower, default='_', choices=['usb', 'ip'], help='list all the connected emulators') group.add_argument('-s', '--supported', nargs=1, help='query whether a device is supported') group.add_argument('-t', '--test', action='store_true', help='perform a self-test') return None
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", "required", "=", "True", ")", "group", ".", "add_argument", "(", "'-l'", ",", "'--list'", ",", "nargs", "=", "'?'", ",", "type", "=", "str", ".", "lower", ",", "default", "=", "'_'", ",", "choices", "=", "[", "'usb'", ",", "'ip'", "]", ",", "help", "=", "'list all the connected emulators'", ")", "group", ".", "add_argument", "(", "'-s'", ",", "'--supported'", ",", "nargs", "=", "1", ",", "help", "=", "'query whether a device is supported'", ")", "group", ".", "add_argument", "(", "'-t'", ",", "'--test'", ",", "action", "=", "'store_true'", ",", "help", "=", "'perform a self-test'", ")", "return", "None" ]
Adds the arguments for the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None``
[ "Adds", "the", "arguments", "for", "the", "emulator", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L379-L398
236,157
square/pylink
pylink/__main__.py
EmulatorCommand.run
def run(self, args): """Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = pylink.JLink() if args.test: if jlink.test(): print('Self-test succeeded.') else: print('Self-test failed.') elif args.list is None or args.list in ['usb', 'ip']: host = pylink.JLinkHost.USB_OR_IP if args.list == 'usb': host = pylink.JLinkHost.USB elif args.list == 'ip': host = pylink.JLinkHost.IP emulators = jlink.connected_emulators(host) for (index, emulator) in enumerate(emulators): if index > 0: print('') print('Product Name: %s' % emulator.acProduct.decode()) print('Serial Number: %s' % emulator.SerialNumber) usb = bool(emulator.Connection) if not usb: print('Nickname: %s' % emulator.acNickname.decode()) print('Firmware: %s' % emulator.acFWString.decode()) print('Connection: %s' % ('USB' if usb else 'IP')) if not usb: print('IP Address: %s' % emulator.aIPAddr) elif args.supported is not None: device = args.supported[0] num_supported_devices = jlink.num_supported_devices() for i in range(num_supported_devices): found_device = jlink.supported_device(i) if device.lower() == found_device.name.lower(): print('Device Name: %s' % device) print('Core ID: %s' % found_device.CoreId) print('Flash Address: %s' % found_device.FlashAddr) print('Flash Size: %s bytes' % found_device.FlashSize) print('RAM Address: %s' % found_device.RAMAddr) print('RAM Size: %s bytes' % found_device.RAMSize) print('Manufacturer: %s' % found_device.manufacturer) break else: print('%s is not supported :(' % device) return None
python
def run(self, args): """Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = pylink.JLink() if args.test: if jlink.test(): print('Self-test succeeded.') else: print('Self-test failed.') elif args.list is None or args.list in ['usb', 'ip']: host = pylink.JLinkHost.USB_OR_IP if args.list == 'usb': host = pylink.JLinkHost.USB elif args.list == 'ip': host = pylink.JLinkHost.IP emulators = jlink.connected_emulators(host) for (index, emulator) in enumerate(emulators): if index > 0: print('') print('Product Name: %s' % emulator.acProduct.decode()) print('Serial Number: %s' % emulator.SerialNumber) usb = bool(emulator.Connection) if not usb: print('Nickname: %s' % emulator.acNickname.decode()) print('Firmware: %s' % emulator.acFWString.decode()) print('Connection: %s' % ('USB' if usb else 'IP')) if not usb: print('IP Address: %s' % emulator.aIPAddr) elif args.supported is not None: device = args.supported[0] num_supported_devices = jlink.num_supported_devices() for i in range(num_supported_devices): found_device = jlink.supported_device(i) if device.lower() == found_device.name.lower(): print('Device Name: %s' % device) print('Core ID: %s' % found_device.CoreId) print('Flash Address: %s' % found_device.FlashAddr) print('Flash Size: %s bytes' % found_device.FlashSize) print('RAM Address: %s' % found_device.RAMAddr) print('RAM Size: %s bytes' % found_device.RAMSize) print('Manufacturer: %s' % found_device.manufacturer) break else: print('%s is not supported :(' % device) return None
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "pylink", ".", "JLink", "(", ")", "if", "args", ".", "test", ":", "if", "jlink", ".", "test", "(", ")", ":", "print", "(", "'Self-test succeeded.'", ")", "else", ":", "print", "(", "'Self-test failed.'", ")", "elif", "args", ".", "list", "is", "None", "or", "args", ".", "list", "in", "[", "'usb'", ",", "'ip'", "]", ":", "host", "=", "pylink", ".", "JLinkHost", ".", "USB_OR_IP", "if", "args", ".", "list", "==", "'usb'", ":", "host", "=", "pylink", ".", "JLinkHost", ".", "USB", "elif", "args", ".", "list", "==", "'ip'", ":", "host", "=", "pylink", ".", "JLinkHost", ".", "IP", "emulators", "=", "jlink", ".", "connected_emulators", "(", "host", ")", "for", "(", "index", ",", "emulator", ")", "in", "enumerate", "(", "emulators", ")", ":", "if", "index", ">", "0", ":", "print", "(", "''", ")", "print", "(", "'Product Name: %s'", "%", "emulator", ".", "acProduct", ".", "decode", "(", ")", ")", "print", "(", "'Serial Number: %s'", "%", "emulator", ".", "SerialNumber", ")", "usb", "=", "bool", "(", "emulator", ".", "Connection", ")", "if", "not", "usb", ":", "print", "(", "'Nickname: %s'", "%", "emulator", ".", "acNickname", ".", "decode", "(", ")", ")", "print", "(", "'Firmware: %s'", "%", "emulator", ".", "acFWString", ".", "decode", "(", ")", ")", "print", "(", "'Connection: %s'", "%", "(", "'USB'", "if", "usb", "else", "'IP'", ")", ")", "if", "not", "usb", ":", "print", "(", "'IP Address: %s'", "%", "emulator", ".", "aIPAddr", ")", "elif", "args", ".", "supported", "is", "not", "None", ":", "device", "=", "args", ".", "supported", "[", "0", "]", "num_supported_devices", "=", "jlink", ".", "num_supported_devices", "(", ")", "for", "i", "in", "range", "(", "num_supported_devices", ")", ":", "found_device", "=", "jlink", ".", "supported_device", "(", "i", ")", "if", "device", ".", "lower", "(", ")", "==", "found_device", ".", "name", ".", "lower", "(", ")", ":", "print", "(", "'Device Name: %s'", "%", "device", ")", "print", "(", "'Core ID: %s'", "%", "found_device", ".", "CoreId", ")", "print", "(", "'Flash Address: %s'", "%", "found_device", ".", "FlashAddr", ")", "print", "(", "'Flash Size: %s bytes'", "%", "found_device", ".", "FlashSize", ")", "print", "(", "'RAM Address: %s'", "%", "found_device", ".", "RAMAddr", ")", "print", "(", "'RAM Size: %s bytes'", "%", "found_device", ".", "RAMSize", ")", "print", "(", "'Manufacturer: %s'", "%", "found_device", ".", "manufacturer", ")", "break", "else", ":", "print", "(", "'%s is not supported :('", "%", "device", ")", "return", "None" ]
Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None``
[ "Runs", "the", "emulator", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L400-L458
236,158
square/pylink
pylink/__main__.py
FirmwareCommand.add_arguments
def add_arguments(self, parser): """Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--downgrade', action='store_true', help='downgrade the J-Link firmware') group.add_argument('-u', '--upgrade', action='store_true', help='upgrade the J-Link firmware') return self.add_common_arguments(parser, False)
python
def add_arguments(self, parser): """Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None`` """ group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-d', '--downgrade', action='store_true', help='downgrade the J-Link firmware') group.add_argument('-u', '--upgrade', action='store_true', help='upgrade the J-Link firmware') return self.add_common_arguments(parser, False)
[ "def", "add_arguments", "(", "self", ",", "parser", ")", ":", "group", "=", "parser", ".", "add_mutually_exclusive_group", "(", "required", "=", "True", ")", "group", ".", "add_argument", "(", "'-d'", ",", "'--downgrade'", ",", "action", "=", "'store_true'", ",", "help", "=", "'downgrade the J-Link firmware'", ")", "group", ".", "add_argument", "(", "'-u'", ",", "'--upgrade'", ",", "action", "=", "'store_true'", ",", "help", "=", "'upgrade the J-Link firmware'", ")", "return", "self", ".", "add_common_arguments", "(", "parser", ",", "False", ")" ]
Adds the arguments for the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance parser (argparse.ArgumentParser): parser to add the commands to Returns: ``None``
[ "Adds", "the", "arguments", "for", "the", "firmware", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L467-L482
236,159
square/pylink
pylink/__main__.py
FirmwareCommand.run
def run(self, args): """Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = self.create_jlink(args) if args.downgrade: if not jlink.firmware_newer(): print('DLL firmware is not older than J-Link firmware.') else: jlink.invalidate_firmware() try: # Change to the firmware of the connected DLL. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Downgraded: %s' % jlink.firmware_version) elif args.upgrade: if not jlink.firmware_outdated(): print('DLL firmware is not newer than J-Link firmware.') else: try: # Upgrade the firmware. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Updated: %s' % jlink.firmware_version) return None
python
def run(self, args): """Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = self.create_jlink(args) if args.downgrade: if not jlink.firmware_newer(): print('DLL firmware is not older than J-Link firmware.') else: jlink.invalidate_firmware() try: # Change to the firmware of the connected DLL. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Downgraded: %s' % jlink.firmware_version) elif args.upgrade: if not jlink.firmware_outdated(): print('DLL firmware is not newer than J-Link firmware.') else: try: # Upgrade the firmware. jlink.update_firmware() except pylink.JLinkException as e: # On J-Link versions < 5.0.0, an exception will be thrown as # the connection will be lost, so we have to re-establish. jlink = self.create_jlink(args) print('Firmware Updated: %s' % jlink.firmware_version) return None
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "if", "args", ".", "downgrade", ":", "if", "not", "jlink", ".", "firmware_newer", "(", ")", ":", "print", "(", "'DLL firmware is not older than J-Link firmware.'", ")", "else", ":", "jlink", ".", "invalidate_firmware", "(", ")", "try", ":", "# Change to the firmware of the connected DLL.", "jlink", ".", "update_firmware", "(", ")", "except", "pylink", ".", "JLinkException", "as", "e", ":", "# On J-Link versions < 5.0.0, an exception will be thrown as", "# the connection will be lost, so we have to re-establish.", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "print", "(", "'Firmware Downgraded: %s'", "%", "jlink", ".", "firmware_version", ")", "elif", "args", ".", "upgrade", ":", "if", "not", "jlink", ".", "firmware_outdated", "(", ")", ":", "print", "(", "'DLL firmware is not newer than J-Link firmware.'", ")", "else", ":", "try", ":", "# Upgrade the firmware.", "jlink", ".", "update_firmware", "(", ")", "except", "pylink", ".", "JLinkException", "as", "e", ":", "# On J-Link versions < 5.0.0, an exception will be thrown as", "# the connection will be lost, so we have to re-establish.", "jlink", "=", "self", ".", "create_jlink", "(", "args", ")", "print", "(", "'Firmware Updated: %s'", "%", "jlink", ".", "firmware_version", ")", "return", "None" ]
Runs the firmware command. Args: self (FirmwareCommand): the ``FirmwareCommand`` instance args (Namespace): arguments to parse Returns: ``None``
[ "Runs", "the", "firmware", "command", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/__main__.py#L484-L523
236,160
square/pylink
pylink/structs.py
JLinkDeviceInfo.name
def name(self): """Returns the name of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Device name. """ return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()
python
def name(self): """Returns the name of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Device name. """ return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()
[ "def", "name", "(", "self", ")", ":", "return", "ctypes", ".", "cast", "(", "self", ".", "sName", ",", "ctypes", ".", "c_char_p", ")", ".", "value", ".", "decode", "(", ")" ]
Returns the name of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Device name.
[ "Returns", "the", "name", "of", "the", "device", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L207-L216
236,161
square/pylink
pylink/structs.py
JLinkDeviceInfo.manufacturer
def manufacturer(self): """Returns the name of the manufacturer of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Manufacturer name. """ buf = ctypes.cast(self.sManu, ctypes.c_char_p).value return buf.decode() if buf else None
python
def manufacturer(self): """Returns the name of the manufacturer of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Manufacturer name. """ buf = ctypes.cast(self.sManu, ctypes.c_char_p).value return buf.decode() if buf else None
[ "def", "manufacturer", "(", "self", ")", ":", "buf", "=", "ctypes", ".", "cast", "(", "self", ".", "sManu", ",", "ctypes", ".", "c_char_p", ")", ".", "value", "return", "buf", ".", "decode", "(", ")", "if", "buf", "else", "None" ]
Returns the name of the manufacturer of the device. Args: self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance Returns: Manufacturer name.
[ "Returns", "the", "name", "of", "the", "manufacturer", "of", "the", "device", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L219-L229
236,162
square/pylink
pylink/structs.py
JLinkBreakpointInfo.software_breakpoint
def software_breakpoint(self): """Returns whether this is a software breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: ``True`` if the breakpoint is a software breakpoint, otherwise ``False``. """ software_types = [ enums.JLinkBreakpoint.SW_RAM, enums.JLinkBreakpoint.SW_FLASH, enums.JLinkBreakpoint.SW ] return any(self.Type & stype for stype in software_types)
python
def software_breakpoint(self): """Returns whether this is a software breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: ``True`` if the breakpoint is a software breakpoint, otherwise ``False``. """ software_types = [ enums.JLinkBreakpoint.SW_RAM, enums.JLinkBreakpoint.SW_FLASH, enums.JLinkBreakpoint.SW ] return any(self.Type & stype for stype in software_types)
[ "def", "software_breakpoint", "(", "self", ")", ":", "software_types", "=", "[", "enums", ".", "JLinkBreakpoint", ".", "SW_RAM", ",", "enums", ".", "JLinkBreakpoint", ".", "SW_FLASH", ",", "enums", ".", "JLinkBreakpoint", ".", "SW", "]", "return", "any", "(", "self", ".", "Type", "&", "stype", "for", "stype", "in", "software_types", ")" ]
Returns whether this is a software breakpoint. Args: self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance Returns: ``True`` if the breakpoint is a software breakpoint, otherwise ``False``.
[ "Returns", "whether", "this", "is", "a", "software", "breakpoint", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/structs.py#L687-L702
236,163
square/pylink
pylink/library.py
Library.find_library_windows
def find_library_windows(cls): """Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found. """ dll = cls.get_appropriate_windows_sdk_name() + '.dll' root = 'C:\\' for d in os.listdir(root): dir_path = os.path.join(root, d) # Have to account for the different Program Files directories. if d.startswith('Program Files') and os.path.isdir(dir_path): dir_path = os.path.join(dir_path, 'SEGGER') if not os.path.isdir(dir_path): continue # Find all the versioned J-Link directories. ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path)) for jlink_dir in ds: # The DLL always has the same name, so if it is found, just # return it. lib_path = os.path.join(dir_path, jlink_dir, dll) if os.path.isfile(lib_path): yield lib_path
python
def find_library_windows(cls): """Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found. """ dll = cls.get_appropriate_windows_sdk_name() + '.dll' root = 'C:\\' for d in os.listdir(root): dir_path = os.path.join(root, d) # Have to account for the different Program Files directories. if d.startswith('Program Files') and os.path.isdir(dir_path): dir_path = os.path.join(dir_path, 'SEGGER') if not os.path.isdir(dir_path): continue # Find all the versioned J-Link directories. ds = filter(lambda x: x.startswith('JLink'), os.listdir(dir_path)) for jlink_dir in ds: # The DLL always has the same name, so if it is found, just # return it. lib_path = os.path.join(dir_path, jlink_dir, dll) if os.path.isfile(lib_path): yield lib_path
[ "def", "find_library_windows", "(", "cls", ")", ":", "dll", "=", "cls", ".", "get_appropriate_windows_sdk_name", "(", ")", "+", "'.dll'", "root", "=", "'C:\\\\'", "for", "d", "in", "os", ".", "listdir", "(", "root", ")", ":", "dir_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "d", ")", "# Have to account for the different Program Files directories.", "if", "d", ".", "startswith", "(", "'Program Files'", ")", "and", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "dir_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "'SEGGER'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", ":", "continue", "# Find all the versioned J-Link directories.", "ds", "=", "filter", "(", "lambda", "x", ":", "x", ".", "startswith", "(", "'JLink'", ")", ",", "os", ".", "listdir", "(", "dir_path", ")", ")", "for", "jlink_dir", "in", "ds", ":", "# The DLL always has the same name, so if it is found, just", "# return it.", "lib_path", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "jlink_dir", ",", "dll", ")", "if", "os", ".", "path", ".", "isfile", "(", "lib_path", ")", ":", "yield", "lib_path" ]
Loads the SEGGER DLL from the windows installation directory. On Windows, these are found either under: - ``C:\\Program Files\\SEGGER\\JLink`` - ``C:\\Program Files (x86)\\SEGGER\\JLink``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
[ "Loads", "the", "SEGGER", "DLL", "from", "the", "windows", "installation", "directory", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L112-L144
236,164
square/pylink
pylink/library.py
Library.find_library_linux
def find_library_linux(cls): """Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found. """ dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'opt', 'SEGGER') for (directory_name, subdirs, files) in os.walk(root): fnames = [] x86_found = False for f in files: path = os.path.join(directory_name, f) if os.path.isfile(path) and f.startswith(dll): fnames.append(f) if '_x86' in path: x86_found = True for fname in fnames: fpath = os.path.join(directory_name, fname) if util.is_os_64bit(): if '_x86' not in fname: yield fpath elif x86_found: if '_x86' in fname: yield fpath else: yield fpath
python
def find_library_linux(cls): """Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found. """ dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'opt', 'SEGGER') for (directory_name, subdirs, files) in os.walk(root): fnames = [] x86_found = False for f in files: path = os.path.join(directory_name, f) if os.path.isfile(path) and f.startswith(dll): fnames.append(f) if '_x86' in path: x86_found = True for fname in fnames: fpath = os.path.join(directory_name, fname) if util.is_os_64bit(): if '_x86' not in fname: yield fpath elif x86_found: if '_x86' in fname: yield fpath else: yield fpath
[ "def", "find_library_linux", "(", "cls", ")", ":", "dll", "=", "Library", ".", "JLINK_SDK_NAME", "root", "=", "os", ".", "path", ".", "join", "(", "'/'", ",", "'opt'", ",", "'SEGGER'", ")", "for", "(", "directory_name", ",", "subdirs", ",", "files", ")", "in", "os", ".", "walk", "(", "root", ")", ":", "fnames", "=", "[", "]", "x86_found", "=", "False", "for", "f", "in", "files", ":", "path", "=", "os", ".", "path", ".", "join", "(", "directory_name", ",", "f", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", "and", "f", ".", "startswith", "(", "dll", ")", ":", "fnames", ".", "append", "(", "f", ")", "if", "'_x86'", "in", "path", ":", "x86_found", "=", "True", "for", "fname", "in", "fnames", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "directory_name", ",", "fname", ")", "if", "util", ".", "is_os_64bit", "(", ")", ":", "if", "'_x86'", "not", "in", "fname", ":", "yield", "fpath", "elif", "x86_found", ":", "if", "'_x86'", "in", "fname", ":", "yield", "fpath", "else", ":", "yield", "fpath" ]
Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
[ "Loads", "the", "SEGGER", "DLL", "from", "the", "root", "directory", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L147-L182
236,165
square/pylink
pylink/library.py
Library.find_library_darwin
def find_library_darwin(cls): """Loads the SEGGER DLL from the installed applications. This method accounts for the all the different ways in which the DLL may be installed depending on the version of the DLL. Always uses the first directory found. SEGGER's DLL is installed in one of three ways dependent on which which version of the SEGGER tools are installed: ======== ============================================================ Versions Directory ======== ============================================================ < 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER`` < 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib`` >= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm`` ======== ============================================================ Args: cls (Library): the ``Library`` class Returns: The path to the J-Link library files in the order they are found. """ dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'Applications', 'SEGGER') if not os.path.isdir(root): return for d in os.listdir(root): dir_path = os.path.join(root, d) # Navigate through each JLink directory. if os.path.isdir(dir_path) and d.startswith('JLink'): files = list(f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))) # For versions >= 6.0.0 and < 5.0.0, this file will exist, so # we want to use this one instead of the versioned one. if (dll + '.dylib') in files: yield os.path.join(dir_path, dll + '.dylib') # For versions >= 5.0.0 and < 6.0.0, there is no strictly # linked library file, so try and find the versioned one. for f in files: if f.startswith(dll): yield os.path.join(dir_path, f)
python
def find_library_darwin(cls): """Loads the SEGGER DLL from the installed applications. This method accounts for the all the different ways in which the DLL may be installed depending on the version of the DLL. Always uses the first directory found. SEGGER's DLL is installed in one of three ways dependent on which which version of the SEGGER tools are installed: ======== ============================================================ Versions Directory ======== ============================================================ < 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER`` < 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib`` >= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm`` ======== ============================================================ Args: cls (Library): the ``Library`` class Returns: The path to the J-Link library files in the order they are found. """ dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'Applications', 'SEGGER') if not os.path.isdir(root): return for d in os.listdir(root): dir_path = os.path.join(root, d) # Navigate through each JLink directory. if os.path.isdir(dir_path) and d.startswith('JLink'): files = list(f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))) # For versions >= 6.0.0 and < 5.0.0, this file will exist, so # we want to use this one instead of the versioned one. if (dll + '.dylib') in files: yield os.path.join(dir_path, dll + '.dylib') # For versions >= 5.0.0 and < 6.0.0, there is no strictly # linked library file, so try and find the versioned one. for f in files: if f.startswith(dll): yield os.path.join(dir_path, f)
[ "def", "find_library_darwin", "(", "cls", ")", ":", "dll", "=", "Library", ".", "JLINK_SDK_NAME", "root", "=", "os", ".", "path", ".", "join", "(", "'/'", ",", "'Applications'", ",", "'SEGGER'", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "root", ")", ":", "return", "for", "d", "in", "os", ".", "listdir", "(", "root", ")", ":", "dir_path", "=", "os", ".", "path", ".", "join", "(", "root", ",", "d", ")", "# Navigate through each JLink directory.", "if", "os", ".", "path", ".", "isdir", "(", "dir_path", ")", "and", "d", ".", "startswith", "(", "'JLink'", ")", ":", "files", "=", "list", "(", "f", "for", "f", "in", "os", ".", "listdir", "(", "dir_path", ")", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "dir_path", ",", "f", ")", ")", ")", "# For versions >= 6.0.0 and < 5.0.0, this file will exist, so", "# we want to use this one instead of the versioned one.", "if", "(", "dll", "+", "'.dylib'", ")", "in", "files", ":", "yield", "os", ".", "path", ".", "join", "(", "dir_path", ",", "dll", "+", "'.dylib'", ")", "# For versions >= 5.0.0 and < 6.0.0, there is no strictly", "# linked library file, so try and find the versioned one.", "for", "f", "in", "files", ":", "if", "f", ".", "startswith", "(", "dll", ")", ":", "yield", "os", ".", "path", ".", "join", "(", "dir_path", ",", "f", ")" ]
Loads the SEGGER DLL from the installed applications. This method accounts for the all the different ways in which the DLL may be installed depending on the version of the DLL. Always uses the first directory found. SEGGER's DLL is installed in one of three ways dependent on which which version of the SEGGER tools are installed: ======== ============================================================ Versions Directory ======== ============================================================ < 5.0.0 ``/Applications/SEGGER/JLink\\ NUMBER`` < 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib`` >= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm`` ======== ============================================================ Args: cls (Library): the ``Library`` class Returns: The path to the J-Link library files in the order they are found.
[ "Loads", "the", "SEGGER", "DLL", "from", "the", "installed", "applications", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L185-L231
236,166
square/pylink
pylink/library.py
Library.load_default
def load_default(self): """Loads the default J-Link SDK DLL. The default J-Link SDK is determined by first checking if ``ctypes`` can find the DLL, then by searching the platform-specific paths. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was loaded, otherwise ``False``. """ path = ctypes_util.find_library(self._sdk) if path is None: # Couldn't find it the standard way. Fallback to the non-standard # way of finding the J-Link library. These methods are operating # system specific. if self._windows or self._cygwin: path = next(self.find_library_windows(), None) elif sys.platform.startswith('linux'): path = next(self.find_library_linux(), None) elif sys.platform.startswith('darwin'): path = next(self.find_library_darwin(), None) if path is not None: return self.load(path) return False
python
def load_default(self): """Loads the default J-Link SDK DLL. The default J-Link SDK is determined by first checking if ``ctypes`` can find the DLL, then by searching the platform-specific paths. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was loaded, otherwise ``False``. """ path = ctypes_util.find_library(self._sdk) if path is None: # Couldn't find it the standard way. Fallback to the non-standard # way of finding the J-Link library. These methods are operating # system specific. if self._windows or self._cygwin: path = next(self.find_library_windows(), None) elif sys.platform.startswith('linux'): path = next(self.find_library_linux(), None) elif sys.platform.startswith('darwin'): path = next(self.find_library_darwin(), None) if path is not None: return self.load(path) return False
[ "def", "load_default", "(", "self", ")", ":", "path", "=", "ctypes_util", ".", "find_library", "(", "self", ".", "_sdk", ")", "if", "path", "is", "None", ":", "# Couldn't find it the standard way. Fallback to the non-standard", "# way of finding the J-Link library. These methods are operating", "# system specific.", "if", "self", ".", "_windows", "or", "self", ".", "_cygwin", ":", "path", "=", "next", "(", "self", ".", "find_library_windows", "(", ")", ",", "None", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'linux'", ")", ":", "path", "=", "next", "(", "self", ".", "find_library_linux", "(", ")", ",", "None", ")", "elif", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "path", "=", "next", "(", "self", ".", "find_library_darwin", "(", ")", ",", "None", ")", "if", "path", "is", "not", "None", ":", "return", "self", ".", "load", "(", "path", ")", "return", "False" ]
Loads the default J-Link SDK DLL. The default J-Link SDK is determined by first checking if ``ctypes`` can find the DLL, then by searching the platform-specific paths. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was loaded, otherwise ``False``.
[ "Loads", "the", "default", "J", "-", "Link", "SDK", "DLL", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L274-L301
236,167
square/pylink
pylink/library.py
Library.load
def load(self, path=None): """Loads the specified DLL, if any, otherwise re-loads the current DLL. If ``path`` is specified, loads the DLL at the given ``path``, otherwise re-loads the DLL currently specified by this library. Note: This creates a temporary DLL file to use for the instance. This is necessary to work around a limitation of the J-Link DLL in which multiple J-Links cannot be accessed from the same process. Args: self (Library): the ``Library`` instance path (path): path to the DLL to load Returns: ``True`` if library was loaded successfully. Raises: OSError: if there is no J-LINK SDK DLL present at the path. See Also: `J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_. """ self.unload() self._path = path or self._path # Windows requires a proper suffix in order to load the library file, # so it must be set here. if self._windows or self._cygwin: suffix = '.dll' elif sys.platform.startswith('darwin'): suffix = '.dylib' else: suffix = '.so' # Copy the J-Link DLL to a temporary file. This will be cleaned up the # next time we load a DLL using this library or if this library is # cleaned up. tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) with open(tf.name, 'wb') as outputfile: with open(self._path, 'rb') as inputfile: outputfile.write(inputfile.read()) # This is needed to work around a WindowsError where the file is not # being properly cleaned up after exiting the with statement. tf.close() self._temp = tf self._lib = ctypes.cdll.LoadLibrary(tf.name) if self._windows: # The J-Link library uses a mix of __cdecl and __stdcall function # calls. While this is fine on a nix platform or in cygwin, this # causes issues with Windows, where it expects the __stdcall # methods to follow the standard calling convention. As a result, # we have to convert them to windows function calls. self._winlib = ctypes.windll.LoadLibrary(tf.name) for stdcall in self._standard_calls_: if hasattr(self._winlib, stdcall): # Backwards compatibility. Some methods do not exist on # older versions of the J-Link firmware, so ignore them in # these cases. setattr(self._lib, stdcall, getattr(self._winlib, stdcall)) return True
python
def load(self, path=None): """Loads the specified DLL, if any, otherwise re-loads the current DLL. If ``path`` is specified, loads the DLL at the given ``path``, otherwise re-loads the DLL currently specified by this library. Note: This creates a temporary DLL file to use for the instance. This is necessary to work around a limitation of the J-Link DLL in which multiple J-Links cannot be accessed from the same process. Args: self (Library): the ``Library`` instance path (path): path to the DLL to load Returns: ``True`` if library was loaded successfully. Raises: OSError: if there is no J-LINK SDK DLL present at the path. See Also: `J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_. """ self.unload() self._path = path or self._path # Windows requires a proper suffix in order to load the library file, # so it must be set here. if self._windows or self._cygwin: suffix = '.dll' elif sys.platform.startswith('darwin'): suffix = '.dylib' else: suffix = '.so' # Copy the J-Link DLL to a temporary file. This will be cleaned up the # next time we load a DLL using this library or if this library is # cleaned up. tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix) with open(tf.name, 'wb') as outputfile: with open(self._path, 'rb') as inputfile: outputfile.write(inputfile.read()) # This is needed to work around a WindowsError where the file is not # being properly cleaned up after exiting the with statement. tf.close() self._temp = tf self._lib = ctypes.cdll.LoadLibrary(tf.name) if self._windows: # The J-Link library uses a mix of __cdecl and __stdcall function # calls. While this is fine on a nix platform or in cygwin, this # causes issues with Windows, where it expects the __stdcall # methods to follow the standard calling convention. As a result, # we have to convert them to windows function calls. self._winlib = ctypes.windll.LoadLibrary(tf.name) for stdcall in self._standard_calls_: if hasattr(self._winlib, stdcall): # Backwards compatibility. Some methods do not exist on # older versions of the J-Link firmware, so ignore them in # these cases. setattr(self._lib, stdcall, getattr(self._winlib, stdcall)) return True
[ "def", "load", "(", "self", ",", "path", "=", "None", ")", ":", "self", ".", "unload", "(", ")", "self", ".", "_path", "=", "path", "or", "self", ".", "_path", "# Windows requires a proper suffix in order to load the library file,", "# so it must be set here.", "if", "self", ".", "_windows", "or", "self", ".", "_cygwin", ":", "suffix", "=", "'.dll'", "elif", "sys", ".", "platform", ".", "startswith", "(", "'darwin'", ")", ":", "suffix", "=", "'.dylib'", "else", ":", "suffix", "=", "'.so'", "# Copy the J-Link DLL to a temporary file. This will be cleaned up the", "# next time we load a DLL using this library or if this library is", "# cleaned up.", "tf", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ",", "suffix", "=", "suffix", ")", "with", "open", "(", "tf", ".", "name", ",", "'wb'", ")", "as", "outputfile", ":", "with", "open", "(", "self", ".", "_path", ",", "'rb'", ")", "as", "inputfile", ":", "outputfile", ".", "write", "(", "inputfile", ".", "read", "(", ")", ")", "# This is needed to work around a WindowsError where the file is not", "# being properly cleaned up after exiting the with statement.", "tf", ".", "close", "(", ")", "self", ".", "_temp", "=", "tf", "self", ".", "_lib", "=", "ctypes", ".", "cdll", ".", "LoadLibrary", "(", "tf", ".", "name", ")", "if", "self", ".", "_windows", ":", "# The J-Link library uses a mix of __cdecl and __stdcall function", "# calls. While this is fine on a nix platform or in cygwin, this", "# causes issues with Windows, where it expects the __stdcall", "# methods to follow the standard calling convention. As a result,", "# we have to convert them to windows function calls.", "self", ".", "_winlib", "=", "ctypes", ".", "windll", ".", "LoadLibrary", "(", "tf", ".", "name", ")", "for", "stdcall", "in", "self", ".", "_standard_calls_", ":", "if", "hasattr", "(", "self", ".", "_winlib", ",", "stdcall", ")", ":", "# Backwards compatibility. Some methods do not exist on", "# older versions of the J-Link firmware, so ignore them in", "# these cases.", "setattr", "(", "self", ".", "_lib", ",", "stdcall", ",", "getattr", "(", "self", ".", "_winlib", ",", "stdcall", ")", ")", "return", "True" ]
Loads the specified DLL, if any, otherwise re-loads the current DLL. If ``path`` is specified, loads the DLL at the given ``path``, otherwise re-loads the DLL currently specified by this library. Note: This creates a temporary DLL file to use for the instance. This is necessary to work around a limitation of the J-Link DLL in which multiple J-Links cannot be accessed from the same process. Args: self (Library): the ``Library`` instance path (path): path to the DLL to load Returns: ``True`` if library was loaded successfully. Raises: OSError: if there is no J-LINK SDK DLL present at the path. See Also: `J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_.
[ "Loads", "the", "specified", "DLL", "if", "any", "otherwise", "re", "-", "loads", "the", "current", "DLL", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L303-L368
236,168
square/pylink
pylink/library.py
Library.unload
def unload(self): """Unloads the library's DLL if it has been loaded. This additionally cleans up the temporary DLL file that was created when the library was loaded. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was unloaded, otherwise ``False``. """ unloaded = False if self._lib is not None: if self._winlib is not None: # ctypes passes integers as 32-bit C integer types, which will # truncate the value of a 64-bit pointer in 64-bit python, so # we have to change the FreeLibrary method to take a pointer # instead of an integer handle. ctypes.windll.kernel32.FreeLibrary.argtypes = ( ctypes.c_void_p, ) # On Windows we must free both loaded libraries before the # temporary file can be cleaned up. ctypes.windll.kernel32.FreeLibrary(self._lib._handle) ctypes.windll.kernel32.FreeLibrary(self._winlib._handle) self._lib = None self._winlib = None unloaded = True else: # On OSX and Linux, just release the library; it's not safe # to close a dll that ctypes is using. del self._lib self._lib = None unloaded = True if self._temp is not None: os.remove(self._temp.name) self._temp = None return unloaded
python
def unload(self): """Unloads the library's DLL if it has been loaded. This additionally cleans up the temporary DLL file that was created when the library was loaded. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was unloaded, otherwise ``False``. """ unloaded = False if self._lib is not None: if self._winlib is not None: # ctypes passes integers as 32-bit C integer types, which will # truncate the value of a 64-bit pointer in 64-bit python, so # we have to change the FreeLibrary method to take a pointer # instead of an integer handle. ctypes.windll.kernel32.FreeLibrary.argtypes = ( ctypes.c_void_p, ) # On Windows we must free both loaded libraries before the # temporary file can be cleaned up. ctypes.windll.kernel32.FreeLibrary(self._lib._handle) ctypes.windll.kernel32.FreeLibrary(self._winlib._handle) self._lib = None self._winlib = None unloaded = True else: # On OSX and Linux, just release the library; it's not safe # to close a dll that ctypes is using. del self._lib self._lib = None unloaded = True if self._temp is not None: os.remove(self._temp.name) self._temp = None return unloaded
[ "def", "unload", "(", "self", ")", ":", "unloaded", "=", "False", "if", "self", ".", "_lib", "is", "not", "None", ":", "if", "self", ".", "_winlib", "is", "not", "None", ":", "# ctypes passes integers as 32-bit C integer types, which will", "# truncate the value of a 64-bit pointer in 64-bit python, so", "# we have to change the FreeLibrary method to take a pointer", "# instead of an integer handle.", "ctypes", ".", "windll", ".", "kernel32", ".", "FreeLibrary", ".", "argtypes", "=", "(", "ctypes", ".", "c_void_p", ",", ")", "# On Windows we must free both loaded libraries before the", "# temporary file can be cleaned up.", "ctypes", ".", "windll", ".", "kernel32", ".", "FreeLibrary", "(", "self", ".", "_lib", ".", "_handle", ")", "ctypes", ".", "windll", ".", "kernel32", ".", "FreeLibrary", "(", "self", ".", "_winlib", ".", "_handle", ")", "self", ".", "_lib", "=", "None", "self", ".", "_winlib", "=", "None", "unloaded", "=", "True", "else", ":", "# On OSX and Linux, just release the library; it's not safe", "# to close a dll that ctypes is using.", "del", "self", ".", "_lib", "self", ".", "_lib", "=", "None", "unloaded", "=", "True", "if", "self", ".", "_temp", "is", "not", "None", ":", "os", ".", "remove", "(", "self", ".", "_temp", ".", "name", ")", "self", ".", "_temp", "=", "None", "return", "unloaded" ]
Unloads the library's DLL if it has been loaded. This additionally cleans up the temporary DLL file that was created when the library was loaded. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was unloaded, otherwise ``False``.
[ "Unloads", "the", "library", "s", "DLL", "if", "it", "has", "been", "loaded", "." ]
81dda0a191d923a8b2627c52cb778aba24d279d7
https://github.com/square/pylink/blob/81dda0a191d923a8b2627c52cb778aba24d279d7/pylink/library.py#L370-L414
236,169
bndr/pipreqs
pipreqs/pipreqs.py
_open
def _open(filename=None, mode='r'): """Open a file or ``sys.stdout`` depending on the provided filename. Args: filename (str): The path to the file that should be opened. If ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is returned depending on the desired mode. Defaults to ``None``. mode (str): The mode that should be used to open the file. Yields: A file handle. """ if not filename or filename == '-': if not mode or 'r' in mode: file = sys.stdin elif 'w' in mode: file = sys.stdout else: raise ValueError('Invalid mode for file: {}'.format(mode)) else: file = open(filename, mode) try: yield file finally: if file not in (sys.stdin, sys.stdout): file.close()
python
def _open(filename=None, mode='r'): """Open a file or ``sys.stdout`` depending on the provided filename. Args: filename (str): The path to the file that should be opened. If ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is returned depending on the desired mode. Defaults to ``None``. mode (str): The mode that should be used to open the file. Yields: A file handle. """ if not filename or filename == '-': if not mode or 'r' in mode: file = sys.stdin elif 'w' in mode: file = sys.stdout else: raise ValueError('Invalid mode for file: {}'.format(mode)) else: file = open(filename, mode) try: yield file finally: if file not in (sys.stdin, sys.stdout): file.close()
[ "def", "_open", "(", "filename", "=", "None", ",", "mode", "=", "'r'", ")", ":", "if", "not", "filename", "or", "filename", "==", "'-'", ":", "if", "not", "mode", "or", "'r'", "in", "mode", ":", "file", "=", "sys", ".", "stdin", "elif", "'w'", "in", "mode", ":", "file", "=", "sys", ".", "stdout", "else", ":", "raise", "ValueError", "(", "'Invalid mode for file: {}'", ".", "format", "(", "mode", ")", ")", "else", ":", "file", "=", "open", "(", "filename", ",", "mode", ")", "try", ":", "yield", "file", "finally", ":", "if", "file", "not", "in", "(", "sys", ".", "stdin", ",", "sys", ".", "stdout", ")", ":", "file", ".", "close", "(", ")" ]
Open a file or ``sys.stdout`` depending on the provided filename. Args: filename (str): The path to the file that should be opened. If ``None`` or ``'-'``, ``sys.stdout`` or ``sys.stdin`` is returned depending on the desired mode. Defaults to ``None``. mode (str): The mode that should be used to open the file. Yields: A file handle.
[ "Open", "a", "file", "or", "sys", ".", "stdout", "depending", "on", "the", "provided", "filename", "." ]
15208540da03fdacf48fcb0a8b88b26da76b64f3
https://github.com/bndr/pipreqs/blob/15208540da03fdacf48fcb0a8b88b26da76b64f3/pipreqs/pipreqs.py#L66-L93
236,170
bndr/pipreqs
pipreqs/pipreqs.py
get_pkg_names
def get_pkg_names(pkgs): """Get PyPI package names from a list of imports. Args: pkgs (List[str]): List of import names. Returns: List[str]: The corresponding PyPI package names. """ result = set() with open(join("mapping"), "r") as f: data = dict(x.strip().split(":") for x in f) for pkg in pkgs: # Look up the mapped requirement. If a mapping isn't found, # simply use the package name. result.add(data.get(pkg, pkg)) # Return a sorted list for backward compatibility. return sorted(result, key=lambda s: s.lower())
python
def get_pkg_names(pkgs): """Get PyPI package names from a list of imports. Args: pkgs (List[str]): List of import names. Returns: List[str]: The corresponding PyPI package names. """ result = set() with open(join("mapping"), "r") as f: data = dict(x.strip().split(":") for x in f) for pkg in pkgs: # Look up the mapped requirement. If a mapping isn't found, # simply use the package name. result.add(data.get(pkg, pkg)) # Return a sorted list for backward compatibility. return sorted(result, key=lambda s: s.lower())
[ "def", "get_pkg_names", "(", "pkgs", ")", ":", "result", "=", "set", "(", ")", "with", "open", "(", "join", "(", "\"mapping\"", ")", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "dict", "(", "x", ".", "strip", "(", ")", ".", "split", "(", "\":\"", ")", "for", "x", "in", "f", ")", "for", "pkg", "in", "pkgs", ":", "# Look up the mapped requirement. If a mapping isn't found,", "# simply use the package name.", "result", ".", "add", "(", "data", ".", "get", "(", "pkg", ",", "pkg", ")", ")", "# Return a sorted list for backward compatibility.", "return", "sorted", "(", "result", ",", "key", "=", "lambda", "s", ":", "s", ".", "lower", "(", ")", ")" ]
Get PyPI package names from a list of imports. Args: pkgs (List[str]): List of import names. Returns: List[str]: The corresponding PyPI package names.
[ "Get", "PyPI", "package", "names", "from", "a", "list", "of", "imports", "." ]
15208540da03fdacf48fcb0a8b88b26da76b64f3
https://github.com/bndr/pipreqs/blob/15208540da03fdacf48fcb0a8b88b26da76b64f3/pipreqs/pipreqs.py#L252-L270
236,171
spyder-ide/qtawesome
qtawesome/__init__.py
charmap
def charmap(prefixed_name): """ Return the character map used for a given font. Returns ------- return_value: dict The dictionary mapping the icon names to the corresponding unicode character. """ prefix, name = prefixed_name.split('.') return _instance().charmap[prefix][name]
python
def charmap(prefixed_name): """ Return the character map used for a given font. Returns ------- return_value: dict The dictionary mapping the icon names to the corresponding unicode character. """ prefix, name = prefixed_name.split('.') return _instance().charmap[prefix][name]
[ "def", "charmap", "(", "prefixed_name", ")", ":", "prefix", ",", "name", "=", "prefixed_name", ".", "split", "(", "'.'", ")", "return", "_instance", "(", ")", ".", "charmap", "[", "prefix", "]", "[", "name", "]" ]
Return the character map used for a given font. Returns ------- return_value: dict The dictionary mapping the icon names to the corresponding unicode character.
[ "Return", "the", "character", "map", "used", "for", "a", "given", "font", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/__init__.py#L176-L187
236,172
spyder-ide/qtawesome
qtawesome/iconic_font.py
set_global_defaults
def set_global_defaults(**kwargs): """Set global defaults for the options passed to the icon painter.""" valid_options = [ 'active', 'selected', 'disabled', 'on', 'off', 'on_active', 'on_selected', 'on_disabled', 'off_active', 'off_selected', 'off_disabled', 'color', 'color_on', 'color_off', 'color_active', 'color_selected', 'color_disabled', 'color_on_selected', 'color_on_active', 'color_on_disabled', 'color_off_selected', 'color_off_active', 'color_off_disabled', 'animation', 'offset', 'scale_factor', ] for kw in kwargs: if kw in valid_options: _default_options[kw] = kwargs[kw] else: error = "Invalid option '{0}'".format(kw) raise KeyError(error)
python
def set_global_defaults(**kwargs): """Set global defaults for the options passed to the icon painter.""" valid_options = [ 'active', 'selected', 'disabled', 'on', 'off', 'on_active', 'on_selected', 'on_disabled', 'off_active', 'off_selected', 'off_disabled', 'color', 'color_on', 'color_off', 'color_active', 'color_selected', 'color_disabled', 'color_on_selected', 'color_on_active', 'color_on_disabled', 'color_off_selected', 'color_off_active', 'color_off_disabled', 'animation', 'offset', 'scale_factor', ] for kw in kwargs: if kw in valid_options: _default_options[kw] = kwargs[kw] else: error = "Invalid option '{0}'".format(kw) raise KeyError(error)
[ "def", "set_global_defaults", "(", "*", "*", "kwargs", ")", ":", "valid_options", "=", "[", "'active'", ",", "'selected'", ",", "'disabled'", ",", "'on'", ",", "'off'", ",", "'on_active'", ",", "'on_selected'", ",", "'on_disabled'", ",", "'off_active'", ",", "'off_selected'", ",", "'off_disabled'", ",", "'color'", ",", "'color_on'", ",", "'color_off'", ",", "'color_active'", ",", "'color_selected'", ",", "'color_disabled'", ",", "'color_on_selected'", ",", "'color_on_active'", ",", "'color_on_disabled'", ",", "'color_off_selected'", ",", "'color_off_active'", ",", "'color_off_disabled'", ",", "'animation'", ",", "'offset'", ",", "'scale_factor'", ",", "]", "for", "kw", "in", "kwargs", ":", "if", "kw", "in", "valid_options", ":", "_default_options", "[", "kw", "]", "=", "kwargs", "[", "kw", "]", "else", ":", "error", "=", "\"Invalid option '{0}'\"", ".", "format", "(", "kw", ")", "raise", "KeyError", "(", "error", ")" ]
Set global defaults for the options passed to the icon painter.
[ "Set", "global", "defaults", "for", "the", "options", "passed", "to", "the", "icon", "painter", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L53-L72
236,173
spyder-ide/qtawesome
qtawesome/iconic_font.py
CharIconPainter.paint
def paint(self, iconic, painter, rect, mode, state, options): """Main paint method.""" for opt in options: self._paint_icon(iconic, painter, rect, mode, state, opt)
python
def paint(self, iconic, painter, rect, mode, state, options): """Main paint method.""" for opt in options: self._paint_icon(iconic, painter, rect, mode, state, opt)
[ "def", "paint", "(", "self", ",", "iconic", ",", "painter", ",", "rect", ",", "mode", ",", "state", ",", "options", ")", ":", "for", "opt", "in", "options", ":", "self", ".", "_paint_icon", "(", "iconic", ",", "painter", ",", "rect", ",", "mode", ",", "state", ",", "opt", ")" ]
Main paint method.
[ "Main", "paint", "method", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L79-L82
236,174
spyder-ide/qtawesome
qtawesome/iconic_font.py
CharIconPainter._paint_icon
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon.""" painter.save() color = options['color'] char = options['char'] color_options = { QIcon.On: { QIcon.Normal: (options['color_on'], options['on']), QIcon.Disabled: (options['color_on_disabled'], options['on_disabled']), QIcon.Active: (options['color_on_active'], options['on_active']), QIcon.Selected: (options['color_on_selected'], options['on_selected']) }, QIcon.Off: { QIcon.Normal: (options['color_off'], options['off']), QIcon.Disabled: (options['color_off_disabled'], options['off_disabled']), QIcon.Active: (options['color_off_active'], options['off_active']), QIcon.Selected: (options['color_off_selected'], options['off_selected']) } } color, char = color_options[state][mode] painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. draw_size = 0.875 * round(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()
python
def _paint_icon(self, iconic, painter, rect, mode, state, options): """Paint a single icon.""" painter.save() color = options['color'] char = options['char'] color_options = { QIcon.On: { QIcon.Normal: (options['color_on'], options['on']), QIcon.Disabled: (options['color_on_disabled'], options['on_disabled']), QIcon.Active: (options['color_on_active'], options['on_active']), QIcon.Selected: (options['color_on_selected'], options['on_selected']) }, QIcon.Off: { QIcon.Normal: (options['color_off'], options['off']), QIcon.Disabled: (options['color_off_disabled'], options['off_disabled']), QIcon.Active: (options['color_off_active'], options['off_active']), QIcon.Selected: (options['color_off_selected'], options['off_selected']) } } color, char = color_options[state][mode] painter.setPen(QColor(color)) # A 16 pixel-high icon yields a font size of 14, which is pixel perfect # for font-awesome. 16 * 0.875 = 14 # The reason why the glyph size is smaller than the icon size is to # account for font bearing. draw_size = 0.875 * round(rect.height() * options['scale_factor']) prefix = options['prefix'] # Animation setup hook animation = options.get('animation') if animation is not None: animation.setup(self, painter, rect) painter.setFont(iconic.font(prefix, draw_size)) if 'offset' in options: rect = QRect(rect) rect.translate(options['offset'][0] * rect.width(), options['offset'][1] * rect.height()) painter.setOpacity(options.get('opacity', 1.0)) painter.drawText(rect, Qt.AlignCenter | Qt.AlignVCenter, char) painter.restore()
[ "def", "_paint_icon", "(", "self", ",", "iconic", ",", "painter", ",", "rect", ",", "mode", ",", "state", ",", "options", ")", ":", "painter", ".", "save", "(", ")", "color", "=", "options", "[", "'color'", "]", "char", "=", "options", "[", "'char'", "]", "color_options", "=", "{", "QIcon", ".", "On", ":", "{", "QIcon", ".", "Normal", ":", "(", "options", "[", "'color_on'", "]", ",", "options", "[", "'on'", "]", ")", ",", "QIcon", ".", "Disabled", ":", "(", "options", "[", "'color_on_disabled'", "]", ",", "options", "[", "'on_disabled'", "]", ")", ",", "QIcon", ".", "Active", ":", "(", "options", "[", "'color_on_active'", "]", ",", "options", "[", "'on_active'", "]", ")", ",", "QIcon", ".", "Selected", ":", "(", "options", "[", "'color_on_selected'", "]", ",", "options", "[", "'on_selected'", "]", ")", "}", ",", "QIcon", ".", "Off", ":", "{", "QIcon", ".", "Normal", ":", "(", "options", "[", "'color_off'", "]", ",", "options", "[", "'off'", "]", ")", ",", "QIcon", ".", "Disabled", ":", "(", "options", "[", "'color_off_disabled'", "]", ",", "options", "[", "'off_disabled'", "]", ")", ",", "QIcon", ".", "Active", ":", "(", "options", "[", "'color_off_active'", "]", ",", "options", "[", "'off_active'", "]", ")", ",", "QIcon", ".", "Selected", ":", "(", "options", "[", "'color_off_selected'", "]", ",", "options", "[", "'off_selected'", "]", ")", "}", "}", "color", ",", "char", "=", "color_options", "[", "state", "]", "[", "mode", "]", "painter", ".", "setPen", "(", "QColor", "(", "color", ")", ")", "# A 16 pixel-high icon yields a font size of 14, which is pixel perfect", "# for font-awesome. 16 * 0.875 = 14", "# The reason why the glyph size is smaller than the icon size is to", "# account for font bearing.", "draw_size", "=", "0.875", "*", "round", "(", "rect", ".", "height", "(", ")", "*", "options", "[", "'scale_factor'", "]", ")", "prefix", "=", "options", "[", "'prefix'", "]", "# Animation setup hook", "animation", "=", "options", ".", "get", "(", "'animation'", ")", "if", "animation", "is", "not", "None", ":", "animation", ".", "setup", "(", "self", ",", "painter", ",", "rect", ")", "painter", ".", "setFont", "(", "iconic", ".", "font", "(", "prefix", ",", "draw_size", ")", ")", "if", "'offset'", "in", "options", ":", "rect", "=", "QRect", "(", "rect", ")", "rect", ".", "translate", "(", "options", "[", "'offset'", "]", "[", "0", "]", "*", "rect", ".", "width", "(", ")", ",", "options", "[", "'offset'", "]", "[", "1", "]", "*", "rect", ".", "height", "(", ")", ")", "painter", ".", "setOpacity", "(", "options", ".", "get", "(", "'opacity'", ",", "1.0", ")", ")", "painter", ".", "drawText", "(", "rect", ",", "Qt", ".", "AlignCenter", "|", "Qt", ".", "AlignVCenter", ",", "char", ")", "painter", ".", "restore", "(", ")" ]
Paint a single icon.
[ "Paint", "a", "single", "icon", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L84-L138
236,175
spyder-ide/qtawesome
qtawesome/iconic_font.py
IconicFont.icon
def icon(self, *names, **kwargs): """Return a QIcon object corresponding to the provided icon name.""" cache_key = '{}{}'.format(names,kwargs) if cache_key not in self.icon_cache: options_list = kwargs.pop('options', [{}] * len(names)) general_options = kwargs if len(options_list) != len(names): error = '"options" must be a list of size {0}'.format(len(names)) raise Exception(error) if QApplication.instance() is not None: parsed_options = [] for i in range(len(options_list)): specific_options = options_list[i] parsed_options.append(self._parse_options(specific_options, general_options, names[i])) # Process high level API api_options = parsed_options self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options) else: warnings.warn("You need to have a running " "QApplication to use QtAwesome!") return QIcon() return self.icon_cache[cache_key]
python
def icon(self, *names, **kwargs): """Return a QIcon object corresponding to the provided icon name.""" cache_key = '{}{}'.format(names,kwargs) if cache_key not in self.icon_cache: options_list = kwargs.pop('options', [{}] * len(names)) general_options = kwargs if len(options_list) != len(names): error = '"options" must be a list of size {0}'.format(len(names)) raise Exception(error) if QApplication.instance() is not None: parsed_options = [] for i in range(len(options_list)): specific_options = options_list[i] parsed_options.append(self._parse_options(specific_options, general_options, names[i])) # Process high level API api_options = parsed_options self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options) else: warnings.warn("You need to have a running " "QApplication to use QtAwesome!") return QIcon() return self.icon_cache[cache_key]
[ "def", "icon", "(", "self", ",", "*", "names", ",", "*", "*", "kwargs", ")", ":", "cache_key", "=", "'{}{}'", ".", "format", "(", "names", ",", "kwargs", ")", "if", "cache_key", "not", "in", "self", ".", "icon_cache", ":", "options_list", "=", "kwargs", ".", "pop", "(", "'options'", ",", "[", "{", "}", "]", "*", "len", "(", "names", ")", ")", "general_options", "=", "kwargs", "if", "len", "(", "options_list", ")", "!=", "len", "(", "names", ")", ":", "error", "=", "'\"options\" must be a list of size {0}'", ".", "format", "(", "len", "(", "names", ")", ")", "raise", "Exception", "(", "error", ")", "if", "QApplication", ".", "instance", "(", ")", "is", "not", "None", ":", "parsed_options", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "options_list", ")", ")", ":", "specific_options", "=", "options_list", "[", "i", "]", "parsed_options", ".", "append", "(", "self", ".", "_parse_options", "(", "specific_options", ",", "general_options", ",", "names", "[", "i", "]", ")", ")", "# Process high level API", "api_options", "=", "parsed_options", "self", ".", "icon_cache", "[", "cache_key", "]", "=", "self", ".", "_icon_by_painter", "(", "self", ".", "painter", ",", "api_options", ")", "else", ":", "warnings", ".", "warn", "(", "\"You need to have a running \"", "\"QApplication to use QtAwesome!\"", ")", "return", "QIcon", "(", ")", "return", "self", ".", "icon_cache", "[", "cache_key", "]" ]
Return a QIcon object corresponding to the provided icon name.
[ "Return", "a", "QIcon", "object", "corresponding", "to", "the", "provided", "icon", "name", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L252-L279
236,176
spyder-ide/qtawesome
qtawesome/iconic_font.py
IconicFont.font
def font(self, prefix, size): """Return a QFont corresponding to the given prefix and size.""" font = QFont(self.fontname[prefix]) font.setPixelSize(size) if prefix[-1] == 's': # solid style font.setStyleName('Solid') return font
python
def font(self, prefix, size): """Return a QFont corresponding to the given prefix and size.""" font = QFont(self.fontname[prefix]) font.setPixelSize(size) if prefix[-1] == 's': # solid style font.setStyleName('Solid') return font
[ "def", "font", "(", "self", ",", "prefix", ",", "size", ")", ":", "font", "=", "QFont", "(", "self", ".", "fontname", "[", "prefix", "]", ")", "font", ".", "setPixelSize", "(", "size", ")", "if", "prefix", "[", "-", "1", "]", "==", "'s'", ":", "# solid style", "font", ".", "setStyleName", "(", "'Solid'", ")", "return", "font" ]
Return a QFont corresponding to the given prefix and size.
[ "Return", "a", "QFont", "corresponding", "to", "the", "given", "prefix", "and", "size", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L357-L363
236,177
spyder-ide/qtawesome
qtawesome/iconic_font.py
IconicFont._custom_icon
def _custom_icon(self, name, **kwargs): """Return the custom icon corresponding to the given name.""" options = dict(_default_options, **kwargs) if name in self.painters: painter = self.painters[name] return self._icon_by_painter(painter, options) else: return QIcon()
python
def _custom_icon(self, name, **kwargs): """Return the custom icon corresponding to the given name.""" options = dict(_default_options, **kwargs) if name in self.painters: painter = self.painters[name] return self._icon_by_painter(painter, options) else: return QIcon()
[ "def", "_custom_icon", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "options", "=", "dict", "(", "_default_options", ",", "*", "*", "kwargs", ")", "if", "name", "in", "self", ".", "painters", ":", "painter", "=", "self", ".", "painters", "[", "name", "]", "return", "self", ".", "_icon_by_painter", "(", "painter", ",", "options", ")", "else", ":", "return", "QIcon", "(", ")" ]
Return the custom icon corresponding to the given name.
[ "Return", "the", "custom", "icon", "corresponding", "to", "the", "given", "name", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L381-L388
236,178
spyder-ide/qtawesome
qtawesome/iconic_font.py
IconicFont._icon_by_painter
def _icon_by_painter(self, painter, options): """Return the icon corresponding to the given painter.""" engine = CharIconEngine(self, painter, options) return QIcon(engine)
python
def _icon_by_painter(self, painter, options): """Return the icon corresponding to the given painter.""" engine = CharIconEngine(self, painter, options) return QIcon(engine)
[ "def", "_icon_by_painter", "(", "self", ",", "painter", ",", "options", ")", ":", "engine", "=", "CharIconEngine", "(", "self", ",", "painter", ",", "options", ")", "return", "QIcon", "(", "engine", ")" ]
Return the icon corresponding to the given painter.
[ "Return", "the", "icon", "corresponding", "to", "the", "given", "painter", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/qtawesome/iconic_font.py#L390-L393
236,179
spyder-ide/qtawesome
setupbase.py
UpdateFA5Command.finalize_options
def finalize_options(self): """Validate the command options.""" assert bool(self.fa_version), 'FA version is mandatory for this command.' if self.zip_path: assert os.path.exists(self.zip_path), ( 'Local zipfile does not exist: %s' % self.zip_path)
python
def finalize_options(self): """Validate the command options.""" assert bool(self.fa_version), 'FA version is mandatory for this command.' if self.zip_path: assert os.path.exists(self.zip_path), ( 'Local zipfile does not exist: %s' % self.zip_path)
[ "def", "finalize_options", "(", "self", ")", ":", "assert", "bool", "(", "self", ".", "fa_version", ")", ",", "'FA version is mandatory for this command.'", "if", "self", ".", "zip_path", ":", "assert", "os", ".", "path", ".", "exists", "(", "self", ".", "zip_path", ")", ",", "(", "'Local zipfile does not exist: %s'", "%", "self", ".", "zip_path", ")" ]
Validate the command options.
[ "Validate", "the", "command", "options", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L98-L103
236,180
spyder-ide/qtawesome
setupbase.py
UpdateFA5Command.__print
def __print(self, msg): """Shortcut for printing with the distutils logger.""" self.announce(msg, level=distutils.log.INFO)
python
def __print(self, msg): """Shortcut for printing with the distutils logger.""" self.announce(msg, level=distutils.log.INFO)
[ "def", "__print", "(", "self", ",", "msg", ")", ":", "self", ".", "announce", "(", "msg", ",", "level", "=", "distutils", ".", "log", ".", "INFO", ")" ]
Shortcut for printing with the distutils logger.
[ "Shortcut", "for", "printing", "with", "the", "distutils", "logger", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L105-L107
236,181
spyder-ide/qtawesome
setupbase.py
UpdateFA5Command.__zip_file
def __zip_file(self): """Get a file object of the FA zip file.""" if self.zip_path: # If using a local file, just open it: self.__print('Opening local zipfile: %s' % self.zip_path) return open(self.zip_path, 'rb') # Otherwise, download it and make a file object in-memory: url = self.__release_url self.__print('Downloading from URL: %s' % url) response = urlopen(url) return io.BytesIO(response.read())
python
def __zip_file(self): """Get a file object of the FA zip file.""" if self.zip_path: # If using a local file, just open it: self.__print('Opening local zipfile: %s' % self.zip_path) return open(self.zip_path, 'rb') # Otherwise, download it and make a file object in-memory: url = self.__release_url self.__print('Downloading from URL: %s' % url) response = urlopen(url) return io.BytesIO(response.read())
[ "def", "__zip_file", "(", "self", ")", ":", "if", "self", ".", "zip_path", ":", "# If using a local file, just open it:", "self", ".", "__print", "(", "'Opening local zipfile: %s'", "%", "self", ".", "zip_path", ")", "return", "open", "(", "self", ".", "zip_path", ",", "'rb'", ")", "# Otherwise, download it and make a file object in-memory:", "url", "=", "self", ".", "__release_url", "self", ".", "__print", "(", "'Downloading from URL: %s'", "%", "url", ")", "response", "=", "urlopen", "(", "url", ")", "return", "io", ".", "BytesIO", "(", "response", ".", "read", "(", ")", ")" ]
Get a file object of the FA zip file.
[ "Get", "a", "file", "object", "of", "the", "FA", "zip", "file", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L123-L134
236,182
spyder-ide/qtawesome
setupbase.py
UpdateFA5Command.__zipped_files_data
def __zipped_files_data(self): """Get a dict of all files of interest from the FA release zipfile.""" files = {} with zipfile.ZipFile(self.__zip_file) as thezip: for zipinfo in thezip.infolist(): if zipinfo.filename.endswith('metadata/icons.json'): with thezip.open(zipinfo) as compressed_file: files['icons.json'] = compressed_file.read() elif zipinfo.filename.endswith('.ttf'): # For the record, the paths usually look like this: # webfonts/fa-brands-400.ttf # webfonts/fa-regular-400.ttf # webfonts/fa-solid-900.ttf name = os.path.basename(zipinfo.filename) tokens = name.split('-') style = tokens[1] if style in self.FA_STYLES: with thezip.open(zipinfo) as compressed_file: files[style] = compressed_file.read() # Safety checks: assert all(style in files for style in self.FA_STYLES), \ 'Not all FA styles found! Update code is broken.' assert 'icons.json' in files, 'icons.json not found! Update code is broken.' return files
python
def __zipped_files_data(self): """Get a dict of all files of interest from the FA release zipfile.""" files = {} with zipfile.ZipFile(self.__zip_file) as thezip: for zipinfo in thezip.infolist(): if zipinfo.filename.endswith('metadata/icons.json'): with thezip.open(zipinfo) as compressed_file: files['icons.json'] = compressed_file.read() elif zipinfo.filename.endswith('.ttf'): # For the record, the paths usually look like this: # webfonts/fa-brands-400.ttf # webfonts/fa-regular-400.ttf # webfonts/fa-solid-900.ttf name = os.path.basename(zipinfo.filename) tokens = name.split('-') style = tokens[1] if style in self.FA_STYLES: with thezip.open(zipinfo) as compressed_file: files[style] = compressed_file.read() # Safety checks: assert all(style in files for style in self.FA_STYLES), \ 'Not all FA styles found! Update code is broken.' assert 'icons.json' in files, 'icons.json not found! Update code is broken.' return files
[ "def", "__zipped_files_data", "(", "self", ")", ":", "files", "=", "{", "}", "with", "zipfile", ".", "ZipFile", "(", "self", ".", "__zip_file", ")", "as", "thezip", ":", "for", "zipinfo", "in", "thezip", ".", "infolist", "(", ")", ":", "if", "zipinfo", ".", "filename", ".", "endswith", "(", "'metadata/icons.json'", ")", ":", "with", "thezip", ".", "open", "(", "zipinfo", ")", "as", "compressed_file", ":", "files", "[", "'icons.json'", "]", "=", "compressed_file", ".", "read", "(", ")", "elif", "zipinfo", ".", "filename", ".", "endswith", "(", "'.ttf'", ")", ":", "# For the record, the paths usually look like this:", "# webfonts/fa-brands-400.ttf", "# webfonts/fa-regular-400.ttf", "# webfonts/fa-solid-900.ttf", "name", "=", "os", ".", "path", ".", "basename", "(", "zipinfo", ".", "filename", ")", "tokens", "=", "name", ".", "split", "(", "'-'", ")", "style", "=", "tokens", "[", "1", "]", "if", "style", "in", "self", ".", "FA_STYLES", ":", "with", "thezip", ".", "open", "(", "zipinfo", ")", "as", "compressed_file", ":", "files", "[", "style", "]", "=", "compressed_file", ".", "read", "(", ")", "# Safety checks:", "assert", "all", "(", "style", "in", "files", "for", "style", "in", "self", ".", "FA_STYLES", ")", ",", "'Not all FA styles found! Update code is broken.'", "assert", "'icons.json'", "in", "files", ",", "'icons.json not found! Update code is broken.'", "return", "files" ]
Get a dict of all files of interest from the FA release zipfile.
[ "Get", "a", "dict", "of", "all", "files", "of", "interest", "from", "the", "FA", "release", "zipfile", "." ]
c88122aac5b7000eab9d2ae98d27fb3ade88d0f3
https://github.com/spyder-ide/qtawesome/blob/c88122aac5b7000eab9d2ae98d27fb3ade88d0f3/setupbase.py#L137-L162
236,183
trailofbits/protofuzz
protofuzz/pbimport.py
from_string
def from_string(proto_str): ''' Produce a Protobuf module from a string description. Return the module if successfully compiled, otherwise raise a BadProtobuf exception. ''' _, proto_file = tempfile.mkstemp(suffix='.proto') with open(proto_file, 'w+') as proto_f: proto_f.write(proto_str) return from_file(proto_file)
python
def from_string(proto_str): ''' Produce a Protobuf module from a string description. Return the module if successfully compiled, otherwise raise a BadProtobuf exception. ''' _, proto_file = tempfile.mkstemp(suffix='.proto') with open(proto_file, 'w+') as proto_f: proto_f.write(proto_str) return from_file(proto_file)
[ "def", "from_string", "(", "proto_str", ")", ":", "_", ",", "proto_file", "=", "tempfile", ".", "mkstemp", "(", "suffix", "=", "'.proto'", ")", "with", "open", "(", "proto_file", ",", "'w+'", ")", "as", "proto_f", ":", "proto_f", ".", "write", "(", "proto_str", ")", "return", "from_file", "(", "proto_file", ")" ]
Produce a Protobuf module from a string description. Return the module if successfully compiled, otherwise raise a BadProtobuf exception.
[ "Produce", "a", "Protobuf", "module", "from", "a", "string", "description", ".", "Return", "the", "module", "if", "successfully", "compiled", "otherwise", "raise", "a", "BadProtobuf", "exception", "." ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L48-L60
236,184
trailofbits/protofuzz
protofuzz/pbimport.py
_load_module
def _load_module(path): 'Helper to load a Python file at path and return as a module' module_name = os.path.splitext(os.path.basename(path))[0] module = None if sys.version_info.minor < 5: loader = importlib.machinery.SourceFileLoader(module_name, path) module = loader.load_module() else: spec = importlib.util.spec_from_file_location(module_name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
python
def _load_module(path): 'Helper to load a Python file at path and return as a module' module_name = os.path.splitext(os.path.basename(path))[0] module = None if sys.version_info.minor < 5: loader = importlib.machinery.SourceFileLoader(module_name, path) module = loader.load_module() else: spec = importlib.util.spec_from_file_location(module_name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
[ "def", "_load_module", "(", "path", ")", ":", "module_name", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "[", "0", "]", "module", "=", "None", "if", "sys", ".", "version_info", ".", "minor", "<", "5", ":", "loader", "=", "importlib", ".", "machinery", ".", "SourceFileLoader", "(", "module_name", ",", "path", ")", "module", "=", "loader", ".", "load_module", "(", ")", "else", ":", "spec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "module_name", ",", "path", ")", "module", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "spec", ")", "spec", ".", "loader", ".", "exec_module", "(", "module", ")", "return", "module" ]
Helper to load a Python file at path and return as a module
[ "Helper", "to", "load", "a", "Python", "file", "at", "path", "and", "return", "as", "a", "module" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L63-L77
236,185
trailofbits/protofuzz
protofuzz/pbimport.py
_compile_proto
def _compile_proto(full_path, dest): 'Helper to compile protobuf files' proto_path = os.path.dirname(full_path) protoc_args = [find_protoc(), '--python_out={}'.format(dest), '--proto_path={}'.format(proto_path), full_path] proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: outs, errs = proc.communicate(timeout=5) except subprocess.TimeoutExpired: proc.kill() outs, errs = proc.communicate() return False if proc.returncode != 0: msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format( full_path, errs.decode('utf-8'), outs.decode('utf-8')) raise BadProtobuf(msg) return True
python
def _compile_proto(full_path, dest): 'Helper to compile protobuf files' proto_path = os.path.dirname(full_path) protoc_args = [find_protoc(), '--python_out={}'.format(dest), '--proto_path={}'.format(proto_path), full_path] proc = subprocess.Popen(protoc_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: outs, errs = proc.communicate(timeout=5) except subprocess.TimeoutExpired: proc.kill() outs, errs = proc.communicate() return False if proc.returncode != 0: msg = 'Failed compiling "{}": \n\nstderr: {}\nstdout: {}'.format( full_path, errs.decode('utf-8'), outs.decode('utf-8')) raise BadProtobuf(msg) return True
[ "def", "_compile_proto", "(", "full_path", ",", "dest", ")", ":", "proto_path", "=", "os", ".", "path", ".", "dirname", "(", "full_path", ")", "protoc_args", "=", "[", "find_protoc", "(", ")", ",", "'--python_out={}'", ".", "format", "(", "dest", ")", ",", "'--proto_path={}'", ".", "format", "(", "proto_path", ")", ",", "full_path", "]", "proc", "=", "subprocess", ".", "Popen", "(", "protoc_args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "try", ":", "outs", ",", "errs", "=", "proc", ".", "communicate", "(", "timeout", "=", "5", ")", "except", "subprocess", ".", "TimeoutExpired", ":", "proc", ".", "kill", "(", ")", "outs", ",", "errs", "=", "proc", ".", "communicate", "(", ")", "return", "False", "if", "proc", ".", "returncode", "!=", "0", ":", "msg", "=", "'Failed compiling \"{}\": \\n\\nstderr: {}\\nstdout: {}'", ".", "format", "(", "full_path", ",", "errs", ".", "decode", "(", "'utf-8'", ")", ",", "outs", ".", "decode", "(", "'utf-8'", ")", ")", "raise", "BadProtobuf", "(", "msg", ")", "return", "True" ]
Helper to compile protobuf files
[ "Helper", "to", "compile", "protobuf", "files" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L80-L101
236,186
trailofbits/protofuzz
protofuzz/pbimport.py
from_file
def from_file(proto_file): ''' Take a filename |protoc_file|, compile it via the Protobuf compiler, and import the module. Return the module if successfully compiled, otherwise raise either a ProtocNotFound or BadProtobuf exception. ''' if not proto_file.endswith('.proto'): raise BadProtobuf() dest = tempfile.mkdtemp() full_path = os.path.abspath(proto_file) _compile_proto(full_path, dest) filename = os.path.split(full_path)[-1] name = re.search(r'^(.*)\.proto$', filename).group(1) target = os.path.join(dest, name+'_pb2.py') return _load_module(target)
python
def from_file(proto_file): ''' Take a filename |protoc_file|, compile it via the Protobuf compiler, and import the module. Return the module if successfully compiled, otherwise raise either a ProtocNotFound or BadProtobuf exception. ''' if not proto_file.endswith('.proto'): raise BadProtobuf() dest = tempfile.mkdtemp() full_path = os.path.abspath(proto_file) _compile_proto(full_path, dest) filename = os.path.split(full_path)[-1] name = re.search(r'^(.*)\.proto$', filename).group(1) target = os.path.join(dest, name+'_pb2.py') return _load_module(target)
[ "def", "from_file", "(", "proto_file", ")", ":", "if", "not", "proto_file", ".", "endswith", "(", "'.proto'", ")", ":", "raise", "BadProtobuf", "(", ")", "dest", "=", "tempfile", ".", "mkdtemp", "(", ")", "full_path", "=", "os", ".", "path", ".", "abspath", "(", "proto_file", ")", "_compile_proto", "(", "full_path", ",", "dest", ")", "filename", "=", "os", ".", "path", ".", "split", "(", "full_path", ")", "[", "-", "1", "]", "name", "=", "re", ".", "search", "(", "r'^(.*)\\.proto$'", ",", "filename", ")", ".", "group", "(", "1", ")", "target", "=", "os", ".", "path", ".", "join", "(", "dest", ",", "name", "+", "'_pb2.py'", ")", "return", "_load_module", "(", "target", ")" ]
Take a filename |protoc_file|, compile it via the Protobuf compiler, and import the module. Return the module if successfully compiled, otherwise raise either a ProtocNotFound or BadProtobuf exception.
[ "Take", "a", "filename", "|protoc_file|", "compile", "it", "via", "the", "Protobuf", "compiler", "and", "import", "the", "module", ".", "Return", "the", "module", "if", "successfully", "compiled", "otherwise", "raise", "either", "a", "ProtocNotFound", "or", "BadProtobuf", "exception", "." ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L104-L123
236,187
trailofbits/protofuzz
protofuzz/pbimport.py
types_from_module
def types_from_module(pb_module): ''' Return protobuf class types from an imported generated module. ''' types = pb_module.DESCRIPTOR.message_types_by_name return [getattr(pb_module, name) for name in types]
python
def types_from_module(pb_module): ''' Return protobuf class types from an imported generated module. ''' types = pb_module.DESCRIPTOR.message_types_by_name return [getattr(pb_module, name) for name in types]
[ "def", "types_from_module", "(", "pb_module", ")", ":", "types", "=", "pb_module", ".", "DESCRIPTOR", ".", "message_types_by_name", "return", "[", "getattr", "(", "pb_module", ",", "name", ")", "for", "name", "in", "types", "]" ]
Return protobuf class types from an imported generated module.
[ "Return", "protobuf", "class", "types", "from", "an", "imported", "generated", "module", "." ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/pbimport.py#L126-L131
236,188
trailofbits/protofuzz
protofuzz/gen.py
Permuter._resolve_child
def _resolve_child(self, path): 'Return a member generator by a dot-delimited path' obj = self for component in path.split('.'): ptr = obj if not isinstance(ptr, Permuter): raise self.MessageNotFound("Bad element path [wrong type]") # pylint: disable=protected-access found_gen = (_ for _ in ptr._generators if _.name() == component) obj = next(found_gen, None) if not obj: raise self.MessageNotFound("Path '{}' unresolved to member." .format(path)) return ptr, obj
python
def _resolve_child(self, path): 'Return a member generator by a dot-delimited path' obj = self for component in path.split('.'): ptr = obj if not isinstance(ptr, Permuter): raise self.MessageNotFound("Bad element path [wrong type]") # pylint: disable=protected-access found_gen = (_ for _ in ptr._generators if _.name() == component) obj = next(found_gen, None) if not obj: raise self.MessageNotFound("Path '{}' unresolved to member." .format(path)) return ptr, obj
[ "def", "_resolve_child", "(", "self", ",", "path", ")", ":", "obj", "=", "self", "for", "component", "in", "path", ".", "split", "(", "'.'", ")", ":", "ptr", "=", "obj", "if", "not", "isinstance", "(", "ptr", ",", "Permuter", ")", ":", "raise", "self", ".", "MessageNotFound", "(", "\"Bad element path [wrong type]\"", ")", "# pylint: disable=protected-access", "found_gen", "=", "(", "_", "for", "_", "in", "ptr", ".", "_generators", "if", "_", ".", "name", "(", ")", "==", "component", ")", "obj", "=", "next", "(", "found_gen", ",", "None", ")", "if", "not", "obj", ":", "raise", "self", ".", "MessageNotFound", "(", "\"Path '{}' unresolved to member.\"", ".", "format", "(", "path", ")", ")", "return", "ptr", ",", "obj" ]
Return a member generator by a dot-delimited path
[ "Return", "a", "member", "generator", "by", "a", "dot", "-", "delimited", "path" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L111-L128
236,189
trailofbits/protofuzz
protofuzz/gen.py
Permuter.make_dependent
def make_dependent(self, source, target, action): ''' Create a dependency between path 'source' and path 'target' via the callable 'action'. >>> permuter._generators [IterValueGenerator(one), IterValueGenerator(two)] >>> permuter.make_dependent('one', 'two', lambda x: x + 1) Going forward, 'two' will only contain values that are (one+1) ''' if not self._generators: return src_permuter, src = self._resolve_child(source) dest = self._resolve_child(target)[1] # pylint: disable=protected-access container = src_permuter._generators idx = container.index(src) container[idx] = DependentValueGenerator(src.name(), dest, action) self._update_independent_generators()
python
def make_dependent(self, source, target, action): ''' Create a dependency between path 'source' and path 'target' via the callable 'action'. >>> permuter._generators [IterValueGenerator(one), IterValueGenerator(two)] >>> permuter.make_dependent('one', 'two', lambda x: x + 1) Going forward, 'two' will only contain values that are (one+1) ''' if not self._generators: return src_permuter, src = self._resolve_child(source) dest = self._resolve_child(target)[1] # pylint: disable=protected-access container = src_permuter._generators idx = container.index(src) container[idx] = DependentValueGenerator(src.name(), dest, action) self._update_independent_generators()
[ "def", "make_dependent", "(", "self", ",", "source", ",", "target", ",", "action", ")", ":", "if", "not", "self", ".", "_generators", ":", "return", "src_permuter", ",", "src", "=", "self", ".", "_resolve_child", "(", "source", ")", "dest", "=", "self", ".", "_resolve_child", "(", "target", ")", "[", "1", "]", "# pylint: disable=protected-access", "container", "=", "src_permuter", ".", "_generators", "idx", "=", "container", ".", "index", "(", "src", ")", "container", "[", "idx", "]", "=", "DependentValueGenerator", "(", "src", ".", "name", "(", ")", ",", "dest", ",", "action", ")", "self", ".", "_update_independent_generators", "(", ")" ]
Create a dependency between path 'source' and path 'target' via the callable 'action'. >>> permuter._generators [IterValueGenerator(one), IterValueGenerator(two)] >>> permuter.make_dependent('one', 'two', lambda x: x + 1) Going forward, 'two' will only contain values that are (one+1)
[ "Create", "a", "dependency", "between", "path", "source", "and", "path", "target", "via", "the", "callable", "action", "." ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L130-L152
236,190
trailofbits/protofuzz
protofuzz/gen.py
Permuter.get
def get(self): 'Retrieve the most recent value generated' # If you attempt to use a generator comprehension below, it will # consume the StopIteration exception and just return an empty tuple, # instead of stopping iteration normally return tuple([(x.name(), x.get()) for x in self._generators])
python
def get(self): 'Retrieve the most recent value generated' # If you attempt to use a generator comprehension below, it will # consume the StopIteration exception and just return an empty tuple, # instead of stopping iteration normally return tuple([(x.name(), x.get()) for x in self._generators])
[ "def", "get", "(", "self", ")", ":", "# If you attempt to use a generator comprehension below, it will", "# consume the StopIteration exception and just return an empty tuple,", "# instead of stopping iteration normally", "return", "tuple", "(", "[", "(", "x", ".", "name", "(", ")", ",", "x", ".", "get", "(", ")", ")", "for", "x", "in", "self", ".", "_generators", "]", ")" ]
Retrieve the most recent value generated
[ "Retrieve", "the", "most", "recent", "value", "generated" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/gen.py#L154-L159
236,191
trailofbits/protofuzz
protofuzz/values.py
_fuzzdb_integers
def _fuzzdb_integers(limit=0): 'Helper to grab some integers from fuzzdb' path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt') stream = _open_fuzzdb_file(path) for line in _limit_helper(stream, limit): yield int(line.decode('utf-8'), 0)
python
def _fuzzdb_integers(limit=0): 'Helper to grab some integers from fuzzdb' path = os.path.join(BASE_PATH, 'integer-overflow/integer-overflows.txt') stream = _open_fuzzdb_file(path) for line in _limit_helper(stream, limit): yield int(line.decode('utf-8'), 0)
[ "def", "_fuzzdb_integers", "(", "limit", "=", "0", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "BASE_PATH", ",", "'integer-overflow/integer-overflows.txt'", ")", "stream", "=", "_open_fuzzdb_file", "(", "path", ")", "for", "line", "in", "_limit_helper", "(", "stream", ",", "limit", ")", ":", "yield", "int", "(", "line", ".", "decode", "(", "'utf-8'", ")", ",", "0", ")" ]
Helper to grab some integers from fuzzdb
[ "Helper", "to", "grab", "some", "integers", "from", "fuzzdb" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L31-L36
236,192
trailofbits/protofuzz
protofuzz/values.py
_fuzzdb_get_strings
def _fuzzdb_get_strings(max_len=0): 'Helper to get all the strings from fuzzdb' ignored = ['integer-overflow'] for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH): if subdir in ignored: continue path = '{}/{}'.format(BASE_PATH, subdir) listing = pkg_resources.resource_listdir('protofuzz', path) for filename in listing: if not filename.endswith('.txt'): continue path = '{}/{}/{}'.format(BASE_PATH, subdir, filename) source = _open_fuzzdb_file(path) for line in source: string = line.decode('utf-8').strip() if not string or string.startswith('#'): continue if max_len != 0 and len(line) > max_len: continue yield string
python
def _fuzzdb_get_strings(max_len=0): 'Helper to get all the strings from fuzzdb' ignored = ['integer-overflow'] for subdir in pkg_resources.resource_listdir('protofuzz', BASE_PATH): if subdir in ignored: continue path = '{}/{}'.format(BASE_PATH, subdir) listing = pkg_resources.resource_listdir('protofuzz', path) for filename in listing: if not filename.endswith('.txt'): continue path = '{}/{}/{}'.format(BASE_PATH, subdir, filename) source = _open_fuzzdb_file(path) for line in source: string = line.decode('utf-8').strip() if not string or string.startswith('#'): continue if max_len != 0 and len(line) > max_len: continue yield string
[ "def", "_fuzzdb_get_strings", "(", "max_len", "=", "0", ")", ":", "ignored", "=", "[", "'integer-overflow'", "]", "for", "subdir", "in", "pkg_resources", ".", "resource_listdir", "(", "'protofuzz'", ",", "BASE_PATH", ")", ":", "if", "subdir", "in", "ignored", ":", "continue", "path", "=", "'{}/{}'", ".", "format", "(", "BASE_PATH", ",", "subdir", ")", "listing", "=", "pkg_resources", ".", "resource_listdir", "(", "'protofuzz'", ",", "path", ")", "for", "filename", "in", "listing", ":", "if", "not", "filename", ".", "endswith", "(", "'.txt'", ")", ":", "continue", "path", "=", "'{}/{}/{}'", ".", "format", "(", "BASE_PATH", ",", "subdir", ",", "filename", ")", "source", "=", "_open_fuzzdb_file", "(", "path", ")", "for", "line", "in", "source", ":", "string", "=", "line", ".", "decode", "(", "'utf-8'", ")", ".", "strip", "(", ")", "if", "not", "string", "or", "string", ".", "startswith", "(", "'#'", ")", ":", "continue", "if", "max_len", "!=", "0", "and", "len", "(", "line", ")", ">", "max_len", ":", "continue", "yield", "string" ]
Helper to get all the strings from fuzzdb
[ "Helper", "to", "get", "all", "the", "strings", "from", "fuzzdb" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L39-L63
236,193
trailofbits/protofuzz
protofuzz/values.py
get_integers
def get_integers(bitwidth, unsigned, limit=0): ''' Get integers from fuzzdb database bitwidth - The bitwidth that has to contain the integer unsigned - Whether the type is unsigned limit - Limit to |limit| results ''' if unsigned: start, stop = 0, ((1 << bitwidth) - 1) else: start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1) for num in _fuzzdb_integers(limit): if num >= start and num <= stop: yield num
python
def get_integers(bitwidth, unsigned, limit=0): ''' Get integers from fuzzdb database bitwidth - The bitwidth that has to contain the integer unsigned - Whether the type is unsigned limit - Limit to |limit| results ''' if unsigned: start, stop = 0, ((1 << bitwidth) - 1) else: start, stop = (-(1 << bitwidth-1)), (1 << (bitwidth-1)-1) for num in _fuzzdb_integers(limit): if num >= start and num <= stop: yield num
[ "def", "get_integers", "(", "bitwidth", ",", "unsigned", ",", "limit", "=", "0", ")", ":", "if", "unsigned", ":", "start", ",", "stop", "=", "0", ",", "(", "(", "1", "<<", "bitwidth", ")", "-", "1", ")", "else", ":", "start", ",", "stop", "=", "(", "-", "(", "1", "<<", "bitwidth", "-", "1", ")", ")", ",", "(", "1", "<<", "(", "bitwidth", "-", "1", ")", "-", "1", ")", "for", "num", "in", "_fuzzdb_integers", "(", "limit", ")", ":", "if", "num", ">=", "start", "and", "num", "<=", "stop", ":", "yield", "num" ]
Get integers from fuzzdb database bitwidth - The bitwidth that has to contain the integer unsigned - Whether the type is unsigned limit - Limit to |limit| results
[ "Get", "integers", "from", "fuzzdb", "database" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L76-L91
236,194
trailofbits/protofuzz
protofuzz/values.py
get_floats
def get_floats(bitwidth, limit=0): ''' Return a number of interesting floating point values ''' assert bitwidth in (32, 64, 80) values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123] for val in _limit_helper(values, limit): yield val
python
def get_floats(bitwidth, limit=0): ''' Return a number of interesting floating point values ''' assert bitwidth in (32, 64, 80) values = [0.0, -1.0, 1.0, -1231231231231.0123, 123123123123123.123] for val in _limit_helper(values, limit): yield val
[ "def", "get_floats", "(", "bitwidth", ",", "limit", "=", "0", ")", ":", "assert", "bitwidth", "in", "(", "32", ",", "64", ",", "80", ")", "values", "=", "[", "0.0", ",", "-", "1.0", ",", "1.0", ",", "-", "1231231231231.0123", ",", "123123123123123.123", "]", "for", "val", "in", "_limit_helper", "(", "values", ",", "limit", ")", ":", "yield", "val" ]
Return a number of interesting floating point values
[ "Return", "a", "number", "of", "interesting", "floating", "point", "values" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/values.py#L94-L102
236,195
trailofbits/protofuzz
protofuzz/protofuzz.py
_int_generator
def _int_generator(descriptor, bitwidth, unsigned): 'Helper to create a basic integer value generator' vals = list(values.get_integers(bitwidth, unsigned)) return gen.IterValueGenerator(descriptor.name, vals)
python
def _int_generator(descriptor, bitwidth, unsigned): 'Helper to create a basic integer value generator' vals = list(values.get_integers(bitwidth, unsigned)) return gen.IterValueGenerator(descriptor.name, vals)
[ "def", "_int_generator", "(", "descriptor", ",", "bitwidth", ",", "unsigned", ")", ":", "vals", "=", "list", "(", "values", ".", "get_integers", "(", "bitwidth", ",", "unsigned", ")", ")", "return", "gen", ".", "IterValueGenerator", "(", "descriptor", ".", "name", ",", "vals", ")" ]
Helper to create a basic integer value generator
[ "Helper", "to", "create", "a", "basic", "integer", "value", "generator" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L41-L44
236,196
trailofbits/protofuzz
protofuzz/protofuzz.py
_string_generator
def _string_generator(descriptor, max_length=0, limit=0): 'Helper to create a string generator' vals = list(values.get_strings(max_length, limit)) return gen.IterValueGenerator(descriptor.name, vals)
python
def _string_generator(descriptor, max_length=0, limit=0): 'Helper to create a string generator' vals = list(values.get_strings(max_length, limit)) return gen.IterValueGenerator(descriptor.name, vals)
[ "def", "_string_generator", "(", "descriptor", ",", "max_length", "=", "0", ",", "limit", "=", "0", ")", ":", "vals", "=", "list", "(", "values", ".", "get_strings", "(", "max_length", ",", "limit", ")", ")", "return", "gen", ".", "IterValueGenerator", "(", "descriptor", ".", "name", ",", "vals", ")" ]
Helper to create a string generator
[ "Helper", "to", "create", "a", "string", "generator" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L47-L50
236,197
trailofbits/protofuzz
protofuzz/protofuzz.py
_float_generator
def _float_generator(descriptor, bitwidth): 'Helper to create floating point values' return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth))
python
def _float_generator(descriptor, bitwidth): 'Helper to create floating point values' return gen.IterValueGenerator(descriptor.name, values.get_floats(bitwidth))
[ "def", "_float_generator", "(", "descriptor", ",", "bitwidth", ")", ":", "return", "gen", ".", "IterValueGenerator", "(", "descriptor", ".", "name", ",", "values", ".", "get_floats", "(", "bitwidth", ")", ")" ]
Helper to create floating point values
[ "Helper", "to", "create", "floating", "point", "values" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L60-L62
236,198
trailofbits/protofuzz
protofuzz/protofuzz.py
_enum_generator
def _enum_generator(descriptor): 'Helper to create protobuf enums' vals = descriptor.enum_type.values_by_number.keys() return gen.IterValueGenerator(descriptor.name, vals)
python
def _enum_generator(descriptor): 'Helper to create protobuf enums' vals = descriptor.enum_type.values_by_number.keys() return gen.IterValueGenerator(descriptor.name, vals)
[ "def", "_enum_generator", "(", "descriptor", ")", ":", "vals", "=", "descriptor", ".", "enum_type", ".", "values_by_number", ".", "keys", "(", ")", "return", "gen", ".", "IterValueGenerator", "(", "descriptor", ".", "name", ",", "vals", ")" ]
Helper to create protobuf enums
[ "Helper", "to", "create", "protobuf", "enums" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L65-L68
236,199
trailofbits/protofuzz
protofuzz/protofuzz.py
_prototype_to_generator
def _prototype_to_generator(descriptor, cls): 'Helper to map a descriptor to a protofuzz generator' _fd = D.FieldDescriptor generator = None ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32] ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64] ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32, _fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64] if descriptor.type in ints32+ints64: bitwidth = [32, 64][descriptor.type in ints64] unsigned = descriptor.type not in ints_signed generator = _int_generator(descriptor, bitwidth, unsigned) elif descriptor.type == _fd.TYPE_DOUBLE: generator = _float_generator(descriptor, 64) elif descriptor.type == _fd.TYPE_FLOAT: generator = _float_generator(descriptor, 32) elif descriptor.type == _fd.TYPE_STRING: generator = _string_generator(descriptor) elif descriptor.type == _fd.TYPE_BYTES: generator = _bytes_generator(descriptor) elif descriptor.type == _fd.TYPE_BOOL: generator = gen.IterValueGenerator(descriptor.name, [True, False]) elif descriptor.type == _fd.TYPE_ENUM: generator = _enum_generator(descriptor) elif descriptor.type == _fd.TYPE_MESSAGE: generator = descriptor_to_generator(descriptor.message_type, cls) generator.set_name(descriptor.name) else: raise RuntimeError("type {} unsupported".format(descriptor.type)) return generator
python
def _prototype_to_generator(descriptor, cls): 'Helper to map a descriptor to a protofuzz generator' _fd = D.FieldDescriptor generator = None ints32 = [_fd.TYPE_INT32, _fd.TYPE_UINT32, _fd.TYPE_FIXED32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32] ints64 = [_fd.TYPE_INT64, _fd.TYPE_UINT64, _fd.TYPE_FIXED64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64] ints_signed = [_fd.TYPE_INT32, _fd.TYPE_SFIXED32, _fd.TYPE_SINT32, _fd.TYPE_INT64, _fd.TYPE_SFIXED64, _fd.TYPE_SINT64] if descriptor.type in ints32+ints64: bitwidth = [32, 64][descriptor.type in ints64] unsigned = descriptor.type not in ints_signed generator = _int_generator(descriptor, bitwidth, unsigned) elif descriptor.type == _fd.TYPE_DOUBLE: generator = _float_generator(descriptor, 64) elif descriptor.type == _fd.TYPE_FLOAT: generator = _float_generator(descriptor, 32) elif descriptor.type == _fd.TYPE_STRING: generator = _string_generator(descriptor) elif descriptor.type == _fd.TYPE_BYTES: generator = _bytes_generator(descriptor) elif descriptor.type == _fd.TYPE_BOOL: generator = gen.IterValueGenerator(descriptor.name, [True, False]) elif descriptor.type == _fd.TYPE_ENUM: generator = _enum_generator(descriptor) elif descriptor.type == _fd.TYPE_MESSAGE: generator = descriptor_to_generator(descriptor.message_type, cls) generator.set_name(descriptor.name) else: raise RuntimeError("type {} unsupported".format(descriptor.type)) return generator
[ "def", "_prototype_to_generator", "(", "descriptor", ",", "cls", ")", ":", "_fd", "=", "D", ".", "FieldDescriptor", "generator", "=", "None", "ints32", "=", "[", "_fd", ".", "TYPE_INT32", ",", "_fd", ".", "TYPE_UINT32", ",", "_fd", ".", "TYPE_FIXED32", ",", "_fd", ".", "TYPE_SFIXED32", ",", "_fd", ".", "TYPE_SINT32", "]", "ints64", "=", "[", "_fd", ".", "TYPE_INT64", ",", "_fd", ".", "TYPE_UINT64", ",", "_fd", ".", "TYPE_FIXED64", ",", "_fd", ".", "TYPE_SFIXED64", ",", "_fd", ".", "TYPE_SINT64", "]", "ints_signed", "=", "[", "_fd", ".", "TYPE_INT32", ",", "_fd", ".", "TYPE_SFIXED32", ",", "_fd", ".", "TYPE_SINT32", ",", "_fd", ".", "TYPE_INT64", ",", "_fd", ".", "TYPE_SFIXED64", ",", "_fd", ".", "TYPE_SINT64", "]", "if", "descriptor", ".", "type", "in", "ints32", "+", "ints64", ":", "bitwidth", "=", "[", "32", ",", "64", "]", "[", "descriptor", ".", "type", "in", "ints64", "]", "unsigned", "=", "descriptor", ".", "type", "not", "in", "ints_signed", "generator", "=", "_int_generator", "(", "descriptor", ",", "bitwidth", ",", "unsigned", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_DOUBLE", ":", "generator", "=", "_float_generator", "(", "descriptor", ",", "64", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_FLOAT", ":", "generator", "=", "_float_generator", "(", "descriptor", ",", "32", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_STRING", ":", "generator", "=", "_string_generator", "(", "descriptor", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_BYTES", ":", "generator", "=", "_bytes_generator", "(", "descriptor", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_BOOL", ":", "generator", "=", "gen", ".", "IterValueGenerator", "(", "descriptor", ".", "name", ",", "[", "True", ",", "False", "]", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_ENUM", ":", "generator", "=", "_enum_generator", "(", "descriptor", ")", "elif", "descriptor", ".", "type", "==", "_fd", ".", "TYPE_MESSAGE", ":", "generator", "=", "descriptor_to_generator", "(", "descriptor", ".", "message_type", ",", "cls", ")", "generator", ".", "set_name", "(", "descriptor", ".", "name", ")", "else", ":", "raise", "RuntimeError", "(", "\"type {} unsupported\"", ".", "format", "(", "descriptor", ".", "type", ")", ")", "return", "generator" ]
Helper to map a descriptor to a protofuzz generator
[ "Helper", "to", "map", "a", "descriptor", "to", "a", "protofuzz", "generator" ]
589492d34de9a0da6cc5554094e2588b893b2fd8
https://github.com/trailofbits/protofuzz/blob/589492d34de9a0da6cc5554094e2588b893b2fd8/protofuzz/protofuzz.py#L71-L105