idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
230,000
def memory_zones ( self ) : count = self . num_memory_zones ( ) if count == 0 : return list ( ) buf = ( structs . JLinkMemoryZone * count ) ( ) res = self . _dll . JLINK_GetMemZones ( buf , count ) if res < 0 : raise errors . JLinkException ( res ) return list ( buf )
Gets all memory zones supported by the current target .
84
11
230,001
def memory_read ( self , addr , num_units , zone = None , nbits = None ) : buf_size = num_units buf = None access = 0 if nbits is None : buf = ( ctypes . c_uint8 * buf_size ) ( ) access = 0 elif nbits == 8 : buf = ( ctypes . c_uint8 * buf_size ) ( ) access = 1 elif nbits == 16 : buf = ( ctypes . c_uint16 * buf_size ) ( ) access = 2 buf_size = buf_size * access elif nbits == 32 : buf = ( ctypes . c_uint32 * buf_size ) ( ) access = 4 buf_size = buf_size * access else : raise ValueError ( 'Given bit size is invalid: %s' % nbits ) args = [ addr , buf_size , buf , access ] method = self . _dll . JLINKARM_ReadMemEx if zone is not None : method = self . _dll . JLINKARM_ReadMemZonedEx args . append ( zone . encode ( ) ) units_read = method ( * args ) if units_read < 0 : raise errors . JLinkReadException ( units_read ) return buf [ : units_read ]
Reads memory from a target system or specific memory zone .
278
12
230,002
def memory_read8 ( self , addr , num_bytes , zone = None ) : return self . memory_read ( addr , num_bytes , zone = zone , nbits = 8 )
Reads memory from the target system in units of bytes .
41
12
230,003
def memory_read16 ( self , addr , num_halfwords , zone = None ) : return self . memory_read ( addr , num_halfwords , zone = zone , nbits = 16 )
Reads memory from the target system in units of 16 - bits .
43
14
230,004
def memory_read32 ( self , addr , num_words , zone = None ) : return self . memory_read ( addr , num_words , zone = zone , nbits = 32 )
Reads memory from the target system in units of 32 - bits .
41
14
230,005
def memory_read64 ( self , addr , num_long_words ) : buf_size = num_long_words buf = ( ctypes . c_ulonglong * buf_size ) ( ) units_read = self . _dll . JLINKARM_ReadMemU64 ( addr , buf_size , buf , 0 ) if units_read < 0 : raise errors . JLinkException ( units_read ) return buf [ : units_read ]
Reads memory from the target system in units of 64 - bits .
99
14
230,006
def memory_write ( self , addr , data , zone = None , nbits = None ) : buf_size = len ( data ) buf = None access = 0 if nbits is None : # Pack the given data into an array of 8-bit unsigned integers in # order to write it successfully packed_data = map ( lambda d : reversed ( binpacker . pack ( d ) ) , data ) packed_data = list ( itertools . chain ( * packed_data ) ) buf_size = len ( packed_data ) buf = ( ctypes . c_uint8 * buf_size ) ( * packed_data ) # Allow the access width to be chosen for us. access = 0 elif nbits == 8 : buf = ( ctypes . c_uint8 * buf_size ) ( * data ) access = 1 elif nbits == 16 : buf = ( ctypes . c_uint16 * buf_size ) ( * data ) access = 2 buf_size = buf_size * access elif nbits == 32 : buf = ( ctypes . c_uint32 * buf_size ) ( * data ) access = 4 buf_size = buf_size * access else : raise ValueError ( 'Given bit size is invalid: %s' % nbits ) args = [ addr , buf_size , buf , access ] method = self . _dll . JLINKARM_WriteMemEx if zone is not None : method = self . _dll . JLINKARM_WriteMemZonedEx args . append ( zone . encode ( ) ) units_written = method ( * args ) if units_written < 0 : raise errors . JLinkWriteException ( units_written ) return units_written
Writes memory to a target system or specific memory zone .
366
12
230,007
def memory_write8 ( self , addr , data , zone = None ) : return self . memory_write ( addr , data , zone , 8 )
Writes bytes to memory of a target system .
32
10
230,008
def memory_write16 ( self , addr , data , zone = None ) : return self . memory_write ( addr , data , zone , 16 )
Writes half - words to memory of a target system .
32
12
230,009
def memory_write32 ( self , addr , data , zone = None ) : return self . memory_write ( addr , data , zone , 32 )
Writes words to memory of a target system .
32
10
230,010
def memory_write64 ( self , addr , data , zone = None ) : words = [ ] bitmask = 0xFFFFFFFF for long_word in data : words . append ( long_word & bitmask ) # Last 32-bits words . append ( ( long_word >> 32 ) & bitmask ) # First 32-bits return self . memory_write32 ( addr , words , zone = zone )
Writes long words to memory of a target system .
87
11
230,011
def register_read_multiple ( self , register_indices ) : num_regs = len ( register_indices ) buf = ( ctypes . c_uint32 * num_regs ) ( * register_indices ) data = ( ctypes . c_uint32 * num_regs ) ( 0 ) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = ( ctypes . c_uint8 * num_regs ) ( 0 ) res = self . _dll . JLINKARM_ReadRegs ( buf , data , statuses , num_regs ) if res < 0 : raise errors . JLinkException ( res ) return list ( data )
Retrieves the values from the registers specified .
169
10
230,012
def register_write ( self , reg_index , value ) : res = self . _dll . JLINKARM_WriteReg ( reg_index , value ) if res != 0 : raise errors . JLinkException ( 'Error writing to register %d' % reg_index ) return value
Writes into an ARM register .
62
7
230,013
def register_write_multiple ( self , register_indices , values ) : if len ( register_indices ) != len ( values ) : raise ValueError ( 'Must be an equal number of registers and values' ) num_regs = len ( register_indices ) buf = ( ctypes . c_uint32 * num_regs ) ( * register_indices ) data = ( ctypes . c_uint32 * num_regs ) ( * values ) # TODO: For some reason, these statuses are wonky, not sure why, might # be bad documentation, but they cannot be trusted at all. statuses = ( ctypes . c_uint8 * num_regs ) ( 0 ) res = self . _dll . JLINKARM_WriteRegs ( buf , data , statuses , num_regs ) if res != 0 : raise errors . JLinkException ( res ) return None
Writes to multiple CPU registers .
199
7
230,014
def ice_register_write ( self , register_index , value , delay = False ) : self . _dll . JLINKARM_WriteICEReg ( register_index , int ( value ) , int ( delay ) ) return None
Writes a value to an ARM ICE register .
51
10
230,015
def etm_supported ( self ) : res = self . _dll . JLINKARM_ETM_IsPresent ( ) if ( res == 1 ) : return True # JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This # fallback checks if ETM is present by checking the Cortex ROM table # for debugging information for ETM. info = ctypes . c_uint32 ( 0 ) index = enums . JLinkROMTable . ETM res = self . _dll . JLINKARM_GetDebugInfo ( index , ctypes . byref ( info ) ) if ( res == 1 ) : return False return True
Returns if the CPU core supports ETM .
144
9
230,016
def etm_register_write ( self , register_index , value , delay = False ) : self . _dll . JLINKARM_ETM_WriteReg ( int ( register_index ) , int ( value ) , int ( delay ) ) return None
Writes a value to an ETM register .
56
10
230,017
def set_vector_catch ( self , flags ) : res = self . _dll . JLINKARM_WriteVectorCatch ( flags ) if res < 0 : raise errors . JLinkException ( res ) return None
Sets vector catch bits of the processor .
47
9
230,018
def step ( self , thumb = False ) : method = self . _dll . JLINKARM_Step if thumb : method = self . _dll . JLINKARM_StepComposite res = method ( ) if res != 0 : raise errors . JLinkException ( "Failed to step over instruction." ) return None
Executes a single step .
70
6
230,019
def num_available_breakpoints ( self , arm = False , thumb = False , ram = False , flash = False , hw = False ) : flags = [ enums . JLinkBreakpoint . ARM , enums . JLinkBreakpoint . THUMB , enums . JLinkBreakpoint . SW_RAM , enums . JLinkBreakpoint . SW_FLASH , enums . JLinkBreakpoint . HW ] set_flags = [ arm , thumb , ram , flash , hw ] if not any ( set_flags ) : flags = enums . JLinkBreakpoint . ANY else : flags = list ( f for i , f in enumerate ( flags ) if set_flags [ i ] ) flags = functools . reduce ( operator . __or__ , flags , 0 ) return self . _dll . JLINKARM_GetNumBPUnits ( flags )
Returns the number of available breakpoints of the specified type .
190
12
230,020
def breakpoint_info ( self , handle = 0 , index = - 1 ) : if index < 0 and handle == 0 : raise ValueError ( 'Handle must be provided if index is not set.' ) bp = structs . JLinkBreakpointInfo ( ) bp . Handle = int ( handle ) res = self . _dll . JLINKARM_GetBPInfoEx ( index , ctypes . byref ( bp ) ) if res < 0 : raise errors . JLinkException ( 'Failed to get breakpoint info.' ) return bp
Returns the information about a set breakpoint .
119
9
230,021
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 .
111
10
230,022
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 .
164
11
230,023
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 .
188
8
230,024
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 .
584
10
230,025
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 .
134
10
230,026
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 .
111
9
230,027
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 .
133
13
230,028
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 .
205
14
230,029
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 .
153
15
230,030
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 .
89
11
230,031
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 .
77
7
230,032
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 .
87
8
230,033
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 .
65
6
230,034
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 .
65
6
230,035
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 .
68
6
230,036
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 .
97
10
230,037
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 .
96
9
230,038
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 .
99
14
230,039
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 .
99
14
230,040
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 .
92
11
230,041
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 .
90
12
230,042
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 .
95
13
230,043
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 .
108
10
230,044
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 .
123
11
230,045
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 .
119
7
230,046
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 .
56
7
230,047
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 .
116
10
230,048
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 .
51
9
230,049
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 .
105
9
230,050
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 .
83
11
230,051
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 .
64
13
230,052
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 .
95
17
230,053
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 .
96
19
230,054
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 .
104
21
230,055
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 .
142
9
230,056
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 .
107
10
230,057
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 .
96
9
230,058
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 .
103
9
230,059
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 .
76
8
230,060
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 .
277
12
230,061
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 .
115
5
230,062
def join ( self , * args , * * kwargs ) : super ( ThreadReturn , self ) . join ( * args , * * kwargs ) return self . _return
Joins the thread .
39
5
230,063
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 .
258
15
230,064
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 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
Asynchronous function decorator . Interprets the function as being asynchronous so returns a function that will handle calling the Function asynchronously .
425
28
230,065
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 .
322
12
230,066
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 .
281
6
230,067
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 .
135
8
230,068
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 .
143
14
230,069
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 .
200
8
230,070
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 .
41
11
230,071
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 .
99
11
230,072
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 .
61
9
230,073
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 .
68
6
230,074
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 .
168
6
230,075
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 .
94
8
230,076
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 .
262
6
230,077
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 .
154
8
230,078
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 .
505
6
230,079
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 .
116
8
230,080
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 .
297
6
230,081
def name ( self ) : return ctypes . cast ( self . sName , ctypes . c_char_p ) . value . decode ( )
Returns the name of the device .
32
7
230,082
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 .
40
10
230,083
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 .
66
9
230,084
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 .
246
14
230,085
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 .
212
13
230,086
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 .
288
13
230,087
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 .
173
11
230,088
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 .
431
17
230,089
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 .
256
13
230,090
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 .
111
14
230,091
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 .
124
11
230,092
def charmap ( prefixed_name ) : prefix , name = prefixed_name . split ( '.' ) return _instance ( ) . charmap [ prefix ] [ name ]
Return the character map used for a given font .
38
10
230,093
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 .
230
12
230,094
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 .
43
4
230,095
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 .
524
6
230,096
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 .
265
12
230,097
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 .
57
12
230,098
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 .
71
10
230,099
def _icon_by_painter ( self , painter , options ) : engine = CharIconEngine ( self , painter , options ) return QIcon ( engine )
Return the icon corresponding to the given painter .
34
9