idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
229,900
def load_all ( self , keys = None , replace_existing_values = True ) : if keys : key_data_list = list ( map ( self . _to_data , keys ) ) return self . _load_all_internal ( key_data_list , replace_existing_values ) else : return self . _encode_invoke ( map_load_all_codec , replace_existing_values = replace_existing_values )
Loads all keys from the store at server side or loads the given keys if provided .
97
18
229,901
def put_if_absent ( self , key , value , ttl = - 1 ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _put_if_absent_internal ( key_data , value_data , ttl )
Associates the specified key with the given value if it is not already associated . If ttl is provided entry will expire and get evicted after the ttl .
103
34
229,902
def remove_if_same ( self , key , value ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _remove_if_same_internal_ ( key_data , value_data )
Removes the entry for a key only if it is currently mapped to a given value .
93
18
229,903
def replace ( self , key , value ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _replace_internal ( key_data , value_data )
Replaces the entry for a key only if it is currently mapped to some value .
84
17
229,904
def replace_if_same ( self , key , old_value , new_value ) : check_not_none ( key , "key can't be None" ) check_not_none ( old_value , "old_value can't be None" ) check_not_none ( new_value , "new_value can't be None" ) key_data = self . _to_data ( key ) old_value_data = self . _to_data ( old_value ) new_value_data = self . _to_data ( new_value ) return self . _replace_if_same_internal ( key_data , old_value_data , new_value_data )
Replaces the entry for a key only if it is currently mapped to a given value .
151
18
229,905
def set ( self , key , value , ttl = - 1 ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _set_internal ( key_data , value_data , ttl )
Puts an entry into this map . Similar to the put operation except that set doesn t return the old value which is more efficient . If ttl is provided entry will expire and get evicted after the ttl .
93
44
229,906
def try_put ( self , key , value , timeout = 0 ) : check_not_none ( key , "key can't be None" ) check_not_none ( value , "value can't be None" ) key_data = self . _to_data ( key ) value_data = self . _to_data ( value ) return self . _try_put_internal ( key_data , value_data , timeout )
Tries to put the given key and value into this map and returns immediately if timeout is not provided . If timeout is provided operation waits until it is completed or timeout is reached .
94
36
229,907
def try_remove ( self , key , timeout = 0 ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _try_remove_internal ( key_data , timeout )
Tries to remove the given key from this map and returns immediately if timeout is not provided . If timeout is provided operation waits until it is completed or timeout is reached .
59
34
229,908
def unlock ( self , key ) : check_not_none ( key , "key can't be None" ) key_data = self . _to_data ( key ) return self . _encode_invoke_on_key ( map_unlock_codec , key_data , key = key_data , thread_id = thread_id ( ) , reference_id = self . reference_id_generator . get_and_increment ( ) )
Releases the lock for the specified key . It never blocks and returns immediately . If the current thread is the holder of this lock then the hold count is decremented . If the hold count is zero then the lock is released .
100
46
229,909
def values ( self , predicate = None ) : if predicate : predicate_data = self . _to_data ( predicate ) return self . _encode_invoke ( map_values_with_predicate_codec , predicate = predicate_data ) else : return self . _encode_invoke ( map_values_codec )
Returns a list clone of the values contained in this map or values of the entries which are filtered with the predicate if provided .
71
25
229,910
def new_transaction ( self , timeout , durability , transaction_type ) : connection = self . _connect ( ) return Transaction ( self . _client , connection , timeout , durability , transaction_type )
Creates a Transaction object with given timeout durability and transaction type .
43
13
229,911
def begin ( self ) : if hasattr ( self . _locals , 'transaction_exists' ) and self . _locals . transaction_exists : raise TransactionError ( "Nested transactions are not allowed." ) if self . state != _STATE_NOT_STARTED : raise TransactionError ( "Transaction has already been started." ) self . _locals . transaction_exists = True self . start_time = time . time ( ) self . thread_id = thread_id ( ) try : request = transaction_create_codec . encode_request ( timeout = int ( self . timeout * 1000 ) , durability = self . durability , transaction_type = self . transaction_type , thread_id = self . thread_id ) response = self . client . invoker . invoke_on_connection ( request , self . connection ) . result ( ) self . id = transaction_create_codec . decode_response ( response ) [ "response" ] self . state = _STATE_ACTIVE except : self . _locals . transaction_exists = False raise
Begins this transaction .
232
5
229,912
def commit ( self ) : self . _check_thread ( ) if self . state != _STATE_ACTIVE : raise TransactionError ( "Transaction is not active." ) try : self . _check_timeout ( ) request = transaction_commit_codec . encode_request ( self . id , self . thread_id ) self . client . invoker . invoke_on_connection ( request , self . connection ) . result ( ) self . state = _STATE_COMMITTED except : self . state = _STATE_PARTIAL_COMMIT raise finally : self . _locals . transaction_exists = False
Commits this transaction .
132
5
229,913
def rollback ( self ) : self . _check_thread ( ) if self . state not in ( _STATE_ACTIVE , _STATE_PARTIAL_COMMIT ) : raise TransactionError ( "Transaction is not active." ) try : if self . state != _STATE_PARTIAL_COMMIT : request = transaction_rollback_codec . encode_request ( self . id , self . thread_id ) self . client . invoker . invoke_on_connection ( request , self . connection ) . result ( ) self . state = _STATE_ROLLED_BACK finally : self . _locals . transaction_exists = False
Rollback of this current transaction .
138
7
229,914
def load_addresses ( self ) : try : return list ( self . cloud_discovery . discover_nodes ( ) . keys ( ) ) except Exception as ex : self . logger . warning ( "Failed to load addresses from Hazelcast.cloud: {}" . format ( ex . args [ 0 ] ) , extra = self . _logger_extras ) return [ ]
Loads member addresses from Hazelcast . cloud endpoint .
82
11
229,915
def translate ( self , address ) : if address is None : return None public_address = self . _private_to_public . get ( address ) if public_address : return public_address self . refresh ( ) return self . _private_to_public . get ( address )
Translates the given address to another address specific to network or service .
60
15
229,916
def refresh ( self ) : try : self . _private_to_public = self . cloud_discovery . discover_nodes ( ) except Exception as ex : self . logger . warning ( "Failed to load addresses from Hazelcast.cloud: {}" . format ( ex . args [ 0 ] ) , extra = self . _logger_extras )
Refreshes the internal lookup table if necessary .
77
10
229,917
def get_host_and_url ( properties , cloud_token ) : host = properties . get ( HazelcastCloudDiscovery . CLOUD_URL_BASE_PROPERTY . name , HazelcastCloudDiscovery . CLOUD_URL_BASE_PROPERTY . default_value ) host = host . replace ( "https://" , "" ) host = host . replace ( "http://" , "" ) return host , HazelcastCloudDiscovery . _CLOUD_URL_PATH + cloud_token
Helper method to get host and url that can be used in HTTPSConnection .
113
15
229,918
def try_set_count ( self , count ) : check_not_negative ( count , "count can't be negative" ) return self . _encode_invoke ( count_down_latch_try_set_count_codec , count = count )
Sets the count to the given value if the current count is zero . If count is not zero this method does nothing and returns false .
57
28
229,919
def destroy ( self ) : self . _on_destroy ( ) return self . _client . proxy . destroy_proxy ( self . service_name , self . name )
Destroys this proxy .
36
6
229,920
def add_listener ( self , member_added = None , member_removed = None , fire_for_existing = False ) : registration_id = str ( uuid . uuid4 ( ) ) self . listeners [ registration_id ] = ( member_added , member_removed ) if fire_for_existing : for member in self . get_member_list ( ) : member_added ( member ) return registration_id
Adds a membership listener to listen for membership updates it will be notified when a member is added to cluster or removed from cluster . There is no check for duplicate registrations so if you register the listener twice it will get events twice .
94
45
229,921
def remove_listener ( self , registration_id ) : try : self . listeners . pop ( registration_id ) return True except KeyError : return False
Removes the specified membership listener .
33
7
229,922
def get_member_by_uuid ( self , member_uuid ) : for member in self . get_member_list ( ) : if member . uuid == member_uuid : return member
Returns the member with specified member uuid .
44
9
229,923
def get_members ( self , selector ) : members = [ ] for member in self . get_member_list ( ) : if selector . select ( member ) : members . append ( member ) return members
Returns the members that satisfy the given selector .
43
9
229,924
def is_after ( self , other ) : any_timestamp_greater = False for replica_id , other_timestamp in other . entry_set ( ) : local_timestamp = self . _replica_timestamps . get ( replica_id ) if local_timestamp is None or local_timestamp < other_timestamp : return False elif local_timestamp > other_timestamp : any_timestamp_greater = True # there is at least one local timestamp greater or local vector clock has additional timestamps return any_timestamp_greater or other . size ( ) < self . size ( )
Returns true if this vector clock is causally strictly after the provided vector clock . This means that it the provided clock is neither equal to greater than or concurrent to this vector clock .
137
36
229,925
def contains ( self , item ) : check_not_none ( item , "Value can't be None" ) item_data = self . _to_data ( item ) return self . _encode_invoke ( set_contains_codec , value = item_data )
Determines whether this set contains the specified item or not .
60
13
229,926
def contains_all ( self , items ) : check_not_none ( items , "Value can't be None" ) data_items = [ ] for item in items : check_not_none ( item , "Value can't be None" ) data_items . append ( self . _to_data ( item ) ) return self . _encode_invoke ( set_contains_all_codec , items = data_items )
Determines whether this set contains all of the items in the specified collection or not .
94
18
229,927
def alter ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_long_alter_codec , function = self . _to_data ( function ) )
Alters the currently stored value by applying a function on it .
54
13
229,928
def alter_and_get ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_long_alter_and_get_codec , function = self . _to_data ( function ) )
Alters the currently stored value by applying a function on it and gets the result .
62
17
229,929
def get_and_alter ( self , function ) : check_not_none ( function , "function can't be None" ) return self . _encode_invoke ( atomic_long_get_and_alter_codec , function = self . _to_data ( function ) )
Alters the currently stored value by applying a function on it on and gets the old value .
62
19
229,930
def main ( jlink_serial , device ) : buf = StringIO . StringIO ( ) jlink = pylink . JLink ( log = buf . write , detailed_log = buf . write ) jlink . open ( serial_no = jlink_serial ) # Use Serial Wire Debug as the target interface. jlink . set_tif ( pylink . enums . JLinkInterfaces . SWD ) jlink . connect ( device , verbose = True ) sys . stdout . write ( 'ARM Id: %d\n' % jlink . core_id ( ) ) sys . stdout . write ( 'CPU Id: %d\n' % jlink . core_cpu ( ) ) sys . stdout . write ( 'Core Name: %s\n' % jlink . core_name ( ) ) sys . stdout . write ( 'Device Family: %d\n' % jlink . device_family ( ) )
Prints the core s information .
206
7
229,931
def acquire ( self ) : if os . path . exists ( self . path ) : try : pid = None with open ( self . path , 'r' ) as f : line = f . readline ( ) . strip ( ) pid = int ( line ) # In the case that the lockfile exists, but the pid does not # correspond to a valid process, remove the file. if not psutil . pid_exists ( pid ) : os . remove ( self . path ) except ValueError as e : # Pidfile is invalid, so just delete it. os . remove ( self . path ) except IOError as e : # Something happened while trying to read/remove the file, so # skip trying to read/remove it. pass try : self . fd = os . open ( self . path , os . O_CREAT | os . O_EXCL | os . O_RDWR ) # PID is written to the file, so that if a process exits wtihout # cleaning up the lockfile, we can still acquire the lock. to_write = '%s%s' % ( os . getpid ( ) , os . linesep ) os . write ( self . fd , to_write . encode ( ) ) except OSError as e : if not os . path . exists ( self . path ) : raise return False self . acquired = True return True
Attempts to acquire a lock for the J - Link lockfile .
297
13
229,932
def release ( self ) : if not self . acquired : return False os . close ( self . fd ) if os . path . exists ( self . path ) : os . remove ( self . path ) self . acquired = False return True
Cleans up the lockfile if it was acquired .
50
11
229,933
def calculate_parity ( n ) : if not is_natural ( n ) : raise ValueError ( 'Expected n to be a positive integer.' ) y = 0 n = abs ( n ) while n : y += n & 1 n = n >> 1 return y & 1
Calculates and returns the parity of a number .
59
11
229,934
def pack ( value , nbits = None ) : if nbits is None : nbits = pack_size ( value ) * BITS_PER_BYTE elif nbits <= 0 : raise ValueError ( 'Given number of bits must be greater than 0.' ) buf_size = int ( math . ceil ( nbits / float ( BITS_PER_BYTE ) ) ) buf = ( ctypes . c_uint8 * buf_size ) ( ) for ( idx , _ ) in enumerate ( buf ) : buf [ idx ] = ( value >> ( idx * BITS_PER_BYTE ) ) & 0xFF return buf
Packs a given value into an array of 8 - bit unsigned integers .
142
15
229,935
def long_description ( ) : cwd = os . path . abspath ( os . path . dirname ( __file__ ) ) readme_path = os . path . join ( cwd , 'README.md' ) if not os . path . exists ( readme_path ) : return pylink . __long_description__ try : import pypandoc return pypandoc . convert ( readme_path , 'rst' ) except ( IOError , ImportError ) : pass return open ( readme_path , 'r' ) . read ( )
Reads and returns the contents of the README .
125
11
229,936
def finalize_options ( self ) : self . cwd = os . path . abspath ( os . path . dirname ( __file__ ) ) self . build_dirs = [ os . path . join ( self . cwd , 'build' ) , os . path . join ( self . cwd , 'htmlcov' ) , os . path . join ( self . cwd , 'dist' ) , os . path . join ( self . cwd , 'pylink_square.egg-info' ) ] self . build_artifacts = [ '.pyc' , '.o' , '.elf' , '.bin' ]
Populate the attributes .
139
5
229,937
def finalize_options ( self ) : self . cwd = os . path . abspath ( os . path . dirname ( __file__ ) ) self . test_dir = os . path . join ( self . cwd , 'tests' )
Finalizes the command s options .
54
7
229,938
def unlock_kinetis_identified ( identity , flags ) : if flags . version_code != identity . version_code : return False if flags . part_no != identity . part_no : return False return flags . valid
Checks whether the given flags are a valid identity .
48
11
229,939
def unlock_kinetis_abort_clear ( ) : flags = registers . AbortRegisterFlags ( ) flags . STKCMPCLR = 1 flags . STKERRCLR = 1 flags . WDERRCLR = 1 flags . ORUNERRCLR = 1 return flags . value
Returns the abort register clear code .
64
7
229,940
def unlock_kinetis_read_until_ack ( jlink , address ) : request = swd . ReadRequest ( address , ap = True ) response = None while True : response = request . send ( jlink ) if response . ack ( ) : break elif response . wait ( ) : continue raise KinetisException ( 'Read exited with status: %s' , response . status ) return response
Polls the device until the request is acknowledged .
88
10
229,941
def unlock_kinetis_swd ( jlink ) : SWDIdentity = Identity ( 0x2 , 0xBA01 ) jlink . power_on ( ) jlink . coresight_configure ( ) # 1. Verify that the device is configured properly. flags = registers . IDCodeRegisterFlags ( ) flags . value = jlink . coresight_read ( 0x0 , False ) if not unlock_kinetis_identified ( SWDIdentity , flags ) : return False # 2. Check for errors. flags = registers . ControlStatusRegisterFlags ( ) flags . value = jlink . coresight_read ( 0x01 , False ) if flags . STICKYORUN or flags . STICKYCMP or flags . STICKYERR or flags . WDATAERR : jlink . coresight_write ( 0x0 , unlock_kinetis_abort_clear ( ) , False ) # 3. Turn on device power and debug. flags = registers . ControlStatusRegisterFlags ( ) flags . value = 0 flags . CSYSPWRUPREQ = 1 # System power-up request flags . CDBGPWRUPREQ = 1 # Debug power-up request jlink . coresight_write ( 0x01 , flags . value , False ) # 4. Assert the reset pin. jlink . set_reset_pin_low ( ) time . sleep ( 1 ) # 5. Send a SWD Request to clear any errors. request = swd . WriteRequest ( 0x0 , False , unlock_kinetis_abort_clear ( ) ) request . send ( jlink ) # 6. Send a SWD Request to select the MDM-AP register, SELECT[31:24] = 0x01 request = swd . WriteRequest ( 0x2 , False , ( 1 << 24 ) ) request . send ( jlink ) try : # 7. Poll until the Flash-ready bit is set in the status register flags. # Have to read first to ensure the data is valid. unlock_kinetis_read_until_ack ( jlink , 0x0 ) flags = registers . MDMAPStatusRegisterFlags ( ) flags . flash_ready = 0 while not flags . flash_ready : flags . value = unlock_kinetis_read_until_ack ( jlink , 0x0 ) . data # 8. System may still be secure at this point, so request a mass erase. # AP[1] bank 0, register 1 is the MDM-AP Control Register. flags = registers . MDMAPControlRegisterFlags ( ) flags . flash_mass_erase = 1 request = swd . WriteRequest ( 0x1 , True , flags . value ) request . send ( jlink ) # 9. Poll the status register until the mass erase command has been # accepted. unlock_kinetis_read_until_ack ( jlink , 0x0 ) flags = registers . MDMAPStatusRegisterFlags ( ) flags . flash_mass_erase_ack = 0 while not flags . flash_mass_erase_ack : flags . value = unlock_kinetis_read_until_ack ( jlink , 0x0 ) . data # 10. Poll the control register until the ``flash_mass_erase`` bit is # cleared, which is done automatically when the mass erase # finishes. unlock_kinetis_read_until_ack ( jlink , 0x1 ) flags = registers . MDMAPControlRegisterFlags ( ) flags . flash_mass_erase = 1 while flags . flash_mass_erase : flags . value = unlock_kinetis_read_until_ack ( jlink , 0x1 ) . data except KinetisException as e : jlink . set_reset_pin_high ( ) return False jlink . set_reset_pin_high ( ) time . sleep ( 1 ) jlink . reset ( ) return True
Unlocks a Kinetis device over SWD .
843
11
229,942
def unlock_kinetis ( jlink ) : if not jlink . connected ( ) : raise ValueError ( 'No target to unlock.' ) method = UNLOCK_METHODS . get ( jlink . tif , None ) if method is None : raise NotImplementedError ( 'Unsupported target interface for unlock.' ) return method ( jlink )
Unlock for Freescale Kinetis K40 or K60 device .
76
16
229,943
def minimum_required ( version ) : def _minimum_required ( func ) : """Internal decorator that wraps around the given function. Args: func (function): function being decorated Returns: The wrapper unction. """ @ functools . wraps ( func ) def wrapper ( self , * args , * * kwargs ) : """Wrapper function to compare the DLL's SDK version. Args: self (JLink): the ``JLink`` instance args (list): list of arguments to pass to ``func`` kwargs (dict): key-word arguments dict to pass to ``func`` Returns: The return value of the wrapped function. Raises: JLinkException: if the DLL's version is less than ``version``. """ if list ( self . version ) < list ( version ) : raise errors . JLinkException ( 'Version %s required.' % version ) return func ( self , * args , * * kwargs ) return wrapper return _minimum_required
Decorator to specify the minimum SDK version required .
208
11
229,944
def open_required ( func ) : @ functools . wraps ( func ) def wrapper ( self , * args , * * kwargs ) : """Wrapper function to check that the given ``JLink`` has been opened. Args: self (JLink): the ``JLink`` instance args: list of arguments to pass to the wrapped function kwargs: key-word arguments dict to pass to the wrapped function Returns: The return value of the wrapped function. Raises: JLinkException: if the J-Link DLL is not open or the J-Link is disconnected. """ if not self . opened ( ) : raise errors . JLinkException ( 'J-Link DLL is not open.' ) elif not self . connected ( ) : raise errors . JLinkException ( 'J-Link connection has been lost.' ) return func ( self , * args , * * kwargs ) return wrapper
Decorator to specify that the J - Link DLL must be opened and a J - Link connection must be established .
193
25
229,945
def connection_required ( func ) : @ functools . wraps ( func ) def wrapper ( self , * args , * * kwargs ) : """Wrapper function to check that the given ``JLink`` has been connected to a target. Args: self (JLink): the ``JLink`` instance args: list of arguments to pass to the wrapped function kwargs: key-word arguments dict to pass to the wrapped function Returns: The return value of the wrapped function. Raises: JLinkException: if the JLink's target is not connected. """ if not self . target_connected ( ) : raise errors . JLinkException ( 'Target is not connected.' ) return func ( self , * args , * * kwargs ) return wrapper
Decorator to specify that a target connection is required in order for the given method to be used .
160
21
229,946
def interface_required ( interface ) : def _interface_required ( func ) : """Internal decorator that wraps around the decorated function. Args: func (function): function being decorated Returns: The wrapper function. """ @ functools . wraps ( func ) def wrapper ( self , * args , * * kwargs ) : """Wrapper function to check that the given ``JLink`` has the same interface as the one specified by the decorator. Args: self (JLink): the ``JLink`` instance args: list of arguments to pass to ``func`` kwargs: key-word arguments dict to pass to ``func`` Returns: The return value of the wrapped function. Raises: JLinkException: if the current interface is not supported by the wrapped method. """ if self . tif != interface : raise errors . JLinkException ( 'Unsupported for current interface.' ) return func ( self , * args , * * kwargs ) return wrapper return _interface_required
Decorator to specify that a particular interface type is required for the given method to be used .
209
20
229,947
def log_handler ( self , handler ) : if not self . opened ( ) : handler = handler or util . noop self . _log_handler = enums . JLinkFunctions . LOG_PROTOTYPE ( handler ) self . _dll . JLINKARM_EnableLog ( self . _log_handler )
Setter for the log handler function .
71
8
229,948
def detailed_log_handler ( self , handler ) : if not self . opened ( ) : handler = handler or util . noop self . _detailed_log_handler = enums . JLinkFunctions . LOG_PROTOTYPE ( handler ) self . _dll . JLINKARM_EnableLogCom ( self . _detailed_log_handler )
Setter for the detailed log handler function .
80
9
229,949
def error_handler ( self , handler ) : if not self . opened ( ) : handler = handler or util . noop self . _error_handler = enums . JLinkFunctions . LOG_PROTOTYPE ( handler ) self . _dll . JLINKARM_SetErrorOutHandler ( self . _error_handler )
Setter for the error handler function .
73
8
229,950
def warning_handler ( self , handler ) : if not self . opened ( ) : handler = handler or util . noop self . _warning_handler = enums . JLinkFunctions . LOG_PROTOTYPE ( handler ) self . _dll . JLINKARM_SetWarnOutHandler ( self . _warning_handler )
Setter for the warning handler function .
74
8
229,951
def connected_emulators ( self , host = enums . JLinkHost . USB ) : res = self . _dll . JLINKARM_EMU_GetList ( host , 0 , 0 ) if res < 0 : raise errors . JLinkException ( res ) num_devices = res info = ( structs . JLinkConnectInfo * num_devices ) ( ) num_found = self . _dll . JLINKARM_EMU_GetList ( host , info , num_devices ) if num_found < 0 : raise errors . JLinkException ( num_found ) return list ( info ) [ : num_found ]
Returns a list of all the connected emulators .
137
10
229,952
def supported_device ( self , index = 0 ) : if not util . is_natural ( index ) or index >= self . num_supported_devices ( ) : raise ValueError ( 'Invalid index.' ) info = structs . JLinkDeviceInfo ( ) result = self . _dll . JLINKARM_DEVICE_GetInfo ( index , ctypes . byref ( info ) ) return info
Gets the device at the given index .
86
9
229,953
def close ( self ) : self . _dll . JLINKARM_Close ( ) if self . _lock is not None : del self . _lock self . _lock = None return None
Closes the open J - Link .
41
8
229,954
def sync_firmware ( self ) : serial_no = self . serial_number if self . firmware_newer ( ) : # The J-Link's firmware is newer than the one compatible with the # DLL (though there are promises of backwards compatibility), so # perform a downgrade. try : # This may throw an exception on older versions of the J-Link # software due to the software timing out after a firmware # upgrade. self . invalidate_firmware ( ) self . update_firmware ( ) except errors . JLinkException as e : pass res = self . open ( serial_no = serial_no ) if self . firmware_newer ( ) : raise errors . JLinkException ( 'Failed to sync firmware version.' ) return res elif self . firmware_outdated ( ) : # The J-Link's firmware is older than the one compatible with the # DLL, so perform a firmware upgrade. try : # This may throw an exception on older versions of the J-Link # software due to the software timing out after a firmware # upgrade. self . update_firmware ( ) except errors . JLinkException as e : pass if self . firmware_outdated ( ) : raise errors . JLinkException ( 'Failed to sync firmware version.' ) return self . open ( serial_no = serial_no ) return None
Syncs the emulator s firmware version and the DLL s firmware .
289
14
229,955
def exec_command ( self , cmd ) : err_buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) res = self . _dll . JLINKARM_ExecCommand ( cmd . encode ( ) , err_buf , self . MAX_BUF_SIZE ) err_buf = ctypes . string_at ( err_buf ) . decode ( ) if len ( err_buf ) > 0 : # This is how they check for error in the documentation, so check # this way as well. raise errors . JLinkException ( err_buf . strip ( ) ) return res
Executes the given command .
133
6
229,956
def jtag_configure ( self , instr_regs = 0 , data_bits = 0 ) : if not util . is_natural ( instr_regs ) : raise ValueError ( 'IR value is not a natural number.' ) if not util . is_natural ( data_bits ) : raise ValueError ( 'Data bits is not a natural number.' ) self . _dll . JLINKARM_ConfigJTAG ( instr_regs , data_bits ) return None
Configures the JTAG scan chain to determine which CPU to address .
103
14
229,957
def coresight_configure ( self , ir_pre = 0 , dr_pre = 0 , ir_post = 0 , dr_post = 0 , ir_len = 0 , perform_tif_init = True ) : if self . tif == enums . JLinkInterfaces . SWD : # No special setup is needed for SWD, just need to output the # switching sequence. res = self . _dll . JLINKARM_CORESIGHT_Configure ( '' ) if res < 0 : raise errors . JLinkException ( res ) return None # JTAG requires more setup than SWD. config_string = 'IRPre=%s;DRPre=%s;IRPost=%s;DRPost=%s;IRLenDevice=%s;' config_string = config_string % ( ir_pre , dr_pre , ir_post , dr_post , ir_len ) if not perform_tif_init : config_string = config_string + ( 'PerformTIFInit=0;' ) res = self . _dll . JLINKARM_CORESIGHT_Configure ( config_string . encode ( ) ) if res < 0 : raise errors . JLinkException ( res ) return None
Prepares target and J - Link for CoreSight function usage .
268
14
229,958
def connect ( self , chip_name , speed = 'auto' , verbose = False ) : if verbose : self . exec_command ( 'EnableRemarks = 1' ) # This is weird but is currently the only way to specify what the # target is to the J-Link. self . exec_command ( 'Device = %s' % chip_name ) # Need to select target interface speed here, so the J-Link knows what # speed to use to establish target communication. if speed == 'auto' : self . set_speed ( auto = True ) elif speed == 'adaptive' : self . set_speed ( adaptive = True ) else : self . set_speed ( speed ) result = self . _dll . JLINKARM_Connect ( ) if result < 0 : raise errors . JLinkException ( result ) try : # Issue a no-op command after connect. This has to be in a try-catch. self . halted ( ) except errors . JLinkException : pass # Determine which device we are. This is essential for using methods # like 'unlock' or 'lock'. for index in range ( self . num_supported_devices ( ) ) : device = self . supported_device ( index ) if device . name . lower ( ) == chip_name . lower ( ) : self . _device = device break else : raise errors . JLinkException ( 'Unsupported device was connected to.' ) return None
Connects the J - Link to its target .
308
10
229,959
def compile_date ( self ) : result = self . _dll . JLINKARM_GetCompileDateTime ( ) return ctypes . cast ( result , ctypes . c_char_p ) . value . decode ( )
Returns a string specifying the date and time at which the DLL was translated .
50
16
229,960
def version ( self ) : version = int ( self . _dll . JLINKARM_GetDLLVersion ( ) ) major = version / 10000 minor = ( version / 100 ) % 100 rev = version % 100 rev = '' if rev == 0 else chr ( rev + ord ( 'a' ) - 1 ) return '%d.%02d%s' % ( major , minor , rev )
Returns the device s version .
87
6
229,961
def compatible_firmware_version ( self ) : identifier = self . firmware_version . split ( 'compiled' ) [ 0 ] buf_size = self . MAX_BUF_SIZE buf = ( ctypes . c_char * buf_size ) ( ) res = self . _dll . JLINKARM_GetEmbeddedFWString ( identifier . encode ( ) , buf , buf_size ) if res < 0 : raise errors . JLinkException ( res ) return ctypes . string_at ( buf ) . decode ( )
Returns the DLL s compatible J - Link firmware version .
116
12
229,962
def firmware_outdated ( self ) : datefmt = ' %b %d %Y %H:%M:%S' compat_date = self . compatible_firmware_version . split ( 'compiled' ) [ 1 ] compat_date = datetime . datetime . strptime ( compat_date , datefmt ) fw_date = self . firmware_version . split ( 'compiled' ) [ 1 ] fw_date = datetime . datetime . strptime ( fw_date , datefmt ) return ( compat_date > fw_date )
Returns whether the J - Link s firmware version is older than the one that the DLL is compatible with .
131
22
229,963
def hardware_info ( self , mask = 0xFFFFFFFF ) : buf = ( ctypes . c_uint32 * 32 ) ( ) res = self . _dll . JLINKARM_GetHWInfo ( mask , ctypes . byref ( buf ) ) if res != 0 : raise errors . JLinkException ( res ) return list ( buf )
Returns a list of 32 integer values corresponding to the bitfields specifying the power consumption of the target .
77
20
229,964
def hardware_status ( self ) : stat = structs . JLinkHardwareStatus ( ) res = self . _dll . JLINKARM_GetHWStatus ( ctypes . byref ( stat ) ) if res == 1 : raise errors . JLinkException ( 'Error in reading hardware status.' ) return stat
Retrieves and returns the hardware status .
67
9
229,965
def hardware_version ( self ) : version = self . _dll . JLINKARM_GetHardwareVersion ( ) major = version / 10000 % 100 minor = version / 100 % 100 return '%d.%02d' % ( major , minor )
Returns the hardware version of the connected J - Link as a major . minor string .
54
17
229,966
def firmware_version ( self ) : buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) self . _dll . JLINKARM_GetFirmwareString ( buf , self . MAX_BUF_SIZE ) return ctypes . string_at ( buf ) . decode ( )
Returns a firmware identification string of the connected J - Link .
70
12
229,967
def extended_capabilities ( self ) : buf = ( ctypes . c_uint8 * 32 ) ( ) self . _dll . JLINKARM_GetEmuCapsEx ( buf , 32 ) return list ( buf )
Gets the capabilities of the connected emulator as a list .
50
12
229,968
def features ( self ) : buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) self . _dll . JLINKARM_GetFeatureString ( buf ) result = ctypes . string_at ( buf ) . decode ( ) . strip ( ) if len ( result ) == 0 : return list ( ) return result . split ( ', ' )
Returns a list of the J - Link embedded features .
82
11
229,969
def product_name ( self ) : buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) self . _dll . JLINKARM_EMU_GetProductName ( buf , self . MAX_BUF_SIZE ) return ctypes . string_at ( buf ) . decode ( )
Returns the product name of the connected J - Link .
71
11
229,970
def oem ( self ) : buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) res = self . _dll . JLINKARM_GetOEMString ( ctypes . byref ( buf ) ) if res != 0 : raise errors . JLinkException ( 'Failed to grab OEM string.' ) oem = ctypes . string_at ( buf ) . decode ( ) if len ( oem ) == 0 : # In the case that the product is an original SEGGER product, then # the OEM string is the empty string, so there is no OEM. return None return oem
Retrieves and returns the OEM string of the connected J - Link .
136
15
229,971
def set_speed ( self , speed = None , auto = False , adaptive = False ) : if speed is None : speed = 0 elif not util . is_natural ( speed ) : raise TypeError ( 'Expected positive number for speed, given %s.' % speed ) elif speed > self . MAX_JTAG_SPEED : raise ValueError ( 'Given speed exceeds max speed of %d.' % self . MAX_JTAG_SPEED ) elif speed < self . MIN_JTAG_SPEED : raise ValueError ( 'Given speed is too slow. Minimum is %d.' % self . MIN_JTAG_SPEED ) if auto : speed = speed | self . AUTO_JTAG_SPEED if adaptive : speed = speed | self . ADAPTIVE_JTAG_SPEED self . _dll . JLINKARM_SetSpeed ( speed ) return None
Sets the speed of the JTAG communication with the ARM core .
192
14
229,972
def speed_info ( self ) : speed_info = structs . JLinkSpeedInfo ( ) self . _dll . JLINKARM_GetSpeedInfo ( ctypes . byref ( speed_info ) ) return speed_info
Retrieves information about supported target interface speeds .
50
10
229,973
def licenses ( self ) : buf_size = self . MAX_BUF_SIZE buf = ( ctypes . c_char * buf_size ) ( ) res = self . _dll . JLINK_GetAvailableLicense ( buf , buf_size ) if res < 0 : raise errors . JLinkException ( res ) return ctypes . string_at ( buf ) . decode ( )
Returns a string of the built - in licenses the J - Link has .
83
15
229,974
def custom_licenses ( self ) : buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( ) result = self . _dll . JLINK_EMU_GetLicenses ( buf , self . MAX_BUF_SIZE ) if result < 0 : raise errors . JLinkException ( result ) return ctypes . string_at ( buf ) . decode ( )
Returns a string of the installed licenses the J - Link has .
87
13
229,975
def add_license ( self , contents ) : buf_size = len ( contents ) buf = ( ctypes . c_char * ( buf_size + 1 ) ) ( * contents . encode ( ) ) res = self . _dll . JLINK_EMU_AddLicense ( buf ) if res == - 1 : raise errors . JLinkException ( 'Unspecified error.' ) elif res == - 2 : raise errors . JLinkException ( 'Failed to read/write license area.' ) elif res == - 3 : raise errors . JLinkException ( 'J-Link out of space.' ) return ( res == 0 )
Adds the given contents as a new custom license to the J - Link .
136
15
229,976
def supported_tifs ( self ) : buf = ctypes . c_uint32 ( ) self . _dll . JLINKARM_TIF_GetAvailable ( ctypes . byref ( buf ) ) return buf . value
Returns a bitmask of the supported target interfaces .
49
10
229,977
def set_tif ( self , interface ) : if not ( ( 1 << interface ) & self . supported_tifs ( ) ) : raise errors . JLinkException ( 'Unsupported target interface: %s' % interface ) # The return code here is actually *NOT* the previous set interface, it # is ``0`` on success, otherwise ``1``. res = self . _dll . JLINKARM_TIF_Select ( interface ) if res != 0 : return False self . _tif = interface return True
Selects the specified target interface .
111
7
229,978
def gpio_properties ( self ) : res = self . _dll . JLINK_EMU_GPIO_GetProps ( 0 , 0 ) if res < 0 : raise errors . JLinkException ( res ) num_props = res buf = ( structs . JLinkGPIODescriptor * num_props ) ( ) res = self . _dll . JLINK_EMU_GPIO_GetProps ( ctypes . byref ( buf ) , num_props ) if res < 0 : raise errors . JLinkException ( res ) return list ( buf )
Returns the properties of the user - controllable GPIOs .
130
13
229,979
def gpio_get ( self , pins = None ) : if pins is None : pins = range ( 4 ) size = len ( pins ) indices = ( ctypes . c_uint8 * size ) ( * pins ) statuses = ( ctypes . c_uint8 * size ) ( ) result = self . _dll . JLINK_EMU_GPIO_GetState ( ctypes . byref ( indices ) , ctypes . byref ( statuses ) , size ) if result < 0 : raise errors . JLinkException ( result ) return list ( statuses )
Returns a list of states for the given pins .
124
10
229,980
def gpio_set ( self , pins , states ) : if len ( pins ) != len ( states ) : raise ValueError ( 'Length mismatch between pins and states.' ) size = len ( pins ) indices = ( ctypes . c_uint8 * size ) ( * pins ) states = ( ctypes . c_uint8 * size ) ( * states ) result_states = ( ctypes . c_uint8 * size ) ( ) result = self . _dll . JLINK_EMU_GPIO_SetState ( ctypes . byref ( indices ) , ctypes . byref ( states ) , ctypes . byref ( result_states ) , size ) if result < 0 : raise errors . JLinkException ( result ) return list ( result_states )
Sets the state for one or more user - controllable GPIOs .
166
16
229,981
def unlock ( self ) : if not unlockers . unlock ( self , self . _device . manufacturer ) : raise errors . JLinkException ( 'Failed to unlock device.' ) return True
Unlocks the device connected to the J - Link .
40
11
229,982
def erase ( self ) : try : # This has to be in a try-catch, as the device may not be in a # state where it can halt, but we still want to try and erase. if not self . halted ( ) : self . halt ( ) except errors . JLinkException : # Can't halt, so just continue to erasing. pass res = self . _dll . JLINK_EraseChip ( ) if res < 0 : raise errors . JLinkEraseException ( res ) return res
Erases the flash contents of the device .
110
9
229,983
def reset ( self , ms = 0 , halt = True ) : self . _dll . JLINKARM_SetResetDelay ( ms ) res = self . _dll . JLINKARM_Reset ( ) if res < 0 : raise errors . JLinkException ( res ) elif not halt : self . _dll . JLINKARM_Go ( ) return res
Resets the target .
82
5
229,984
def halt ( self ) : res = int ( self . _dll . JLINKARM_Halt ( ) ) if res == 0 : time . sleep ( 1 ) return True return False
Halts the CPU Core .
40
6
229,985
def halted ( self ) : result = int ( self . _dll . JLINKARM_IsHalted ( ) ) if result < 0 : raise errors . JLinkException ( result ) return ( result > 0 )
Returns whether the CPU core was halted .
46
8
229,986
def core_name ( self ) : buf_size = self . MAX_BUF_SIZE buf = ( ctypes . c_char * buf_size ) ( ) self . _dll . JLINKARM_Core2CoreName ( self . core_cpu ( ) , buf , buf_size ) return ctypes . string_at ( buf ) . decode ( )
Returns the name of the target ARM core .
79
9
229,987
def scan_chain_len ( self , scan_chain ) : res = self . _dll . JLINKARM_MeasureSCLen ( scan_chain ) if res < 0 : raise errors . JLinkException ( res ) return res
Retrieves and returns the number of bits in the scan chain .
51
14
229,988
def register_list ( self ) : num_items = self . MAX_NUM_CPU_REGISTERS buf = ( ctypes . c_uint32 * num_items ) ( ) num_regs = self . _dll . JLINKARM_GetRegisterList ( buf , num_items ) return buf [ : num_regs ]
Returns a list of the indices for the CPU registers .
74
11
229,989
def register_name ( self , register_index ) : result = self . _dll . JLINKARM_GetRegisterName ( register_index ) return ctypes . cast ( result , ctypes . c_char_p ) . value . decode ( )
Retrives and returns the name of an ARM CPU register .
55
13
229,990
def cpu_speed ( self , silent = False ) : res = self . _dll . JLINKARM_MeasureCPUSpeedEx ( - 1 , 1 , int ( silent ) ) if res < 0 : raise errors . JLinkException ( res ) return res
Retrieves the CPU speed of the target .
56
10
229,991
def cpu_halt_reasons ( self ) : buf_size = self . MAX_NUM_MOES buf = ( structs . JLinkMOEInfo * buf_size ) ( ) num_reasons = self . _dll . JLINKARM_GetMOEs ( buf , buf_size ) if num_reasons < 0 : raise errors . JLinkException ( num_reasons ) return list ( buf ) [ : num_reasons ]
Retrives the reasons that the CPU was halted .
99
11
229,992
def jtag_send ( self , tms , tdi , num_bits ) : if not util . is_natural ( num_bits ) or num_bits <= 0 or num_bits > 32 : raise ValueError ( 'Number of bits must be >= 1 and <= 32.' ) self . _dll . JLINKARM_StoreBits ( tms , tdi , num_bits ) return None
Sends data via JTAG .
87
7
229,993
def swd_read8 ( self , offset ) : value = self . _dll . JLINK_SWD_GetU8 ( offset ) return ctypes . c_uint8 ( value ) . value
Gets a unit of 8 bits from the input buffer .
45
12
229,994
def swd_read16 ( self , offset ) : value = self . _dll . JLINK_SWD_GetU16 ( offset ) return ctypes . c_uint16 ( value ) . value
Gets a unit of 16 bits from the input buffer .
45
12
229,995
def swd_read32 ( self , offset ) : value = self . _dll . JLINK_SWD_GetU32 ( offset ) return ctypes . c_uint32 ( value ) . value
Gets a unit of 32 bits from the input buffer .
45
12
229,996
def swd_sync ( self , pad = False ) : if pad : self . _dll . JLINK_SWD_SyncBytes ( ) else : self . _dll . JLINK_SWD_SyncBits ( ) return None
Causes a flush to write all data remaining in output buffers to SWD device .
53
17
229,997
def flash_write ( self , addr , data , nbits = None , flags = 0 ) : # This indicates that all data written from this point on will go into # the buffer of the flashloader of the DLL. self . _dll . JLINKARM_BeginDownload ( flags ) self . memory_write ( addr , data , nbits = nbits ) # Start downloading the data into the flash memory. bytes_flashed = self . _dll . JLINKARM_EndDownload ( ) if bytes_flashed < 0 : raise errors . JLinkFlashException ( bytes_flashed ) return bytes_flashed
Writes data to the flash region of a device .
133
11
229,998
def code_memory_read ( self , addr , num_bytes ) : buf_size = num_bytes buf = ( ctypes . c_uint8 * buf_size ) ( ) res = self . _dll . JLINKARM_ReadCodeMem ( addr , buf_size , buf ) if res < 0 : raise errors . JLinkException ( res ) return list ( buf ) [ : res ]
Reads bytes from code memory .
87
7
229,999
def num_memory_zones ( self ) : count = self . _dll . JLINK_GetMemZones ( 0 , 0 ) if count < 0 : raise errors . JLinkException ( count ) return count
Returns the number of memory zones supported by the target .
47
11