idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
227,900
def verify_json ( self , json , user_key , user_id , device_id ) : try : signatures = json . pop ( 'signatures' ) except KeyError : return False key_id = 'ed25519:{}' . format ( device_id ) try : signature_base64 = signatures [ user_id ] [ key_id ] except KeyError : json [ 'signatures' ] = signatures return False unsigned = json . pop ( 'unsigned' , None ) try : olm . ed25519_verify ( user_key , encode_canonical_json ( json ) , signature_base64 ) success = True except olm . utility . OlmVerifyError : success = False json [ 'signatures' ] = signatures if unsigned : json [ 'unsigned' ] = unsigned return success
Verifies a signed key object s signature .
175
9
227,901
def get_display_name ( self , room = None ) : if room : try : return room . members_displaynames [ self . user_id ] except KeyError : return self . user_id if not self . displayname : self . displayname = self . api . get_display_name ( self . user_id ) return self . displayname or self . user_id
Get this user s display name .
82
7
227,902
def set_display_name ( self , display_name ) : self . displayname = display_name return self . api . set_display_name ( self . user_id , display_name )
Set this users display name .
43
6
227,903
def prepare_encrypted_request ( self , session , endpoint , message ) : host = urlsplit ( endpoint ) . hostname if self . protocol == 'credssp' and len ( message ) > self . SIXTEN_KB : content_type = 'multipart/x-multi-encrypted' encrypted_message = b'' message_chunks = [ message [ i : i + self . SIXTEN_KB ] for i in range ( 0 , len ( message ) , self . SIXTEN_KB ) ] for message_chunk in message_chunks : encrypted_chunk = self . _encrypt_message ( message_chunk , host ) encrypted_message += encrypted_chunk else : content_type = 'multipart/encrypted' encrypted_message = self . _encrypt_message ( message , host ) encrypted_message += self . MIME_BOUNDARY + b"--\r\n" request = requests . Request ( 'POST' , endpoint , data = encrypted_message ) prepared_request = session . prepare_request ( request ) prepared_request . headers [ 'Content-Length' ] = str ( len ( prepared_request . body ) ) prepared_request . headers [ 'Content-Type' ] = '{0};protocol="{1}";boundary="Encrypted Boundary"' . format ( content_type , self . protocol_string . decode ( ) ) return prepared_request
Creates a prepared request to send to the server with an encrypted message and correct headers
314
17
227,904
def parse_encrypted_response ( self , response ) : content_type = response . headers [ 'Content-Type' ] if 'protocol="{0}"' . format ( self . protocol_string . decode ( ) ) in content_type : host = urlsplit ( response . request . url ) . hostname msg = self . _decrypt_response ( response , host ) else : msg = response . text return msg
Takes in the encrypted response from the server and decrypts it
92
13
227,905
def open_shell ( self , i_stream = 'stdin' , o_stream = 'stdout stderr' , working_directory = None , env_vars = None , noprofile = False , codepage = 437 , lifetime = None , idle_timeout = None ) : req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , # NOQA action = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Create' ) } header = req [ 'env:Envelope' ] [ 'env:Header' ] header [ 'w:OptionSet' ] = { 'w:Option' : [ { '@Name' : 'WINRS_NOPROFILE' , '#text' : str ( noprofile ) . upper ( ) # TODO remove str call } , { '@Name' : 'WINRS_CODEPAGE' , '#text' : str ( codepage ) # TODO remove str call } ] } shell = req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) . setdefault ( 'rsp:Shell' , { } ) shell [ 'rsp:InputStreams' ] = i_stream shell [ 'rsp:OutputStreams' ] = o_stream if working_directory : # TODO ensure that rsp:WorkingDirectory should be nested within rsp:Shell # NOQA shell [ 'rsp:WorkingDirectory' ] = working_directory # TODO check Lifetime param: http://msdn.microsoft.com/en-us/library/cc251546(v=PROT.13).aspx # NOQA #if lifetime: # shell['rsp:Lifetime'] = iso8601_duration.sec_to_dur(lifetime) # TODO make it so the input is given in milliseconds and converted to xs:duration # NOQA if idle_timeout : shell [ 'rsp:IdleTimeOut' ] = idle_timeout if env_vars : env = shell . setdefault ( 'rsp:Environment' , { } ) for key , value in env_vars . items ( ) : env [ 'rsp:Variable' ] = { '@Name' : key , '#text' : value } res = self . send_message ( xmltodict . unparse ( req ) ) #res = xmltodict.parse(res) #return res['s:Envelope']['s:Body']['x:ResourceCreated']['a:ReferenceParameters']['w:SelectorSet']['w:Selector']['#text'] root = ET . fromstring ( res ) return next ( node for node in root . findall ( './/*' ) if node . get ( 'Name' ) == 'ShellId' ) . text
Create a Shell on the destination host
673
7
227,906
def close_shell ( self , shell_id ) : message_id = uuid . uuid4 ( ) req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , # NOQA action = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete' , shell_id = shell_id , message_id = message_id ) } # SOAP message requires empty env:Body req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) res = self . send_message ( xmltodict . unparse ( req ) ) root = ET . fromstring ( res ) relates_to = next ( node for node in root . findall ( './/*' ) if node . tag . endswith ( 'RelatesTo' ) ) . text # TODO change assert into user-friendly exception assert uuid . UUID ( relates_to . replace ( 'uuid:' , '' ) ) == message_id
Close the shell
256
3
227,907
def run_command ( self , shell_id , command , arguments = ( ) , console_mode_stdin = True , skip_cmd_shell = False ) : req = { 'env:Envelope' : self . _get_soap_header ( resource_uri = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd' , # NOQA action = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command' , # NOQA shell_id = shell_id ) } header = req [ 'env:Envelope' ] [ 'env:Header' ] header [ 'w:OptionSet' ] = { 'w:Option' : [ { '@Name' : 'WINRS_CONSOLEMODE_STDIN' , '#text' : str ( console_mode_stdin ) . upper ( ) } , { '@Name' : 'WINRS_SKIP_CMD_SHELL' , '#text' : str ( skip_cmd_shell ) . upper ( ) } ] } cmd_line = req [ 'env:Envelope' ] . setdefault ( 'env:Body' , { } ) . setdefault ( 'rsp:CommandLine' , { } ) cmd_line [ 'rsp:Command' ] = { '#text' : command } if arguments : unicode_args = [ a if isinstance ( a , text_type ) else a . decode ( 'utf-8' ) for a in arguments ] cmd_line [ 'rsp:Arguments' ] = u' ' . join ( unicode_args ) res = self . send_message ( xmltodict . unparse ( req ) ) root = ET . fromstring ( res ) command_id = next ( node for node in root . findall ( './/*' ) if node . tag . endswith ( 'CommandId' ) ) . text return command_id
Run a command on a machine with an open shell
440
10
227,908
def get_command_output ( self , shell_id , command_id ) : stdout_buffer , stderr_buffer = [ ] , [ ] command_done = False while not command_done : try : stdout , stderr , return_code , command_done = self . _raw_get_command_output ( shell_id , command_id ) stdout_buffer . append ( stdout ) stderr_buffer . append ( stderr ) except WinRMOperationTimeoutError as e : # this is an expected error when waiting for a long-running process, just silently retry pass return b'' . join ( stdout_buffer ) , b'' . join ( stderr_buffer ) , return_code
Get the Output of the given shell and command
161
9
227,909
def run_ps ( self , script ) : # must use utf16 little endian on windows encoded_ps = b64encode ( script . encode ( 'utf_16_le' ) ) . decode ( 'ascii' ) rs = self . run_cmd ( 'powershell -encodedcommand {0}' . format ( encoded_ps ) ) if len ( rs . std_err ) : # if there was an error message, clean it it up and make it human # readable rs . std_err = self . _clean_error_msg ( rs . std_err ) return rs
base64 encodes a Powershell script and executes the powershell encoded script command
130
16
227,910
def _clean_error_msg ( self , msg ) : # TODO prepare unit test, beautify code # if the msg does not start with this, return it as is if msg . startswith ( b"#< CLIXML\r\n" ) : # for proper xml, we need to remove the CLIXML part # (the first line) msg_xml = msg [ 11 : ] try : # remove the namespaces from the xml for easier processing msg_xml = self . _strip_namespace ( msg_xml ) root = ET . fromstring ( msg_xml ) # the S node is the error message, find all S nodes nodes = root . findall ( "./S" ) new_msg = "" for s in nodes : # append error msg string to result, also # the hex chars represent CRLF so we replace with newline new_msg += s . text . replace ( "_x000D__x000A_" , "\n" ) except Exception as e : # if any of the above fails, the msg was not true xml # print a warning and return the orignal string # TODO do not print, raise user defined error instead print ( "Warning: there was a problem converting the Powershell" " error message: %s" % ( e ) ) else : # if new_msg was populated, that's our error message # otherwise the original error message will be used if len ( new_msg ) : # remove leading and trailing whitespace while we are here return new_msg . strip ( ) . encode ( 'utf-8' ) # either failed to decode CLIXML or there was nothing to decode # just return the original message return msg
converts a Powershell CLIXML message to a more human readable string
360
15
227,911
def _strip_namespace ( self , xml ) : p = re . compile ( b"xmlns=*[\"\"][^\"\"]*[\"\"]" ) allmatches = p . finditer ( xml ) for match in allmatches : xml = xml . replace ( match . group ( ) , b"" ) return xml
strips any namespaces from an xml string
73
9
227,912
def return_handler ( module_logger , first_is_session = True ) : def _outer ( visa_library_method ) : def _inner ( self , session , * args , * * kwargs ) : ret_value = visa_library_method ( * args , * * kwargs ) module_logger . debug ( '%s%s -> %r' , visa_library_method . __name__ , _args_to_str ( args , kwargs ) , ret_value ) try : ret_value = constants . StatusCode ( ret_value ) except ValueError : pass if first_is_session : self . _last_status = ret_value self . _last_status_in_session [ session ] = ret_value if ret_value < 0 : raise VisaIOError ( ret_value ) if ret_value in self . issue_warning_on : if session and ret_value not in self . _ignore_warning_in_session [ session ] : module_logger . warn ( VisaIOWarning ( ret_value ) , stacklevel = 2 ) return ret_value return _inner return _outer
Decorator for VISA library classes .
249
9
227,913
def list_backends ( ) : return [ 'ni' ] + [ name for ( loader , name , ispkg ) in pkgutil . iter_modules ( ) if name . startswith ( 'pyvisa-' ) and not name . endswith ( '-script' ) ]
Return installed backends .
63
5
227,914
def get_wrapper_class ( backend_name ) : try : return _WRAPPERS [ backend_name ] except KeyError : if backend_name == 'ni' : from . ctwrapper import NIVisaLibrary _WRAPPERS [ 'ni' ] = NIVisaLibrary return NIVisaLibrary try : pkg = __import__ ( 'pyvisa-' + backend_name ) _WRAPPERS [ backend_name ] = cls = pkg . WRAPPER_CLASS return cls except ImportError : raise ValueError ( 'Wrapper not found: No package named pyvisa-%s' % backend_name )
Return the WRAPPER_CLASS for a given backend .
139
12
227,915
def open_visa_library ( specification ) : if not specification : logger . debug ( 'No visa library specified, trying to find alternatives.' ) try : specification = os . environ [ 'PYVISA_LIBRARY' ] except KeyError : logger . debug ( 'Environment variable PYVISA_LIBRARY is unset.' ) try : argument , wrapper = specification . split ( '@' ) except ValueError : argument = specification wrapper = None # Flag that we need a fallback, but avoid nested exceptions if wrapper is None : if argument : # some filename given wrapper = 'ni' else : wrapper = _get_default_wrapper ( ) cls = get_wrapper_class ( wrapper ) try : return cls ( argument ) except Exception as e : logger . debug ( 'Could not open VISA wrapper %s: %s\n%s' , cls , str ( argument ) , e ) raise
Helper function to create a VISA library wrapper .
198
10
227,916
def get_last_status_in_session ( self , session ) : try : return self . _last_status_in_session [ session ] except KeyError : raise errors . Error ( 'The session %r does not seem to be valid as it does not have any last status' % session )
Last status in session .
64
5
227,917
def ignore_warning ( self , session , * warnings_constants ) : self . _ignore_warning_in_session [ session ] . update ( warnings_constants ) yield self . _ignore_warning_in_session [ session ] . difference_update ( warnings_constants )
A session dependent context for ignoring warnings
61
7
227,918
def uninstall_all_visa_handlers ( self , session ) : if session is not None : self . __uninstall_all_handlers_helper ( session ) else : for session in list ( self . handlers ) : self . __uninstall_all_handlers_helper ( session )
Uninstalls all previously installed handlers for a particular session .
66
12
227,919
def write_memory ( self , session , space , offset , data , width , extended = False ) : if width == 8 : return self . out_8 ( session , space , offset , data , extended ) elif width == 16 : return self . out_16 ( session , space , offset , data , extended ) elif width == 32 : return self . out_32 ( session , space , offset , data , extended ) elif width == 64 : return self . out_64 ( session , space , offset , data , extended ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32, or 64' % width )
Write in an 8 - bit 16 - bit 32 - bit 64 - bit value to the specified memory space and offset .
141
24
227,920
def peek ( self , session , address , width ) : if width == 8 : return self . peek_8 ( session , address ) elif width == 16 : return self . peek_16 ( session , address ) elif width == 32 : return self . peek_32 ( session , address ) elif width == 64 : return self . peek_64 ( session , address ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32 or 64' % width )
Read an 8 16 32 or 64 - bit value from the specified address .
106
15
227,921
def poke ( self , session , address , width , data ) : if width == 8 : return self . poke_8 ( session , address , data ) elif width == 16 : return self . poke_16 ( session , address , data ) elif width == 32 : return self . poke_32 ( session , address , data ) elif width == 64 : return self . poke_64 ( session , address , data ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32, or 64' % width )
Writes an 8 16 32 or 64 - bit value from the specified address .
117
16
227,922
def close ( self ) : try : logger . debug ( 'Closing ResourceManager (session: %s)' , self . session ) # Cleanly close all resources when closing the manager. for resource in self . _created_resources : resource . close ( ) self . visalib . close ( self . session ) self . session = None self . visalib . resource_manager = None except errors . InvalidSession : pass
Close the resource manager session .
89
6
227,923
def list_resources_info ( self , query = '?*::INSTR' ) : return dict ( ( resource , self . resource_info ( resource ) ) for resource in self . list_resources ( query ) )
Returns a dictionary mapping resource names to resource extended information of all connected devices matching query .
47
17
227,924
def open_bare_resource ( self , resource_name , access_mode = constants . AccessModes . no_lock , open_timeout = constants . VI_TMO_IMMEDIATE ) : return self . visalib . open ( self . session , resource_name , access_mode , open_timeout )
Open the specified resource without wrapping into a class
69
9
227,925
def open_resource ( self , resource_name , access_mode = constants . AccessModes . no_lock , open_timeout = constants . VI_TMO_IMMEDIATE , resource_pyclass = None , * * kwargs ) : if resource_pyclass is None : info = self . resource_info ( resource_name , extended = True ) try : resource_pyclass = self . _resource_classes [ ( info . interface_type , info . resource_class ) ] except KeyError : resource_pyclass = self . _resource_classes [ ( constants . InterfaceType . unknown , '' ) ] logger . warning ( 'There is no class defined for %r. Using Resource' , ( info . interface_type , info . resource_class ) ) res = resource_pyclass ( self , resource_name ) for key in kwargs . keys ( ) : try : getattr ( res , key ) present = True except AttributeError : present = False except errors . InvalidSession : present = True if not present : raise ValueError ( '%r is not a valid attribute for type %s' % ( key , res . __class__ . __name__ ) ) res . open ( access_mode , open_timeout ) self . _created_resources . add ( res ) for key , value in kwargs . items ( ) : setattr ( res , key , value ) return res
Return an instrument for the resource name .
302
8
227,926
def register_subclass ( cls ) : key = cls . interface_type , cls . resource_class if key in _SUBCLASSES : raise ValueError ( 'Class already registered for %s and %s' % key ) _SUBCLASSES [ ( cls . interface_type , cls . resource_class ) ] = cls _INTERFACE_TYPES . add ( cls . interface_type ) _RESOURCE_CLASSES [ cls . interface_type ] . add ( cls . resource_class ) if cls . is_rc_optional : if cls . interface_type in _DEFAULT_RC : raise ValueError ( 'Default already specified for %s' % cls . interface_type ) _DEFAULT_RC [ cls . interface_type ] = cls . resource_class return cls
Register a subclass for a given interface type and resource class .
187
12
227,927
def bad_syntax ( cls , syntax , resource_name , ex = None ) : if ex : msg = "The syntax is '%s' (%s)." % ( syntax , ex ) else : msg = "The syntax is '%s'." % syntax msg = "Could not parse '%s'. %s" % ( resource_name , msg ) return cls ( msg )
Exception used when the resource name cannot be parsed .
83
10
227,928
def rc_notfound ( cls , interface_type , resource_name = None ) : msg = "Resource class for %s not provided and default not found." % interface_type if resource_name : msg = "Could not parse '%s'. %s" % ( resource_name , msg ) return cls ( msg )
Exception used when no resource class is provided and no default is found .
71
14
227,929
def from_string ( cls , resource_name ) : # TODO Remote VISA uname = resource_name . upper ( ) for interface_type in _INTERFACE_TYPES : # Loop through all known interface types until we found one # that matches the beginning of the resource name if not uname . startswith ( interface_type ) : continue if len ( resource_name ) == len ( interface_type ) : parts = ( ) else : parts = resource_name [ len ( interface_type ) : ] . split ( '::' ) # Try to match the last part of the resource name to # one of the known resource classes for the given interface type. # If not possible, use the default resource class # for the given interface type. if parts and parts [ - 1 ] in _RESOURCE_CLASSES [ interface_type ] : parts , resource_class = parts [ : - 1 ] , parts [ - 1 ] else : try : resource_class = _DEFAULT_RC [ interface_type ] except KeyError : raise InvalidResourceName . rc_notfound ( interface_type , resource_name ) # Look for the subclass try : subclass = _SUBCLASSES [ ( interface_type , resource_class ) ] except KeyError : raise InvalidResourceName . subclass_notfound ( ( interface_type , resource_class ) , resource_name ) # And create the object try : rn = subclass . from_parts ( * parts ) rn . user = resource_name return rn except ValueError as ex : raise InvalidResourceName . bad_syntax ( subclass . _visa_syntax , resource_name , ex ) raise InvalidResourceName ( 'Could not parse %s: unknown interface type' % resource_name )
Parse a resource name and return a ResourceName
376
10
227,930
def set_user_handle_type ( library , user_handle ) : # Actually, it's not necessary to change ViHndlr *globally*. However, # I don't want to break symmetry too much with all the other VPP43 # routines. global ViHndlr if user_handle is None : user_handle_p = c_void_p else : user_handle_p = POINTER ( type ( user_handle ) ) ViHndlr = FUNCTYPE ( ViStatus , ViSession , ViEventType , ViEvent , user_handle_p ) library . viInstallHandler . argtypes = [ ViSession , ViEventType , ViHndlr , user_handle_p ] library . viUninstallHandler . argtypes = [ ViSession , ViEventType , ViHndlr , user_handle_p ]
Set the type of the user handle to install and uninstall handler signature .
183
14
227,931
def set_signature ( library , function_name , argtypes , restype , errcheck ) : func = getattr ( library , function_name ) func . argtypes = argtypes if restype is not None : func . restype = restype if errcheck is not None : func . errcheck = errcheck
Set the signature of single function in a library .
68
10
227,932
def assert_interrupt_signal ( library , session , mode , status_id ) : return library . viAssertIntrSignal ( session , mode , status_id )
Asserts the specified interrupt or signal .
39
9
227,933
def discard_events ( library , session , event_type , mechanism ) : return library . viDiscardEvents ( session , event_type , mechanism )
Discards event occurrences for specified event types and mechanisms in a session .
32
14
227,934
def enable_event ( library , session , event_type , mechanism , context = None ) : if context is None : context = constants . VI_NULL elif context != constants . VI_NULL : warnings . warn ( 'In enable_event, context will be set VI_NULL.' ) context = constants . VI_NULL # according to spec VPP-4.3, section 3.7.3.1 return library . viEnableEvent ( session , event_type , mechanism , context )
Enable event occurrences for specified event types and mechanisms in a session .
104
13
227,935
def find_resources ( library , session , query ) : find_list = ViFindList ( ) return_counter = ViUInt32 ( ) instrument_description = create_string_buffer ( constants . VI_FIND_BUFLEN ) # [ViSession, ViString, ViPFindList, ViPUInt32, ViAChar] # ViString converts from (str, unicode, bytes) to bytes ret = library . viFindRsrc ( session , query , byref ( find_list ) , byref ( return_counter ) , instrument_description ) return find_list , return_counter . value , buffer_to_text ( instrument_description ) , ret
Queries a VISA system to locate the resources associated with a specified interface .
145
16
227,936
def gpib_command ( library , session , data ) : return_count = ViUInt32 ( ) # [ViSession, ViBuf, ViUInt32, ViPUInt32] ret = library . viGpibCommand ( session , data , len ( data ) , byref ( return_count ) ) return return_count . value , ret
Write GPIB command bytes on the bus .
77
9
227,937
def in_8 ( library , session , space , offset , extended = False ) : value_8 = ViUInt8 ( ) if extended : ret = library . viIn8Ex ( session , space , offset , byref ( value_8 ) ) else : ret = library . viIn8 ( session , space , offset , byref ( value_8 ) ) return value_8 . value , ret
Reads in an 8 - bit value from the specified memory space and offset .
86
16
227,938
def in_16 ( library , session , space , offset , extended = False ) : value_16 = ViUInt16 ( ) if extended : ret = library . viIn16Ex ( session , space , offset , byref ( value_16 ) ) else : ret = library . viIn16 ( session , space , offset , byref ( value_16 ) ) return value_16 . value , ret
Reads in an 16 - bit value from the specified memory space and offset .
86
16
227,939
def in_32 ( library , session , space , offset , extended = False ) : value_32 = ViUInt32 ( ) if extended : ret = library . viIn32Ex ( session , space , offset , byref ( value_32 ) ) else : ret = library . viIn32 ( session , space , offset , byref ( value_32 ) ) return value_32 . value , ret
Reads in an 32 - bit value from the specified memory space and offset .
86
16
227,940
def in_64 ( library , session , space , offset , extended = False ) : value_64 = ViUInt64 ( ) if extended : ret = library . viIn64Ex ( session , space , offset , byref ( value_64 ) ) else : ret = library . viIn64 ( session , space , offset , byref ( value_64 ) ) return value_64 . value , ret
Reads in an 64 - bit value from the specified memory space and offset .
86
16
227,941
def map_trigger ( library , session , trigger_source , trigger_destination , mode ) : return library . viMapTrigger ( session , trigger_source , trigger_destination , mode )
Map the specified trigger source line to the specified destination line .
41
12
227,942
def memory_allocation ( library , session , size , extended = False ) : offset = ViBusAddress ( ) if extended : ret = library . viMemAllocEx ( session , size , byref ( offset ) ) else : ret = library . viMemAlloc ( session , size , byref ( offset ) ) return offset , ret
Allocates memory from a resource s memory region .
72
11
227,943
def move_asynchronously ( library , session , source_space , source_offset , source_width , destination_space , destination_offset , destination_width , length ) : job_id = ViJobId ( ) ret = library . viMoveAsync ( session , source_space , source_offset , source_width , destination_space , destination_offset , destination_width , length , byref ( job_id ) ) return job_id , ret
Moves a block of data asynchronously .
97
10
227,944
def move_in_8 ( library , session , space , offset , length , extended = False ) : buffer_8 = ( ViUInt8 * length ) ( ) if extended : ret = library . viMoveIn8Ex ( session , space , offset , length , buffer_8 ) else : ret = library . viMoveIn8 ( session , space , offset , length , buffer_8 ) return list ( buffer_8 ) , ret
Moves an 8 - bit block of data from the specified address space and offset to local memory .
93
20
227,945
def move_in_16 ( library , session , space , offset , length , extended = False ) : buffer_16 = ( ViUInt16 * length ) ( ) if extended : ret = library . viMoveIn16Ex ( session , space , offset , length , buffer_16 ) else : ret = library . viMoveIn16 ( session , space , offset , length , buffer_16 ) return list ( buffer_16 ) , ret
Moves an 16 - bit block of data from the specified address space and offset to local memory .
93
20
227,946
def move_in_32 ( library , session , space , offset , length , extended = False ) : buffer_32 = ( ViUInt32 * length ) ( ) if extended : ret = library . viMoveIn32Ex ( session , space , offset , length , buffer_32 ) else : ret = library . viMoveIn32 ( session , space , offset , length , buffer_32 ) return list ( buffer_32 ) , ret
Moves an 32 - bit block of data from the specified address space and offset to local memory .
93
20
227,947
def move_in_64 ( library , session , space , offset , length , extended = False ) : buffer_64 = ( ViUInt64 * length ) ( ) if extended : ret = library . viMoveIn64Ex ( session , space , offset , length , buffer_64 ) else : ret = library . viMoveIn64 ( session , space , offset , length , buffer_64 ) return list ( buffer_64 ) , ret
Moves an 64 - bit block of data from the specified address space and offset to local memory .
93
20
227,948
def move_out_16 ( library , session , space , offset , length , data , extended = False ) : converted_buffer = ( ViUInt16 * length ) ( * tuple ( data ) ) if extended : return library . viMoveOut16Ex ( session , space , offset , length , converted_buffer ) else : return library . viMoveOut16 ( session , space , offset , length , converted_buffer )
Moves an 16 - bit block of data from local memory to the specified address space and offset .
89
20
227,949
def move_out_32 ( library , session , space , offset , length , data , extended = False ) : converted_buffer = ( ViUInt32 * length ) ( * tuple ( data ) ) if extended : return library . viMoveOut32Ex ( session , space , offset , length , converted_buffer ) else : return library . viMoveOut32 ( session , space , offset , length , converted_buffer )
Moves an 32 - bit block of data from local memory to the specified address space and offset .
89
20
227,950
def move_out_64 ( library , session , space , offset , length , data , extended = False ) : converted_buffer = ( ViUInt64 * length ) ( * tuple ( data ) ) if extended : return library . viMoveOut64Ex ( session , space , offset , length , converted_buffer ) else : return library . viMoveOut64 ( session , space , offset , length , converted_buffer )
Moves an 64 - bit block of data from local memory to the specified address space and offset .
89
20
227,951
def open_default_resource_manager ( library ) : session = ViSession ( ) ret = library . viOpenDefaultRM ( byref ( session ) ) return session . value , ret
This function returns a session to the Default Resource Manager resource .
39
12
227,952
def out_8 ( library , session , space , offset , data , extended = False ) : if extended : return library . viOut8Ex ( session , space , offset , data ) else : return library . viOut8 ( session , space , offset , data )
Write in an 8 - bit value from the specified memory space and offset .
56
15
227,953
def out_16 ( library , session , space , offset , data , extended = False ) : if extended : return library . viOut16Ex ( session , space , offset , data , extended = False ) else : return library . viOut16 ( session , space , offset , data , extended = False )
Write in an 16 - bit value from the specified memory space and offset .
64
15
227,954
def out_32 ( library , session , space , offset , data , extended = False ) : if extended : return library . viOut32Ex ( session , space , offset , data ) else : return library . viOut32 ( session , space , offset , data )
Write in an 32 - bit value from the specified memory space and offset .
56
15
227,955
def out_64 ( library , session , space , offset , data , extended = False ) : if extended : return library . viOut64Ex ( session , space , offset , data ) else : return library . viOut64 ( session , space , offset , data )
Write in an 64 - bit value from the specified memory space and offset .
56
15
227,956
def parse_resource ( library , session , resource_name ) : interface_type = ViUInt16 ( ) interface_board_number = ViUInt16 ( ) # [ViSession, ViRsrc, ViPUInt16, ViPUInt16] # ViRsrc converts from (str, unicode, bytes) to bytes ret = library . viParseRsrc ( session , resource_name , byref ( interface_type ) , byref ( interface_board_number ) ) return ResourceInfo ( constants . InterfaceType ( interface_type . value ) , interface_board_number . value , None , None , None ) , ret
Parse a resource string to get the interface information .
137
11
227,957
def peek ( library , session , address , width ) : if width == 8 : return peek_8 ( library , session , address ) elif width == 16 : return peek_16 ( library , session , address ) elif width == 32 : return peek_32 ( library , session , address ) elif width == 64 : return peek_64 ( library , session , address ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16, 32 or 64' % width )
Read an 8 16 or 32 - bit value from the specified address .
106
14
227,958
def peek_8 ( library , session , address ) : value_8 = ViUInt8 ( ) ret = library . viPeek8 ( session , address , byref ( value_8 ) ) return value_8 . value , ret
Read an 8 - bit value from the specified address .
51
11
227,959
def peek_16 ( library , session , address ) : value_16 = ViUInt16 ( ) ret = library . viPeek16 ( session , address , byref ( value_16 ) ) return value_16 . value , ret
Read an 16 - bit value from the specified address .
51
11
227,960
def peek_32 ( library , session , address ) : value_32 = ViUInt32 ( ) ret = library . viPeek32 ( session , address , byref ( value_32 ) ) return value_32 . value , ret
Read an 32 - bit value from the specified address .
51
11
227,961
def peek_64 ( library , session , address ) : value_64 = ViUInt64 ( ) ret = library . viPeek64 ( session , address , byref ( value_64 ) ) return value_64 . value , ret
Read an 64 - bit value from the specified address .
51
11
227,962
def poke ( library , session , address , width , data ) : if width == 8 : return poke_8 ( library , session , address , data ) elif width == 16 : return poke_16 ( library , session , address , data ) elif width == 32 : return poke_32 ( library , session , address , data ) raise ValueError ( '%s is not a valid size. Valid values are 8, 16 or 32' % width )
Writes an 8 16 or 32 - bit value from the specified address .
95
15
227,963
def poke_8 ( library , session , address , data ) : return library . viPoke8 ( session , address , data )
Write an 8 - bit value from the specified address .
28
11
227,964
def poke_16 ( library , session , address , data ) : return library . viPoke16 ( session , address , data )
Write an 16 - bit value from the specified address .
28
11
227,965
def poke_32 ( library , session , address , data ) : return library . viPoke32 ( session , address , data )
Write an 32 - bit value from the specified address .
28
11
227,966
def poke_64 ( library , session , address , data ) : return library . viPoke64 ( session , address , data )
Write an 64 - bit value from the specified address .
28
11
227,967
def read_asynchronously ( library , session , count ) : buffer = create_string_buffer ( count ) job_id = ViJobId ( ) ret = library . viReadAsync ( session , buffer , count , byref ( job_id ) ) return buffer , job_id , ret
Reads data from device or interface asynchronously .
63
11
227,968
def read_stb ( library , session ) : status = ViUInt16 ( ) ret = library . viReadSTB ( session , byref ( status ) ) return status . value , ret
Reads a status byte of the service request .
42
10
227,969
def read_to_file ( library , session , filename , count ) : return_count = ViUInt32 ( ) ret = library . viReadToFile ( session , filename , count , return_count ) return return_count , ret
Read data synchronously and store the transferred data in a file .
51
13
227,970
def status_description ( library , session , status ) : description = create_string_buffer ( 256 ) ret = library . viStatusDesc ( session , status , description ) return buffer_to_text ( description ) , ret
Returns a user - readable description of the status code passed to the operation .
47
15
227,971
def terminate ( library , session , degree , job_id ) : return library . viTerminate ( session , degree , job_id )
Requests a VISA session to terminate normal execution of an operation .
29
14
227,972
def unmap_trigger ( library , session , trigger_source , trigger_destination ) : return library . viUnmapTrigger ( session , trigger_source , trigger_destination )
Undo a previous map from the specified trigger source line to the specified destination line .
39
17
227,973
def usb_control_in ( library , session , request_type_bitmap_field , request_id , request_value , index , length = 0 ) : buffer = create_string_buffer ( length ) return_count = ViUInt16 ( ) ret = library . viUsbControlIn ( session , request_type_bitmap_field , request_id , request_value , index , length , buffer , byref ( return_count ) ) return buffer . raw [ : return_count . value ] , ret
Performs a USB control pipe transfer from the device .
112
11
227,974
def usb_control_out ( library , session , request_type_bitmap_field , request_id , request_value , index , data = "" ) : length = len ( data ) return library . viUsbControlOut ( session , request_type_bitmap_field , request_id , request_value , index , length , data )
Performs a USB control pipe transfer to the device .
75
11
227,975
def wait_on_event ( library , session , in_event_type , timeout ) : out_event_type = ViEventType ( ) out_context = ViEvent ( ) ret = library . viWaitOnEvent ( session , in_event_type , timeout , byref ( out_event_type ) , byref ( out_context ) ) return out_event_type . value , out_context , ret
Waits for an occurrence of the specified event for a given session .
90
14
227,976
def write_asynchronously ( library , session , data ) : job_id = ViJobId ( ) # [ViSession, ViBuf, ViUInt32, ViPJobId] ret = library . viWriteAsync ( session , data , len ( data ) , byref ( job_id ) ) return job_id , ret
Writes data to device or interface asynchronously .
73
11
227,977
def write_from_file ( library , session , filename , count ) : return_count = ViUInt32 ( ) ret = library . viWriteFromFile ( session , filename , count , return_count ) return return_count , ret
Take data from a file and write it out synchronously .
51
12
227,978
def in_resource ( cls , session_type ) : if cls . resources is AllSessionTypes : return True return session_type in cls . resources
Returns True if the attribute is part of a given session type .
34
13
227,979
def do_list ( self , args ) : try : resources = self . resource_manager . list_resources_info ( ) except Exception as e : print ( e ) else : self . resources = [ ] for ndx , ( resource_name , value ) in enumerate ( resources . items ( ) ) : if not args : print ( '({0:2d}) {1}' . format ( ndx , resource_name ) ) if value . alias : print ( ' alias: {}' . format ( value . alias ) ) self . resources . append ( ( resource_name , value . alias or None ) )
List all connected resources .
132
5
227,980
def do_close ( self , args ) : if not self . current : print ( 'There are no resources in use. Use the command "open".' ) return try : self . current . close ( ) except Exception as e : print ( e ) else : print ( 'The resource has been closed.' ) self . current = None self . prompt = self . default_prompt
Close resource in use .
80
5
227,981
def do_read ( self , args ) : if not self . current : print ( 'There are no resources in use. Use the command "open".' ) return try : print ( self . current . read ( ) ) except Exception as e : print ( e )
Receive from the resource in use .
56
8
227,982
def do_attr ( self , args ) : if not self . current : print ( 'There are no resources in use. Use the command "open".' ) return args = args . strip ( ) if not args : self . print_attribute_list ( ) return args = args . split ( ' ' ) if len ( args ) > 2 : print ( 'Invalid syntax, use `attr <name>` to get; or `attr <name> <value>` to set' ) elif len ( args ) == 1 : # Get attr_name = args [ 0 ] if attr_name . startswith ( 'VI_' ) : try : print ( self . current . get_visa_attribute ( getattr ( constants , attr_name ) ) ) except Exception as e : print ( e ) else : try : print ( getattr ( self . current , attr_name ) ) except Exception as e : print ( e ) else : attr_name , attr_state = args [ 0 ] , args [ 1 ] if attr_name . startswith ( 'VI_' ) : try : attributeId = getattr ( constants , attr_name ) attr = attributes . AttributesByID [ attributeId ] datatype = attr . visa_type retcode = None if datatype == 'ViBoolean' : if attr_state == 'True' : attr_state = True elif attr_state == 'False' : attr_state = False else : retcode = constants . StatusCode . error_nonsupported_attribute_state elif datatype in [ 'ViUInt8' , 'ViUInt16' , 'ViUInt32' , 'ViInt8' , 'ViInt16' , 'ViInt32' ] : try : attr_state = int ( attr_state ) except ValueError : retcode = constants . StatusCode . error_nonsupported_attribute_state if not retcode : retcode = self . current . set_visa_attribute ( attributeId , attr_state ) if retcode : print ( 'Error {}' . format ( str ( retcode ) ) ) else : print ( 'Done' ) except Exception as e : print ( e ) else : print ( 'Setting Resource Attributes by python name is not yet supported.' ) return try : print ( getattr ( self . current , attr_name ) ) print ( 'Done' ) except Exception as e : print ( e )
Get or set the state for a visa attribute .
544
10
227,983
def do_exit ( self , arg ) : if self . current : self . current . close ( ) self . resource_manager . close ( ) del self . resource_manager return True
Exit the shell session .
39
5
227,984
def resource_info ( self ) : return self . visalib . parse_resource_extended ( self . _resource_manager . session , self . resource_name )
Get the extended information of this resource .
37
8
227,985
def interface_type ( self ) : return self . visalib . parse_resource ( self . _resource_manager . session , self . resource_name ) [ 0 ] . interface_type
The interface type of the resource as a number .
41
10
227,986
def close ( self ) : try : logger . debug ( '%s - closing' , self . _resource_name , extra = self . _logging_extra ) self . before_close ( ) self . visalib . close ( self . session ) logger . debug ( '%s - is closed' , self . _resource_name , extra = self . _logging_extra ) self . session = None except errors . InvalidSession : pass
Closes the VISA session and marks the handle as invalid .
96
13
227,987
def install_handler ( self , event_type , handler , user_handle = None ) : return self . visalib . install_visa_handler ( self . session , event_type , handler , user_handle )
Installs handlers for event callbacks in this resource .
48
11
227,988
def uninstall_handler ( self , event_type , handler , user_handle = None ) : self . visalib . uninstall_visa_handler ( self . session , event_type , handler , user_handle )
Uninstalls handlers for events in this resource .
47
10
227,989
def discard_events ( self , event_type , mechanism ) : self . visalib . discard_events ( self . session , event_type , mechanism )
Discards event occurrences for specified event types and mechanisms in this resource .
34
14
227,990
def enable_event ( self , event_type , mechanism , context = None ) : self . visalib . enable_event ( self . session , event_type , mechanism , context )
Enable event occurrences for specified event types and mechanisms in this resource .
40
13
227,991
def wait_on_event ( self , in_event_type , timeout , capture_timeout = False ) : try : event_type , context , ret = self . visalib . wait_on_event ( self . session , in_event_type , timeout ) except errors . VisaIOError as exc : if capture_timeout and exc . error_code == constants . StatusCode . error_timeout : return WaitResponse ( in_event_type , None , exc . error_code , self . visalib , timed_out = True ) raise return WaitResponse ( event_type , context , ret , self . visalib )
Waits for an occurrence of the specified event in this resource .
136
13
227,992
def lock ( self , timeout = 'default' , requested_key = None ) : timeout = self . timeout if timeout == 'default' else timeout timeout = self . _cleanup_timeout ( timeout ) return self . visalib . lock ( self . session , constants . AccessModes . shared_lock , timeout , requested_key ) [ 0 ]
Establish a shared lock to the resource .
75
9
227,993
def lock_excl ( self , timeout = 'default' ) : timeout = self . timeout if timeout == 'default' else timeout timeout = self . _cleanup_timeout ( timeout ) self . visalib . lock ( self . session , constants . AccessModes . exclusive_lock , timeout , None )
Establish an exclusive lock to the resource .
66
9
227,994
def lock_context ( self , timeout = 'default' , requested_key = 'exclusive' ) : if requested_key == 'exclusive' : self . lock_excl ( timeout ) access_key = None else : access_key = self . lock ( timeout , requested_key ) try : yield access_key finally : self . unlock ( )
A context that locks
74
4
227,995
def del_row ( self , row_index ) : if row_index > len ( self . _rows ) - 1 : raise Exception ( "Cant delete row at index %d, table only has %d rows!" % ( row_index , len ( self . _rows ) ) ) del self . _rows [ row_index ]
Delete a row to the table
72
6
227,996
def get_html_string ( self , * * kwargs ) : options = self . _get_options ( kwargs ) if options [ "format" ] : string = self . _get_formatted_html_string ( options ) else : string = self . _get_simple_html_string ( options ) return string
Return string representation of HTML formatted version of table in current state .
72
13
227,997
def make_fields_unique ( self , fields ) : for i in range ( 0 , len ( fields ) ) : for j in range ( i + 1 , len ( fields ) ) : if fields [ i ] == fields [ j ] : fields [ j ] += "'"
iterates over the row and make each field unique
58
10
227,998
def meta_request ( func ) : def inner ( self , resource , * args , * * kwargs ) : serialize_response = kwargs . pop ( 'serialize' , True ) try : resp = func ( self , resource , * args , * * kwargs ) except ApiException as e : raise api_exception ( e ) if serialize_response : return serialize ( resource , resp ) return resp return inner
Handles parsing response structure and translating API Exceptions
95
10
227,999
def watch ( self , resource , namespace = None , name = None , label_selector = None , field_selector = None , resource_version = None , timeout = None ) : watcher = watch . Watch ( ) for event in watcher . stream ( resource . get , namespace = namespace , name = name , field_selector = field_selector , label_selector = label_selector , resource_version = resource_version , serialize = False , timeout_seconds = timeout ) : event [ 'object' ] = ResourceInstance ( resource , event [ 'object' ] ) yield event
Stream events for a resource from the Kubernetes API
129
12