idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
244,500 | def clone ( self ) : builder = LintConfigBuilder ( ) builder . _config_blueprint = copy . deepcopy ( self . _config_blueprint ) builder . _config_path = self . _config_path return builder | Creates an exact copy of a LintConfigBuilder . |
244,501 | def _git ( * command_parts , ** kwargs ) : git_kwargs = { '_tty_out' : False } git_kwargs . update ( kwargs ) try : result = sh . git ( * command_parts , ** git_kwargs ) if hasattr ( result , 'exit_code' ) and result . exit_code > 0 : return result return ustr ( result ) except CommandNotFound : raise GitNotInstalledEr... | Convenience function for running git commands . Automatically deals with exceptions and unicode . |
244,502 | def git_commentchar ( ) : commentchar = _git ( "config" , "--get" , "core.commentchar" , _ok_code = [ 1 ] ) if hasattr ( commentchar , 'exit_code' ) and commentchar . exit_code == 1 : commentchar = "#" return ustr ( commentchar ) . replace ( u"\n" , u"" ) | Shortcut for retrieving comment char from git config |
244,503 | def from_full_message ( commit_msg_str ) : all_lines = commit_msg_str . splitlines ( ) try : cutline_index = all_lines . index ( GitCommitMessage . CUTLINE ) except ValueError : cutline_index = None lines = [ line for line in all_lines [ : cutline_index ] if not line . startswith ( GitCommitMessage . COMMENT_CHAR ) ] f... | Parses a full git commit message by parsing a given string into the different parts of a commit message |
244,504 | def should_ignore_rule ( self , rule ) : return rule . id in self . config . ignore or rule . name in self . config . ignore | Determines whether a rule should be ignored based on the general list of commits to ignore |
244,505 | def _apply_line_rules ( lines , commit , rules , line_nr_start ) : all_violations = [ ] line_nr = line_nr_start for line in lines : for rule in rules : violations = rule . validate ( line , commit ) if violations : for violation in violations : violation . line_nr = line_nr all_violations . append ( violation ) line_nr... | Iterates over the lines in a given list of lines and validates a given list of rules against each line |
244,506 | def _apply_commit_rules ( rules , commit ) : all_violations = [ ] for rule in rules : violations = rule . validate ( commit ) if violations : all_violations . extend ( violations ) return all_violations | Applies a set of rules against a given commit and gitcontext |
244,507 | def lint ( self , commit ) : LOG . debug ( "Linting commit %s" , commit . sha or "[SHA UNKNOWN]" ) LOG . debug ( "Commit Object\n" + ustr ( commit ) ) for rule in self . configuration_rules : rule . apply ( self . config , commit ) ignore_commit_types = [ "merge" , "squash" , "fixup" ] for commit_type in ignore_commit_... | Lint the last commit in a given git context by applying all ignore title body and commit rules . |
244,508 | def print_violations ( self , violations ) : for v in violations : line_nr = v . line_nr if v . line_nr else "-" self . display . e ( u"{0}: {1}" . format ( line_nr , v . rule_id ) , exact = True ) self . display . ee ( u"{0}: {1} {2}" . format ( line_nr , v . rule_id , v . message ) , exact = True ) if v . content : s... | Print a given set of violations to the standard error output |
244,509 | def _output ( self , message , verbosity , exact , stream ) : if exact : if self . config . verbosity == verbosity : stream . write ( message + "\n" ) else : if self . config . verbosity >= verbosity : stream . write ( message + "\n" ) | Output a message if the config s verbosity is > = to the given verbosity . If exact == True the message will only be outputted if the given verbosity exactly matches the config s verbosity . |
244,510 | def setup_logging ( ) : root_log = logging . getLogger ( "gitlint" ) root_log . propagate = False handler = logging . StreamHandler ( ) formatter = logging . Formatter ( LOG_FORMAT ) handler . setFormatter ( formatter ) root_log . addHandler ( handler ) root_log . setLevel ( logging . ERROR ) | Setup gitlint logging |
244,511 | def build_config ( ctx , target , config_path , c , extra_path , ignore , verbose , silent , debug ) : config_builder = LintConfigBuilder ( ) try : if config_path : config_builder . set_from_config_file ( config_path ) elif os . path . exists ( DEFAULT_CONFIG_FILE ) : config_builder . set_from_config_file ( DEFAULT_CON... | Creates a LintConfig object based on a set of commandline parameters . |
244,512 | def get_stdin_data ( ) : mode = os . fstat ( sys . stdin . fileno ( ) ) . st_mode stdin_is_pipe_or_file = stat . S_ISFIFO ( mode ) or stat . S_ISREG ( mode ) if stdin_is_pipe_or_file : input_data = sys . stdin . read ( ) if input_data : return ustr ( input_data ) return False | Helper function that returns data send to stdin or False if nothing is send |
244,513 | def cli ( ctx , target , config , c , commits , extra_path , ignore , msg_filename , verbose , silent , debug , ) : try : if debug : logging . getLogger ( "gitlint" ) . setLevel ( logging . DEBUG ) log_system_info ( ) config , config_builder = build_config ( ctx , target , config , c , extra_path , ignore , verbose , s... | Git lint tool checks your git commit messages for styling issues |
244,514 | def install_hook ( ctx ) : try : lint_config = ctx . obj [ 0 ] hooks . GitHookInstaller . install_commit_msg_hook ( lint_config ) hook_path = hooks . GitHookInstaller . commit_msg_hook_path ( lint_config ) click . echo ( u"Successfully installed gitlint commit-msg hook in {0}" . format ( hook_path ) ) ctx . exit ( 0 ) ... | Install gitlint as a git commit - msg hook . |
244,515 | def uninstall_hook ( ctx ) : try : lint_config = ctx . obj [ 0 ] hooks . GitHookInstaller . uninstall_commit_msg_hook ( lint_config ) hook_path = hooks . GitHookInstaller . commit_msg_hook_path ( lint_config ) click . echo ( u"Successfully uninstalled gitlint commit-msg hook from {0}" . format ( hook_path ) ) ctx . exi... | Uninstall gitlint commit - msg hook . |
244,516 | def generate_config ( ctx ) : path = click . prompt ( 'Please specify a location for the sample gitlint config file' , default = DEFAULT_CONFIG_FILE ) path = os . path . abspath ( path ) dir_name = os . path . dirname ( path ) if not os . path . exists ( dir_name ) : click . echo ( u"Error: Directory '{0}' does not exi... | Generates a sample gitlint config file . |
244,517 | def _assert_git_repo ( target ) : hooks_dir = os . path . abspath ( os . path . join ( target , HOOKS_DIR_PATH ) ) if not os . path . isdir ( hooks_dir ) : raise GitHookInstallerError ( u"{0} is not a git repository." . format ( target ) ) | Asserts that a given target directory is a git repository |
244,518 | def get_job_url ( config , hub , group , project ) : if ( ( config is not None ) and ( 'hub' in config ) and ( hub is None ) ) : hub = config [ "hub" ] if ( ( config is not None ) and ( 'group' in config ) and ( group is None ) ) : group = config [ "group" ] if ( ( config is not None ) and ( 'project' in config ) and (... | Util method to get job url |
244,519 | def get_backend_stats_url ( config , hub , backend_type ) : if ( ( config is not None ) and ( 'hub' in config ) and ( hub is None ) ) : hub = config [ "hub" ] if ( hub is not None ) : return '/Network/{}/devices/{}' . format ( hub , backend_type ) return '/Backends/{}' . format ( backend_type ) | Util method to get backend stats url |
244,520 | def get_backend_url ( config , hub , group , project ) : if ( ( config is not None ) and ( 'hub' in config ) and ( hub is None ) ) : hub = config [ "hub" ] if ( ( config is not None ) and ( 'group' in config ) and ( group is None ) ) : group = config [ "group" ] if ( ( config is not None ) and ( 'project' in config ) a... | Util method to get backend url |
244,521 | def obtain_token ( self , config = None ) : client_application = CLIENT_APPLICATION if self . config and ( "client_application" in self . config ) : client_application += ':' + self . config [ "client_application" ] headers = { 'x-qx-client-application' : client_application } if self . token_unique : try : response = r... | Obtain the token to access to QX Platform . |
244,522 | def check_token ( self , respond ) : if respond . status_code == 401 : self . credential . obtain_token ( config = self . config ) return False return True | Check is the user s token is valid |
244,523 | def post ( self , path , params = '' , data = None ) : self . result = None data = data or { } headers = { 'Content-Type' : 'application/json' , 'x-qx-client-application' : self . client_application } url = str ( self . credential . config [ 'url' ] + path + '?access_token=' + self . credential . get_token ( ) + params... | POST Method Wrapper of the REST API |
244,524 | def _parse_response ( self , respond ) : mobj = self . _max_qubit_error_re . match ( respond . text ) if mobj : raise RegisterSizeError ( 'device register size must be <= {}' . format ( mobj . group ( 1 ) ) ) return True | parse text of response for HTTP errors |
244,525 | def _check_backend ( self , backend , endpoint ) : original_backend = backend backend = backend . lower ( ) if endpoint == 'experiment' : if backend in self . __names_backend_ibmqxv2 : return 'real' elif backend in self . __names_backend_ibmqxv3 : return 'ibmqx3' elif backend in self . __names_backend_simulator : retur... | Check if the name of a backend is valid to run in QX Platform |
244,526 | def get_execution ( self , id_execution , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) execution = self... | Get a execution by its id |
244,527 | def get_result_from_execution ( self , id_execution , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) exec... | Get the result of a execution by the execution id |
244,528 | def get_code ( self , id_code , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) code = self . req . get ( ... | Get a code by its id |
244,529 | def get_image_code ( self , id_code , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) return self . req . ... | Get the image of a code by its id |
244,530 | def get_last_codes ( self , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) last = '/users/' + self . req ... | Get the last codes of the user |
244,531 | def run_job ( self , job , backend = 'simulator' , shots = 1 , max_credits = None , seed = None , hub = None , group = None , project = None , hpc = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id (... | Execute a job |
244,532 | def get_job ( self , id_job , hub = None , group = None , project = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : respond = { } respond [ "status"... | Get the information about a job by its id |
244,533 | def get_jobs ( self , limit = 10 , skip = 0 , backend = None , only_completed = False , filter = None , hub = None , group = None , project = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_i... | Get the information about the user jobs |
244,534 | def get_status_job ( self , id_job , hub = None , group = None , project = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : respond = { } respond [ "... | Get the status about a job by its id |
244,535 | def cancel_job ( self , id_job , hub = None , group = None , project = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : respond = { } respond [ "stat... | Cancel the information about a job by its id |
244,536 | def backend_status ( self , backend = 'ibmqx4' , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) backend_type = self . _check_backend ( backend , 'status' ) if not backend_type : raise BadBacke... | Get the status of a chip |
244,537 | def backend_calibration ( self , backend = 'ibmqx4' , hub = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials in... | Get the calibration of a real chip |
244,538 | def available_backends ( self , hub = None , group = None , project = None , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'cred... | Get the backends available to use in the QX Platform |
244,539 | def available_backend_simulators ( self , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) else : ret = sel... | Get the backend simulators available to use in the QX Platform |
244,540 | def get_my_credits ( self , access_token = None , user_id = None ) : if access_token : self . req . credential . set_token ( access_token ) if user_id : self . req . credential . set_user_id ( user_id ) if not self . check_credentials ( ) : raise CredentialsError ( 'credentials invalid' ) else : user_data_url = '/users... | Get the credits by user to use in the QX Platform |
244,541 | def trace ( self , predicate ) : self . _handler = predicate if self . threading_support is None or self . threading_support : self . _threading_previous = getattr ( threading , '_trace_hook' , None ) threading . settrace ( self ) self . _previous = sys . gettrace ( ) sys . settrace ( self ) return self | Starts tracing with the given callable . |
244,542 | def And ( * predicates , ** kwargs ) : if kwargs : predicates += Query ( ** kwargs ) , return _flatten ( _And , * predicates ) | And predicate . Returns False at the first sub - predicate that returns False . |
244,543 | def Or ( * predicates , ** kwargs ) : if kwargs : predicates += tuple ( Query ( ** { k : v } ) for k , v in kwargs . items ( ) ) return _flatten ( _Or , * predicates ) | Or predicate . Returns True at the first sub - predicate that returns True . |
244,544 | def wrap ( function_to_trace = None , ** trace_options ) : def tracing_decorator ( func ) : @ functools . wraps ( func ) def tracing_wrapper ( * args , ** kwargs ) : predicates = [ ] local = trace_options . pop ( 'local' , False ) if local : predicates . append ( Q ( depth_lt = 2 ) ) predicates . append ( ~ When ( Q ( ... | Functions decorated with this will be traced . |
244,545 | def threadid ( self ) : current = self . thread . ident main = get_main_thread ( ) if main is None : return current else : return current if current != main . ident else None | Current thread ident . If current thread is main thread then it returns None . |
244,546 | def filename ( self , exists = os . path . exists , cython_suffix_re = CYTHON_SUFFIX_RE ) : filename = self . frame . f_globals . get ( '__file__' , '' ) if filename is None : filename = '' if filename . endswith ( ( '.pyc' , '.pyo' ) ) : filename = filename [ : - 1 ] elif filename . endswith ( '$py.class' ) : filename... | A string with absolute path to file . |
244,547 | def stdlib ( self ) : if self . module == 'pkg_resources' or self . module . startswith ( 'pkg_resources.' ) : return False elif self . filename . startswith ( SITE_PACKAGES_PATHS ) : return False elif self . filename . startswith ( SYS_PREFIX_PATHS ) : return True else : return False | A boolean flag . True if frame is in stdlib . |
244,548 | def _iter_symbols ( code ) : for node in ast . walk ( ast . parse ( code ) ) : if isinstance ( node , ast . Name ) : yield node . id | Iterate all the variable names in the given expression . |
244,549 | def __make_request_url ( self , teststep_dict , entry_json ) : request_params = utils . convert_list_to_dict ( entry_json [ "request" ] . get ( "queryString" , [ ] ) ) url = entry_json [ "request" ] . get ( "url" ) if not url : logging . exception ( "url missed in request." ) sys . exit ( 1 ) parsed_object = urlparse .... | parse HAR entry request url and queryString and make teststep url and params |
244,550 | def __make_request_method ( self , teststep_dict , entry_json ) : method = entry_json [ "request" ] . get ( "method" ) if not method : logging . exception ( "method missed in request." ) sys . exit ( 1 ) teststep_dict [ "request" ] [ "method" ] = method | parse HAR entry request method and make teststep method . |
244,551 | def __make_request_headers ( self , teststep_dict , entry_json ) : teststep_headers = { } for header in entry_json [ "request" ] . get ( "headers" , [ ] ) : if header [ "name" ] . lower ( ) in IGNORE_REQUEST_HEADERS : continue teststep_headers [ header [ "name" ] ] = header [ "value" ] if teststep_headers : teststep_di... | parse HAR entry request headers and make teststep headers . header in IGNORE_REQUEST_HEADERS will be ignored . |
244,552 | def _make_request_data ( self , teststep_dict , entry_json ) : method = entry_json [ "request" ] . get ( "method" ) if method in [ "POST" , "PUT" , "PATCH" ] : postData = entry_json [ "request" ] . get ( "postData" , { } ) mimeType = postData . get ( "mimeType" ) if "text" in postData : post_data = postData . get ( "te... | parse HAR entry request data and make teststep request data |
244,553 | def _make_validate ( self , teststep_dict , entry_json ) : teststep_dict [ "validate" ] . append ( { "eq" : [ "status_code" , entry_json [ "response" ] . get ( "status" ) ] } ) resp_content_dict = entry_json [ "response" ] . get ( "content" ) headers_mapping = utils . convert_list_to_dict ( entry_json [ "response" ] . ... | parse HAR entry response and make teststep validate . |
244,554 | def load_har_log_entries ( file_path ) : with io . open ( file_path , "r+" , encoding = "utf-8-sig" ) as f : try : content_json = json . loads ( f . read ( ) ) return content_json [ "log" ] [ "entries" ] except ( KeyError , TypeError ) : logging . error ( "HAR file content error: {}" . format ( file_path ) ) sys . exit... | load HAR file and return log entries list |
244,555 | def x_www_form_urlencoded ( post_data ) : if isinstance ( post_data , dict ) : return "&" . join ( [ u"{}={}" . format ( key , value ) for key , value in post_data . items ( ) ] ) else : return post_data | convert origin dict to x - www - form - urlencoded |
244,556 | def convert_x_www_form_urlencoded_to_dict ( post_data ) : if isinstance ( post_data , str ) : converted_dict = { } for k_v in post_data . split ( "&" ) : try : key , value = k_v . split ( "=" ) except ValueError : raise Exception ( "Invalid x_www_form_urlencoded data format: {}" . format ( post_data ) ) converted_dict ... | convert x_www_form_urlencoded data to dict |
244,557 | def dump_yaml ( testcase , yaml_file ) : logging . info ( "dump testcase to YAML format." ) with io . open ( yaml_file , 'w' , encoding = "utf-8" ) as outfile : yaml . dump ( testcase , outfile , allow_unicode = True , default_flow_style = False , indent = 4 ) logging . info ( "Generate YAML testcase successfully: {}" ... | dump HAR entries to yaml testcase |
244,558 | def dump_json ( testcase , json_file ) : logging . info ( "dump testcase to JSON format." ) with io . open ( json_file , 'w' , encoding = "utf-8" ) as outfile : my_json_str = json . dumps ( testcase , ensure_ascii = ensure_ascii , indent = 4 ) if isinstance ( my_json_str , bytes ) : my_json_str = my_json_str . decode (... | dump HAR entries to json testcase |
244,559 | def prepare_request ( self , request ) : try : request_id = local . request_id except AttributeError : request_id = NO_REQUEST_ID if self . request_id_header and request_id != NO_REQUEST_ID : request . headers [ self . request_id_header ] = request_id return super ( Session , self ) . prepare_request ( request ) | Include the request ID if available in the outgoing request |
244,560 | def _get ( self , url , params = None , headers = None ) : url = self . clean_url ( url ) response = requests . get ( url , params = params , verify = self . verify , timeout = self . timeout , headers = headers ) return response | Wraps a GET request with a url check |
244,561 | def _post ( self , url , data = None , json = None , params = None , headers = None ) : url = self . clean_url ( url ) response = requests . post ( url , data = data , json = json , params = params , headers = headers , timeout = self . timeout , verify = self . verify ) return response | Wraps a POST request with a url check |
244,562 | def expand ( self , url ) : url = self . clean_url ( url ) response = self . _get ( url ) if response . ok : return response . url raise ExpandingErrorException | Base expand method . Only visits the link and return the response url |
244,563 | def clean_url ( url ) : if not url . startswith ( ( 'http://' , 'https://' ) ) : url = f'http://{url}' if not URL_RE . match ( url ) : raise BadURLException ( f'{url} is not valid' ) return url | URL Validation function |
244,564 | def create_function_from_request_pdu ( pdu ) : function_code = get_function_code_from_request_pdu ( pdu ) try : function_class = function_code_to_function_map [ function_code ] except KeyError : raise IllegalFunctionError ( function_code ) return function_class . create_from_request_pdu ( pdu ) | Return function instance based on request PDU . |
244,565 | def request_pdu ( self ) : if None in [ self . starting_address , self . quantity ] : raise Exception return struct . pack ( '>BHH' , self . function_code , self . starting_address , self . quantity ) | Build request PDU to read coils . |
244,566 | def request_pdu ( self ) : if None in [ self . address , self . value ] : raise Exception return struct . pack ( '>BHH' , self . function_code , self . address , self . _value ) | Build request PDU to write single coil . |
244,567 | def value ( self , value ) : try : struct . pack ( '>' + conf . TYPE_CHAR , value ) except struct . error : raise IllegalDataValueError self . _value = value | Value to be written on register . |
244,568 | def request_pdu ( self ) : if None in [ self . address , self . value ] : raise Exception return struct . pack ( '>BH' + conf . TYPE_CHAR , self . function_code , self . address , self . value ) | Build request PDU to write single register . |
244,569 | def serve_forever ( self , poll_interval = 0.5 ) : self . serial_port . timeout = poll_interval while not self . _shutdown_request : try : self . serve_once ( ) except ( CRCError , struct . error ) as e : log . error ( 'Can\'t handle request: {0}' . format ( e ) ) except ( SerialTimeoutException , ValueError ) : pass | Wait for incomming requests . |
244,570 | def execute_route ( self , meta_data , request_pdu ) : try : function = create_function_from_request_pdu ( request_pdu ) results = function . execute ( meta_data [ 'unit_id' ] , self . route_map ) try : return function . create_response_pdu ( results ) except TypeError : return function . create_response_pdu ( ) except... | Execute configured route based on requests meta data and request PDU . |
244,571 | def serial_port ( self , serial_port ) : char_size = get_char_size ( serial_port . baudrate ) serial_port . inter_byte_timeout = 1.5 * char_size serial_port . timeout = 3.5 * char_size self . _serial_port = serial_port | Set timeouts on serial port based on baudrate to detect frames . |
244,572 | def serve_once ( self ) : request_adu = self . serial_port . read ( 256 ) log . debug ( '<-- {0}' . format ( hexlify ( request_adu ) ) ) if len ( request_adu ) == 0 : raise ValueError response_adu = self . process ( request_adu ) self . respond ( response_adu ) | Listen and handle 1 request . |
244,573 | def generate_look_up_table ( ) : poly = 0xA001 table = [ ] for index in range ( 256 ) : data = index << 1 crc = 0 for _ in range ( 8 , 0 , - 1 ) : data >>= 1 if ( data ^ crc ) & 0x0001 : crc = ( crc >> 1 ) ^ poly else : crc >>= 1 table . append ( crc ) return table | Generate look up table . |
244,574 | def get_crc ( msg ) : register = 0xFFFF for byte_ in msg : try : val = struct . unpack ( '<B' , byte_ ) [ 0 ] except TypeError : val = byte_ register = ( register >> 8 ) ^ look_up_table [ ( register ^ val ) & 0xFF ] return struct . pack ( '<H' , register ) | Return CRC of 2 byte for message . |
244,575 | def validate_crc ( msg ) : if not struct . unpack ( '<H' , get_crc ( msg [ : - 2 ] ) ) == struct . unpack ( '<H' , msg [ - 2 : ] ) : raise CRCError ( 'CRC validation failed.' ) | Validate CRC of message . |
244,576 | def _create_request_adu ( slave_id , req_pdu ) : first_part_adu = struct . pack ( '>B' , slave_id ) + req_pdu return first_part_adu + get_crc ( first_part_adu ) | Return request ADU for Modbus RTU . |
244,577 | def send_message ( adu , serial_port ) : serial_port . write ( adu ) serial_port . flush ( ) exception_adu_size = 5 response_error_adu = recv_exactly ( serial_port . read , exception_adu_size ) raise_for_exception_adu ( response_error_adu ) expected_response_size = expected_response_pdu_size_from_request_pdu ( adu [ 1 ... | Send ADU over serial to to server and return parsed response . |
244,578 | def pack_mbap ( transaction_id , protocol_id , length , unit_id ) : return struct . pack ( '>HHHB' , transaction_id , protocol_id , length , unit_id ) | Create and return response MBAP . |
244,579 | def memoize ( f ) : cache = { } @ wraps ( f ) def inner ( arg ) : if arg not in cache : cache [ arg ] = f ( arg ) return cache [ arg ] return inner | Decorator which caches function s return value each it is called . If called later with same arguments the cached value is returned . |
244,580 | def recv_exactly ( recv_fn , size ) : recv_bytes = 0 chunks = [ ] while recv_bytes < size : chunk = recv_fn ( size - recv_bytes ) if len ( chunk ) == 0 : break recv_bytes += len ( chunk ) chunks . append ( chunk ) response = b'' . join ( chunks ) if len ( response ) != size : raise ValueError return response | Use the function to read and return exactly number of bytes desired . |
244,581 | def _create_mbap_header ( slave_id , pdu ) : transaction_id = randint ( 0 , 65535 ) length = len ( pdu ) + 1 return struct . pack ( '>HHHB' , transaction_id , 0 , length , slave_id ) | Return byte array with MBAP header for PDU . |
244,582 | def send_message ( adu , sock ) : sock . sendall ( adu ) exception_adu_size = 9 response_error_adu = recv_exactly ( sock . recv , exception_adu_size ) raise_for_exception_adu ( response_error_adu ) expected_response_size = expected_response_pdu_size_from_request_pdu ( adu [ 7 : ] ) + 7 response_remainder = recv_exactly... | Send ADU over socket to to server and return parsed response . |
244,583 | def get_serial_port ( ) : port = Serial ( port = '/dev/ttyS1' , baudrate = 9600 , parity = PARITY_NONE , stopbits = 1 , bytesize = 8 , timeout = 1 ) fh = port . fileno ( ) serial_rs485 = struct . pack ( 'hhhhhhhh' , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) fcntl . ioctl ( fh , 0x542F , serial_rs485 ) return port | Return serial . Serial instance ready to use for RS485 . |
244,584 | def _set_multi_bit_value_format_character ( self ) : self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . upper ( ) if self . SIGNED_VALUES : self . MULTI_BIT_VALUE_FORMAT_CHARACTER = self . MULTI_BIT_VALUE_FORMAT_CHARACTER . lower ( ) | Set format character for multibit values . |
244,585 | def get_filename4code ( module , content , ext = None ) : imagedir = module + "-images" fn = hashlib . sha1 ( content . encode ( sys . getfilesystemencoding ( ) ) ) . hexdigest ( ) try : os . mkdir ( imagedir ) sys . stderr . write ( 'Created directory ' + imagedir + '\n' ) except OSError : pass if ext : fn += "." + ex... | Generate filename based on content |
244,586 | def toJSONFilters ( actions ) : try : input_stream = io . TextIOWrapper ( sys . stdin . buffer , encoding = 'utf-8' ) except AttributeError : input_stream = codecs . getreader ( "utf-8" ) ( sys . stdin ) source = input_stream . read ( ) if len ( sys . argv ) > 1 : format = sys . argv [ 1 ] else : format = "" sys . stdo... | Generate a JSON - to - JSON filter from stdin to stdout |
244,587 | def applyJSONFilters ( actions , source , format = "" ) : doc = json . loads ( source ) if 'meta' in doc : meta = doc [ 'meta' ] elif doc [ 0 ] : meta = doc [ 0 ] [ 'unMeta' ] else : meta = { } altered = doc for action in actions : altered = walk ( altered , action , format , meta ) return json . dumps ( altered ) | Walk through JSON structure and apply filters |
244,588 | def stringify ( x ) : result = [ ] def go ( key , val , format , meta ) : if key in [ 'Str' , 'MetaString' ] : result . append ( val ) elif key == 'Code' : result . append ( val [ 1 ] ) elif key == 'Math' : result . append ( val [ 1 ] ) elif key == 'LineBreak' : result . append ( " " ) elif key == 'SoftBreak' : result ... | Walks the tree x and returns concatenated string content leaving out all formatting . |
244,589 | def attributes ( attrs ) : attrs = attrs or { } ident = attrs . get ( "id" , "" ) classes = attrs . get ( "classes" , [ ] ) keyvals = [ [ x , attrs [ x ] ] for x in attrs if ( x != "classes" and x != "id" ) ] return [ ident , classes , keyvals ] | Returns an attribute list constructed from the dictionary attrs . |
244,590 | def to_latlon ( easting , northing , zone_number , zone_letter = None , northern = None , strict = True ) : if not zone_letter and northern is None : raise ValueError ( 'either zone_letter or northern needs to be set' ) elif zone_letter and northern is not None : raise ValueError ( 'set either zone_letter or northern, ... | This function convert an UTM coordinate into Latitude and Longitude |
244,591 | def from_latlon ( latitude , longitude , force_zone_number = None , force_zone_letter = None ) : if not in_bounds ( latitude , - 80.0 , 84.0 ) : raise OutOfRangeError ( 'latitude out of range (must be between 80 deg S and 84 deg N)' ) if not in_bounds ( longitude , - 180.0 , 180.0 ) : raise OutOfRangeError ( 'longitude... | This function convert Latitude and Longitude to UTM coordinate |
244,592 | def _capture_original_object ( self ) : try : self . _doubles_target = getattr ( self . target , self . _name ) except AttributeError : raise VerifyingDoubleError ( self . target , self . _name ) | Capture the original python object . |
244,593 | def set_value ( self , value ) : self . _value = value setattr ( self . target , self . _name , value ) | Set the value of the target . |
244,594 | def patch_class ( input_class ) : class Instantiator ( object ) : @ classmethod def _doubles__new__ ( self , * args , ** kwargs ) : pass new_class = type ( input_class . __name__ , ( input_class , Instantiator ) , { } ) return new_class | Create a new class based on the input_class . |
244,595 | def satisfy_any_args_match ( self ) : is_match = super ( Expectation , self ) . satisfy_any_args_match ( ) if is_match : self . _satisfy ( ) return is_match | Returns a boolean indicating whether or not the mock will accept arbitrary arguments . This will be true unless the user has specified otherwise using with_args or with_no_args . |
244,596 | def is_satisfied ( self ) : return self . _call_counter . has_correct_call_count ( ) and ( self . _call_counter . never ( ) or self . _is_satisfied ) | Returns a boolean indicating whether or not the double has been satisfied . Stubs are always satisfied but mocks are only satisfied if they ve been called as was declared or if call is expected not to happen . |
244,597 | def has_too_many_calls ( self ) : if self . has_exact and self . _call_count > self . _exact : return True if self . has_maximum and self . _call_count > self . _maximum : return True return False | Test if there have been too many calls |
244,598 | def has_too_few_calls ( self ) : if self . has_exact and self . _call_count < self . _exact : return True if self . has_minimum and self . _call_count < self . _minimum : return True return False | Test if there have not been enough calls |
244,599 | def _restriction_string ( self ) : if self . has_minimum : string = 'at least ' value = self . _minimum elif self . has_maximum : string = 'at most ' value = self . _maximum elif self . has_exact : string = '' value = self . _exact return ( string + '{} {}' ) . format ( value , pluralize ( 'time' , value ) ) | Get a string explaining the expectation currently set |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.