idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
251,000
def get_auth ( self ) : return ( self . _cfgparse . get ( self . _section , 'username' ) , self . _cfgparse . get ( self . _section , 'password' ) )
Returns username from the configfile .
251,001
def connect ( config_file = qcs . default_filename , section = 'info' , remember_me = False , remember_me_always = False ) : conf = qcconf . QualysConnectConfig ( filename = config_file , section = section , remember_me = remember_me , remember_me_always = remember_me_always ) connect = qcconn . QGConnector ( conf . ge...
Return a QGAPIConnect object for v1 API pulling settings from config file .
251,002
def format_api_version ( self , api_version ) : if type ( api_version ) == str : api_version = api_version . lower ( ) if api_version [ 0 ] == 'v' and api_version [ 1 ] . isdigit ( ) : api_version = api_version [ 1 : ] if api_version in ( 'asset management' , 'assets' , 'tag' , 'tagging' , 'tags' ) : api_version = 'am'...
Return QualysGuard API version for api_version specified .
251,003
def which_api_version ( self , api_call ) : if api_call . endswith ( '.php' ) : return 1 elif api_call . startswith ( 'api/2.0/' ) : return 2 elif '/am/' in api_call : return 'am' elif '/was/' in api_call : return 'was' return False
Return QualysGuard API version for api_call specified .
251,004
def url_api_version ( self , api_version ) : if api_version == 1 : url = "https://%s/msp/" % ( self . server , ) elif api_version == 2 : url = "https://%s/" % ( self . server , ) elif api_version == 'was' : url = "https://%s/qps/rest/3.0/" % ( self . server , ) elif api_version == 'am' : url = "https://%s/qps/rest/1.0/...
Return base API url string for the QualysGuard api_version and server .
251,005
def format_http_method ( self , api_version , api_call , data ) : if api_version == 2 : return 'post' elif api_version == 1 : if api_call in self . api_methods [ '1 post' ] : return 'post' else : return 'get' elif api_version == 'was' : api_call_endpoint = api_call [ : api_call . rfind ( '/' ) + 1 ] if api_call_endpoin...
Return QualysGuard API http method with POST preferred ..
251,006
def preformat_call ( self , api_call ) : api_call_formatted = api_call . lstrip ( '/' ) api_call_formatted = api_call_formatted . rstrip ( '?' ) if api_call != api_call_formatted : logger . debug ( 'api_call post strip =\n%s' % api_call_formatted ) return api_call_formatted
Return properly formatted QualysGuard API call .
251,007
def format_call ( self , api_version , api_call ) : api_call = api_call . lstrip ( '/' ) api_call = api_call . rstrip ( '?' ) logger . debug ( 'api_call post strip =\n%s' % api_call ) if ( api_version == 2 and api_call [ - 1 ] != '/' ) : logger . debug ( 'Adding "/" to api_call.' ) api_call += '/' if api_call in self ....
Return properly formatted QualysGuard API call according to api_version etiquette .
251,008
def format_payload ( self , api_version , data ) : if ( api_version in ( 1 , 2 ) ) : if type ( data ) == str : logger . debug ( 'Converting string to dict:\n%s' % data ) data = data . lstrip ( '?' ) data = data . rstrip ( '&' ) data = parse_qs ( data ) logger . debug ( 'Converted:\n%s' % str ( data ) ) elif api_version...
Return appropriate QualysGuard API call .
251,009
def travis_after ( ini , envlist ) : if os . environ . get ( 'TRAVIS_PULL_REQUEST' , 'false' ) != 'false' : return if not after_config_matches ( ini , envlist ) : return github_token = os . environ . get ( 'GITHUB_TOKEN' ) if not github_token : print ( 'No GitHub token given.' , file = sys . stderr ) sys . exit ( NO_GI...
Wait for all jobs to finish then exit successfully .
251,010
def after_config_matches ( ini , envlist ) : section = ini . sections . get ( 'travis:after' , { } ) if not section : return False if 'envlist' in section or 'toxenv' in section : if 'toxenv' in section : print ( 'The "toxenv" key of the [travis:after] section is ' 'deprecated in favor of the "envlist" key.' , file = s...
Determine if this job should wait for the others .
251,011
def get_job_statuses ( github_token , api_url , build_id , polling_interval , job_number ) : auth = get_json ( '{api_url}/auth/github' . format ( api_url = api_url ) , data = { 'github_token' : github_token } ) [ 'access_token' ] while True : build = get_json ( '{api_url}/builds/{build_id}' . format ( api_url = api_url...
Wait for all the travis jobs to complete .
251,012
def get_json ( url , auth = None , data = None ) : headers = { 'Accept' : 'application/vnd.travis-ci.2+json' , 'User-Agent' : 'Travis/Tox-Travis-1.0a' , } if auth : headers [ 'Authorization' ] = 'token {auth}' . format ( auth = auth ) params = { } if data : headers [ 'Content-Type' ] = 'application/json' params [ 'data...
Make a GET request and return the response as parsed JSON .
251,013
def detect_envlist ( ini ) : declared_envs = get_declared_envs ( ini ) desired_factors = get_desired_factors ( ini ) desired_envs = [ '-' . join ( env ) for env in product ( * desired_factors ) ] return match_envs ( declared_envs , desired_envs , passthru = len ( desired_factors ) == 1 )
Default envlist automatically based on the Travis environment .
251,014
def autogen_envconfigs ( config , envs ) : prefix = 'tox' if config . toxinipath . basename == 'setup.cfg' else None reader = tox . config . SectionReader ( "tox" , config . _cfg , prefix = prefix ) distshare_default = "{homedir}/.tox/distshare" reader . addsubstitutions ( toxinidir = config . toxinidir , homedir = con...
Make the envconfigs for undeclared envs .
251,015
def get_declared_envs ( ini ) : tox_section_name = 'tox:tox' if ini . path . endswith ( 'setup.cfg' ) else 'tox' tox_section = ini . sections . get ( tox_section_name , { } ) envlist = split_env ( tox_section . get ( 'envlist' , [ ] ) ) section_envs = [ section [ 8 : ] for section in sorted ( ini . sections , key = ini...
Get the full list of envs from the tox ini .
251,016
def get_version_info ( ) : overrides = os . environ . get ( '__TOX_TRAVIS_SYS_VERSION' ) if overrides : version , major , minor = overrides . split ( ',' ) [ : 3 ] major , minor = int ( major ) , int ( minor ) else : version , ( major , minor ) = sys . version , sys . version_info [ : 2 ] return version , major , minor
Get version info from the sys module .
251,017
def guess_python_env ( ) : version , major , minor = get_version_info ( ) if 'PyPy' in version : return 'pypy3' if major == 3 else 'pypy' return 'py{major}{minor}' . format ( major = major , minor = minor )
Guess the default python env to use .
251,018
def get_default_envlist ( version ) : if version in [ 'pypy' , 'pypy3' ] : return version match = re . match ( r'^(\d)\.(\d)(?:\.\d+)?$' , version or '' ) if match : major , minor = match . groups ( ) return 'py{major}{minor}' . format ( major = major , minor = minor ) return guess_python_env ( )
Parse a default tox env based on the version .
251,019
def get_desired_factors ( ini ) : travis_section = ini . sections . get ( 'travis' , { } ) found_factors = [ ( factor , parse_dict ( travis_section [ factor ] ) ) for factor in TRAVIS_FACTORS if factor in travis_section ] if 'tox:travis' in ini . sections : print ( 'The [tox:travis] section is deprecated in favor of' '...
Get the list of desired envs per declared factor .
251,020
def match_envs ( declared_envs , desired_envs , passthru ) : matched = [ declared for declared in declared_envs if any ( env_matches ( declared , desired ) for desired in desired_envs ) ] return desired_envs if not matched and passthru else matched
Determine the envs that match the desired_envs .
251,021
def env_matches ( declared , desired ) : desired_factors = desired . split ( '-' ) declared_factors = declared . split ( '-' ) return all ( factor in declared_factors for factor in desired_factors )
Determine if a declared env matches a desired env .
251,022
def override_ignore_outcome ( ini ) : travis_reader = tox . config . SectionReader ( "travis" , ini ) return travis_reader . getbool ( 'unignore_outcomes' , False )
Decide whether to override ignore_outcomes .
251,023
def tox_addoption ( parser ) : parser . add_argument ( '--travis-after' , dest = 'travis_after' , action = 'store_true' , help = 'Exit successfully after all Travis jobs complete successfully.' ) if 'TRAVIS' in os . environ : pypy_version_monkeypatch ( ) subcommand_test_monkeypatch ( tox_subcommand_test_post )
Add arguments and needed monkeypatches .
251,024
def tox_configure ( config ) : if 'TRAVIS' not in os . environ : return ini = config . _cfg if 'TOXENV' not in os . environ and not config . option . env : envlist = detect_envlist ( ini ) undeclared = set ( envlist ) - set ( config . envconfigs ) if undeclared : print ( 'Matching undeclared envs is deprecated. Be sure...
Check for the presence of the added options .
251,025
def parse_dict ( value ) : lines = [ line . strip ( ) for line in value . strip ( ) . splitlines ( ) ] pairs = [ line . split ( ':' , 1 ) for line in lines if line ] return dict ( ( k . strip ( ) , v . strip ( ) ) for k , v in pairs )
Parse a dict value from the tox config .
251,026
def pypy_version_monkeypatch ( ) : version = os . environ . get ( 'TRAVIS_PYTHON_VERSION' ) if version and default_factors and version . startswith ( 'pypy3.3-' ) : default_factors [ 'pypy3' ] = 'python'
Patch Tox to work with non - default PyPy 3 versions .
251,027
def direction ( self ) : if _get_bit ( self . _mcp . iodir , self . _pin ) : return digitalio . Direction . INPUT return digitalio . Direction . OUTPUT
The direction of the pin either True for an input or False for an output .
251,028
def pull ( self ) : if _get_bit ( self . _mcp . gppu , self . _pin ) : return digitalio . Pull . UP return None
Enable or disable internal pull - up resistors for this pin . A value of digitalio . Pull . UP will enable a pull - up resistor and None will disable it . Pull - down resistors are NOT supported!
251,029
def get_throttled_read_event_count ( table_name , lookback_window_start = 15 , lookback_period = 5 ) : try : metrics = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'ReadThrottleEvents' ) except BotoServerError : raise if metrics : throttled_read_events = int ( metrics [ 0 ] [ 'Sum' ] ) else...
Returns the number of throttled read events during a given time frame
251,030
def get_throttled_by_consumed_read_percent ( table_name , lookback_window_start = 15 , lookback_period = 5 ) : try : metrics1 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'ConsumedReadCapacityUnits' ) metrics2 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'Re...
Returns the number of throttled read events in percent of consumption
251,031
def get_throttled_by_consumed_write_percent ( table_name , lookback_window_start = 15 , lookback_period = 5 ) : try : metrics1 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , 'ConsumedWriteCapacityUnits' ) metrics2 = __get_aws_metric ( table_name , lookback_window_start , lookback_period , '...
Returns the number of throttled write events in percent of consumption
251,032
def __get_aws_metric ( table_name , lookback_window_start , lookback_period , metric_name ) : try : now = datetime . utcnow ( ) start_time = now - timedelta ( minutes = lookback_window_start ) end_time = now - timedelta ( minutes = lookback_window_start - lookback_period ) return cloudwatch_connection . get_metric_stat...
Returns a metric list from the AWS CloudWatch service may return None if no metric exists
251,033
def ensure_provisioning ( table_name , table_key , gsi_name , gsi_key , num_consec_read_checks , num_consec_write_checks ) : if get_global_option ( 'circuit_breaker_url' ) or get_gsi_option ( table_key , gsi_key , 'circuit_breaker_url' ) : if circuit_breaker . is_open ( table_name , table_key , gsi_name , gsi_key ) : l...
Ensure that provisioning is correct for Global Secondary Indexes
251,034
def __update_throughput ( table_name , table_key , gsi_name , gsi_key , read_units , write_units ) : try : current_ru = dynamodb . get_provisioned_gsi_read_units ( table_name , gsi_name ) current_wu = dynamodb . get_provisioned_gsi_write_units ( table_name , gsi_name ) except JSONResponseError : raise try : gsi_status ...
Update throughput on the GSI
251,035
def is_open ( table_name = None , table_key = None , gsi_name = None , gsi_key = None ) : logger . debug ( 'Checking circuit breaker status' ) pattern = re . compile ( r'^(?P<scheme>http(s)?://)' r'((?P<username>.+):(?P<password>.+)@){0,1}' r'(?P<url>.*)$' ) url = timeout = None if gsi_name : url = get_gsi_option ( tab...
Checks whether the circuit breaker is open
251,036
def __get_connection_cloudwatch ( ) : region = get_global_option ( 'region' ) try : if ( get_global_option ( 'aws_access_key_id' ) and get_global_option ( 'aws_secret_access_key' ) ) : logger . debug ( 'Authenticating to CloudWatch using ' 'credentials in configuration file' ) connection = cloudwatch . connect_to_regio...
Ensure connection to CloudWatch
251,037
def get_tables_and_gsis ( ) : table_names = set ( ) configured_tables = get_configured_tables ( ) not_used_tables = set ( configured_tables ) for table_instance in list_tables ( ) : for key_name in configured_tables : try : if re . match ( key_name , table_instance . table_name ) : logger . debug ( "Table {0} match wit...
Get a set of tables and gsis and their configuration keys
251,038
def list_tables ( ) : tables = [ ] try : table_list = DYNAMODB_CONNECTION . list_tables ( ) while True : for table_name in table_list [ u'TableNames' ] : tables . append ( get_table ( table_name ) ) if u'LastEvaluatedTableName' in table_list : table_list = DYNAMODB_CONNECTION . list_tables ( table_list [ u'LastEvaluate...
Return list of DynamoDB tables available from AWS
251,039
def table_gsis ( table_name ) : try : desc = DYNAMODB_CONNECTION . describe_table ( table_name ) [ u'Table' ] except JSONResponseError : raise if u'GlobalSecondaryIndexes' in desc : return desc [ u'GlobalSecondaryIndexes' ] return [ ]
Returns a list of GSIs for the given table
251,040
def __get_connection_dynamodb ( retries = 3 ) : connected = False region = get_global_option ( 'region' ) while not connected : if ( get_global_option ( 'aws_access_key_id' ) and get_global_option ( 'aws_secret_access_key' ) ) : logger . debug ( 'Authenticating to DynamoDB using ' 'credentials in configuration file' ) ...
Ensure connection to DynamoDB
251,041
def __is_gsi_maintenance_window ( table_name , gsi_name , maintenance_windows ) : maintenance_window_list = [ ] for window in maintenance_windows . split ( ',' ) : try : start , end = window . split ( '-' , 1 ) except ValueError : logger . error ( '{0} - GSI: {1} - ' 'Malformatted maintenance window' . format ( table_n...
Checks that the current time is within the maintenance window
251,042
def publish_gsi_notification ( table_key , gsi_key , message , message_types , subject = None ) : topic = get_gsi_option ( table_key , gsi_key , 'sns_topic_arn' ) if not topic : return for message_type in message_types : if ( message_type in get_gsi_option ( table_key , gsi_key , 'sns_message_types' ) ) : __publish ( t...
Publish a notification for a specific GSI
251,043
def publish_table_notification ( table_key , message , message_types , subject = None ) : topic = get_table_option ( table_key , 'sns_topic_arn' ) if not topic : return for message_type in message_types : if message_type in get_table_option ( table_key , 'sns_message_types' ) : __publish ( topic , message , subject ) r...
Publish a notification for a specific table
251,044
def __publish ( topic , message , subject = None ) : try : SNS_CONNECTION . publish ( topic = topic , message = message , subject = subject ) logger . info ( 'Sent SNS notification to {0}' . format ( topic ) ) except BotoServerError as error : logger . error ( 'Problem sending SNS notification: {0}' . format ( error . ...
Publish a message to a SNS topic
251,045
def __get_connection_SNS ( ) : region = get_global_option ( 'region' ) try : if ( get_global_option ( 'aws_access_key_id' ) and get_global_option ( 'aws_secret_access_key' ) ) : logger . debug ( 'Authenticating to SNS using ' 'credentials in configuration file' ) connection = sns . connect_to_region ( region , aws_acce...
Ensure connection to SNS
251,046
def __calculate_always_decrease_rw_values ( table_name , read_units , provisioned_reads , write_units , provisioned_writes ) : if read_units <= provisioned_reads and write_units <= provisioned_writes : return ( read_units , write_units ) if read_units < provisioned_reads : logger . info ( '{0} - Reads could be decrease...
Calculate values for always - decrease - rw - together
251,047
def __update_throughput ( table_name , key_name , read_units , write_units ) : try : current_ru = dynamodb . get_provisioned_table_read_units ( table_name ) current_wu = dynamodb . get_provisioned_table_write_units ( table_name ) except JSONResponseError : raise try : table_status = dynamodb . get_table_status ( table_...
Update throughput on the DynamoDB table
251,048
def get_configuration ( ) : configuration = { 'global' : { } , 'logging' : { } , 'tables' : ordereddict ( ) } cmd_line_options = command_line_parser . parse ( ) conf_file_options = None if 'config' in cmd_line_options : conf_file_options = config_file_parser . parse ( cmd_line_options [ 'config' ] ) configuration [ 'gl...
Get the configuration from command line and config files
251,049
def __get_cmd_table_options ( cmd_line_options ) : table_name = cmd_line_options [ 'table_name' ] options = { table_name : { } } for option in DEFAULT_OPTIONS [ 'table' ] . keys ( ) : options [ table_name ] [ option ] = DEFAULT_OPTIONS [ 'table' ] [ option ] if option in cmd_line_options : options [ table_name ] [ opti...
Get all table options from the command line
251,050
def __get_config_table_options ( conf_file_options ) : options = ordereddict ( ) if not conf_file_options : return options for table_name in conf_file_options [ 'tables' ] : options [ table_name ] = { } for option in DEFAULT_OPTIONS [ 'table' ] . keys ( ) : options [ table_name ] [ option ] = DEFAULT_OPTIONS [ 'table' ...
Get all table options from the config file
251,051
def __get_global_options ( cmd_line_options , conf_file_options = None ) : options = { } for option in DEFAULT_OPTIONS [ 'global' ] . keys ( ) : options [ option ] = DEFAULT_OPTIONS [ 'global' ] [ option ] if conf_file_options and option in conf_file_options : options [ option ] = conf_file_options [ option ] if cmd_li...
Get all global options
251,052
def __get_logging_options ( cmd_line_options , conf_file_options = None ) : options = { } for option in DEFAULT_OPTIONS [ 'logging' ] . keys ( ) : options [ option ] = DEFAULT_OPTIONS [ 'logging' ] [ option ] if conf_file_options and option in conf_file_options : options [ option ] = conf_file_options [ option ] if cmd...
Get all logging options
251,053
def __check_logging_rules ( configuration ) : valid_log_levels = [ 'debug' , 'info' , 'warning' , 'error' ] if configuration [ 'logging' ] [ 'log_level' ] . lower ( ) not in valid_log_levels : print ( 'Log level must be one of {0}' . format ( ', ' . join ( valid_log_levels ) ) ) sys . exit ( 1 )
Check that the logging values are proper
251,054
def is_consumed_over_proposed ( current_provisioning , proposed_provisioning , consumed_units_percent ) : consumption_based_current_provisioning = int ( math . ceil ( current_provisioning * ( consumed_units_percent / 100 ) ) ) return consumption_based_current_provisioning > proposed_provisioning
Determines if the currently consumed capacity is over the proposed capacity for this table
251,055
def __get_min_reads ( current_provisioning , min_provisioned_reads , log_tag ) : reads = 1 if min_provisioned_reads : reads = int ( min_provisioned_reads ) if reads > int ( current_provisioning * 2 ) : reads = int ( current_provisioning * 2 ) logger . debug ( '{0} - ' 'Cannot reach min-provisioned-reads as max scale up...
Get the minimum number of reads to current_provisioning
251,056
def __get_min_writes ( current_provisioning , min_provisioned_writes , log_tag ) : writes = 1 if min_provisioned_writes : writes = int ( min_provisioned_writes ) if writes > int ( current_provisioning * 2 ) : writes = int ( current_provisioning * 2 ) logger . debug ( '{0} - ' 'Cannot reach min-provisioned-writes as max...
Get the minimum number of writes to current_provisioning
251,057
def restart ( self , * args , ** kwargs ) : self . stop ( ) try : self . start ( * args , ** kwargs ) except IOError : raise
Restart the daemon
251,058
def __parse_options ( config_file , section , options ) : configuration = { } for option in options : try : if option . get ( 'type' ) == 'str' : configuration [ option . get ( 'key' ) ] = config_file . get ( section , option . get ( 'option' ) ) elif option . get ( 'type' ) == 'int' : try : configuration [ option . ge...
Parse the section options
251,059
def main ( ) : try : if get_global_option ( 'show_config' ) : print json . dumps ( config . get_configuration ( ) , indent = 2 ) elif get_global_option ( 'daemon' ) : daemon = DynamicDynamoDBDaemon ( '{0}/dynamic-dynamodb.{1}.pid' . format ( get_global_option ( 'pid_file_dir' ) , get_global_option ( 'instance' ) ) ) if...
Main function called from dynamic - dynamodb
251,060
def decode_tve_parameter ( data ) : ( nontve , ) = struct . unpack ( nontve_header , data [ : nontve_header_len ] ) if nontve == 1023 : ( size , ) = struct . unpack ( '!H' , data [ nontve_header_len : nontve_header_len + 2 ] ) ( subtype , ) = struct . unpack ( '!H' , data [ size - 4 : size - 2 ] ) param_name , param_fm...
Generic byte decoding function for TVE parameters .
251,061
def read ( filename ) : fname = os . path . join ( here , filename ) with codecs . open ( fname , encoding = 'utf-8' ) as f : return f . read ( )
Get the long description from a file .
251,062
def deserialize ( self ) : if self . msgbytes is None : raise LLRPError ( 'No message bytes to deserialize.' ) data = self . msgbytes msgtype , length , msgid = struct . unpack ( self . full_hdr_fmt , data [ : self . full_hdr_len ] ) ver = ( msgtype >> 10 ) & BITMASK ( 3 ) msgtype = msgtype & BITMASK ( 10 ) try : name ...
Turns a sequence of bytes into a message dictionary .
251,063
def parseReaderConfig ( self , confdict ) : logger . debug ( 'parseReaderConfig input: %s' , confdict ) conf = { } for k , v in confdict . items ( ) : if not k . startswith ( 'Parameter' ) : continue ty = v [ 'Type' ] data = v [ 'Data' ] vendor = None subtype = None try : vendor , subtype = v [ 'Vendor' ] , v [ 'Subtyp...
Parse a reader configuration dictionary .
251,064
def parseCapabilities ( self , capdict ) : gdc = capdict [ 'GeneralDeviceCapabilities' ] max_ant = gdc [ 'MaxNumberOfAntennaSupported' ] if max ( self . antennas ) > max_ant : reqd = ',' . join ( map ( str , self . antennas ) ) avail = ',' . join ( map ( str , range ( 1 , max_ant + 1 ) ) ) errmsg = ( 'Invalid antenna s...
Parse a capabilities dictionary and adjust instance settings .
251,065
def startInventory ( self , proto = None , force_regen_rospec = False ) : if self . state == LLRPClient . STATE_INVENTORYING : logger . warn ( 'ignoring startInventory() while already inventorying' ) return None rospec = self . getROSpec ( force_new = force_regen_rospec ) [ 'ROSpec' ] logger . info ( 'starting inventor...
Add a ROSpec to the reader and enable it .
251,066
def stopPolitely ( self , disconnect = False ) : logger . info ( 'stopping politely' ) if disconnect : logger . info ( 'will disconnect when stopped' ) self . disconnecting = True self . sendMessage ( { 'DELETE_ACCESSSPEC' : { 'Ver' : 1 , 'Type' : 41 , 'ID' : 0 , 'AccessSpecID' : 0 } } ) self . setState ( LLRPClient . ...
Delete all active ROSpecs . Return a Deferred that will be called when the DELETE_ROSPEC_RESPONSE comes back .
251,067
def parsePowerTable ( uhfbandcap ) : bandtbl = { k : v for k , v in uhfbandcap . items ( ) if k . startswith ( 'TransmitPowerLevelTableEntry' ) } tx_power_table = [ 0 ] * ( len ( bandtbl ) + 1 ) for k , v in bandtbl . items ( ) : idx = v [ 'Index' ] tx_power_table [ idx ] = int ( v [ 'TransmitPowerValue' ] ) / 100.0 re...
Parse the transmit power table
251,068
def get_tx_power ( self , tx_power ) : if not self . tx_power_table : logger . warn ( 'get_tx_power(): tx_power_table is empty!' ) return { } logger . debug ( 'requested tx_power: %s' , tx_power ) min_power = self . tx_power_table . index ( min ( self . tx_power_table ) ) max_power = self . tx_power_table . index ( max...
Validates tx_power against self . tx_power_table
251,069
def setTxPower ( self , tx_power ) : tx_pow_validated = self . get_tx_power ( tx_power ) logger . debug ( 'tx_pow_validated: %s' , tx_pow_validated ) needs_update = False for ant , ( tx_pow_idx , tx_pow_dbm ) in tx_pow_validated . items ( ) : if self . tx_power [ ant ] != tx_pow_idx : self . tx_power [ ant ] = tx_pow_i...
Set the transmission power for one or more antennas .
251,070
def pause ( self , duration_seconds = 0 , force = False , force_regen_rospec = False ) : logger . debug ( 'pause(%s)' , duration_seconds ) if self . state != LLRPClient . STATE_INVENTORYING : if not force : logger . info ( 'ignoring pause(); not inventorying (state==%s)' , self . getStateName ( self . state ) ) return ...
Pause an inventory operation for a set amount of time .
251,071
def sendMessage ( self , msg_dict ) : sent_ids = [ ] for name in msg_dict : self . last_msg_id += 1 msg_dict [ name ] [ 'ID' ] = self . last_msg_id sent_ids . append ( ( name , self . last_msg_id ) ) llrp_msg = LLRPMessage ( msgdict = msg_dict ) assert llrp_msg . msgbytes , "LLRPMessage is empty" self . transport . wri...
Serialize and send a dict LLRP Message
251,072
def buildProtocol ( self , addr ) : self . resetDelay ( ) clargs = self . client_args . copy ( ) hostport = '{}:{}' . format ( addr . host , addr . port ) logger . debug ( 'Building protocol for %s' , hostport ) if hostport in self . antenna_dict : clargs [ 'antennas' ] = [ int ( x ) for x in self . antenna_dict [ host...
Get a new LLRP client protocol object .
251,073
def setTxPower ( self , tx_power , peername = None ) : if peername : protocols = [ p for p in self . protocols if p . peername [ 0 ] == peername ] else : protocols = self . protocols for proto in protocols : proto . setTxPower ( tx_power )
Set the transmit power on one or all readers
251,074
def politeShutdown ( self ) : protoDeferreds = [ ] for proto in self . protocols : protoDeferreds . append ( proto . stopPolitely ( disconnect = True ) ) return defer . DeferredList ( protoDeferreds )
Stop inventory on all connected readers .
251,075
def parse_sgtin_96 ( sgtin_96 ) : if not sgtin_96 : raise Exception ( 'Pass in a value.' ) if not sgtin_96 . startswith ( "30" ) : raise Exception ( 'Not SGTIN-96.' ) binary = "{0:020b}" . format ( int ( sgtin_96 , 16 ) ) . zfill ( 96 ) header = int ( binary [ : 8 ] , 2 ) tag_filter = int ( binary [ 8 : 11 ] , 2 ) part...
Given a SGTIN - 96 hex string parse each segment . Returns a dictionary of the segments .
251,076
def decode_param ( data ) : logger . debug ( 'decode_param data: %r' , data ) header_len = struct . calcsize ( '!HH' ) partype , parlen = struct . unpack ( '!HH' , data [ : header_len ] ) pardata = data [ header_len : parlen ] logger . debug ( 'decode_param pardata: %r' , pardata ) ret = { 'Type' : partype , } if party...
Decode any parameter to a byte sequence .
251,077
def download_files ( file_list ) : for _ , source_data_file in file_list : sql_gz_name = source_data_file [ 'name' ] . split ( '/' ) [ - 1 ] msg = 'Downloading: %s' % ( sql_gz_name ) log . debug ( msg ) new_data = objectstore . get_object ( handelsregister_conn , source_data_file , 'handelsregister' ) with open ( 'data...
Download the latest data .
251,078
def get_connection ( store_settings : dict = { } ) -> Connection : store = store_settings if not store_settings : store = make_config_from_env ( ) os_options = { 'tenant_id' : store [ 'TENANT_ID' ] , 'region_name' : store [ 'REGION_NAME' ] , } use_internal = os . getenv ( 'OBJECTSTORE_LOCAL' , '' ) if use_internal : os...
get an objectsctore connection
251,079
def get_object ( connection , object_meta_data : dict , dirname : str ) : return connection . get_object ( dirname , object_meta_data [ 'name' ] ) [ 1 ]
Download object from objectstore . object_meta_data is an object retured when using get_full_container_list
251,080
def put_object ( connection , container : str , object_name : str , contents , content_type : str ) -> None : connection . put_object ( container , object_name , contents = contents , content_type = content_type )
Put file to objectstore
251,081
def delete_object ( connection , container : str , object_meta_data : dict ) -> None : connection . delete_object ( container , object_meta_data [ 'name' ] )
Delete single object from objectstore
251,082
def return_file_objects ( connection , container , prefix = 'database' ) : options = [ ] meta_data = objectstore . get_full_container_list ( connection , container , prefix = 'database' ) env = ENV . upper ( ) for o_info in meta_data : expected_file = f'database.{ENV}' if o_info [ 'name' ] . startswith ( expected_file ...
Given connecton and container find database dumps
251,083
def remove_old_dumps ( connection , container : str , days = None ) : if not days : return if days < 20 : LOG . error ( 'A minimum of 20 backups is stored' ) return options = return_file_objects ( connection , container ) for dt , o_info in options : now = datetime . datetime . now ( ) delta = now - dt if delta . days ...
Remove dumps older than x days
251,084
def download_database ( connection , container : str , target : str = "" ) : meta_data = objectstore . get_full_container_list ( connection , container , prefix = 'database' ) options = return_file_objects ( connection , container ) for o_info in meta_data : expected_file = f'database.{ENV}' LOG . info ( o_info [ 'name...
Download database dump
251,085
def remember ( self , user_name ) : log . debug ( 'Repoze OAuth remember' ) environ = toolkit . request . environ rememberer = self . _get_rememberer ( environ ) identity = { 'repoze.who.userid' : user_name } headers = rememberer . remember ( environ , identity ) for header , value in headers : toolkit . response . hea...
Remember the authenticated identity .
251,086
def redirect_from_callback ( self ) : state = toolkit . request . params . get ( 'state' ) came_from = get_came_from ( state ) toolkit . response . status = 302 toolkit . response . location = came_from
Redirect to the callback URL after a successful authentication .
251,087
def can_share_folder ( self , user , folder ) : return folder . parent_id is None and folder . author_id == user . id
Return True if user can share folder .
251,088
def storage_color ( self , user_storage ) : p = user_storage . percentage if p >= 0 and p < 60 : return "success" if p >= 60 and p < 90 : return "warning" if p >= 90 and p <= 100 : return "danger" raise ValueError ( "percentage out of range" )
Return labels indicating amount of storage used .
251,089
def folder_created_message ( self , request , folder ) : messages . success ( request , _ ( "Folder {} was created" . format ( folder ) ) )
Send messages . success message after successful folder creation .
251,090
def document_created_message ( self , request , document ) : messages . success ( request , _ ( "Document {} was created" . format ( document ) ) )
Send messages . success message after successful document creation .
251,091
def folder_shared_message ( self , request , user , folder ) : messages . success ( request , _ ( "Folder {} is now shared with {}" . format ( folder , user ) ) )
Send messages . success message after successful share .
251,092
def folder_pre_delete ( self , request , folder ) : for m in folder . members ( ) : if m . __class__ == folder . __class__ : self . folder_pre_delete ( request , m ) m . delete ( )
Perform folder operations prior to deletions . For example deleting all contents .
251,093
def file_upload_to ( self , instance , filename ) : ext = filename . split ( "." ) [ - 1 ] filename = "{}.{}" . format ( uuid . uuid4 ( ) , ext ) return os . path . join ( "document" , filename )
Callable passed to the FileField s upload_to kwarg on Document . file
251,094
def for_user ( self , user ) : qs = SharedMemberQuerySet ( model = self . model , using = self . _db , user = user ) qs = qs . filter ( Q ( author = user ) | Q ( foldershareduser__user = user ) ) return qs . distinct ( ) & self . distinct ( )
All folders the given user can do something with .
251,095
def _parse_list ( cls , args ) : argparser = ArgumentParser ( prog = "cluster list" ) group = argparser . add_mutually_exclusive_group ( ) group . add_argument ( "--id" , dest = "cluster_id" , help = "show cluster with this id" ) group . add_argument ( "--label" , dest = "label" , help = "show cluster with this label" ...
Parse command line arguments to construct a dictionary of cluster parameters that can be used to determine which clusters to list .
251,096
def _parse_cluster_manage_command ( cls , args , action ) : argparser = ArgumentParser ( prog = "cluster_manage_command" ) group = argparser . add_mutually_exclusive_group ( required = True ) group . add_argument ( "--id" , dest = "cluster_id" , help = "execute on cluster with this id" ) group . add_argument ( "--label...
Parse command line arguments for cluster manage commands .
251,097
def _parse_reassign_label ( cls , args ) : argparser = ArgumentParser ( prog = "cluster reassign_label" ) argparser . add_argument ( "destination_cluster" , metavar = "destination_cluster_id_label" , help = "id/label of the cluster to move the label to" ) argparser . add_argument ( "label" , help = "label to be moved f...
Parse command line arguments for reassigning label .
251,098
def reassign_label ( cls , destination_cluster , label ) : conn = Qubole . agent ( version = Cluster . api_version ) data = { "destination_cluster" : destination_cluster , "label" : label } return conn . put ( cls . rest_entity_path + "/reassign-label" , data )
Reassign a label from one cluster to another .
251,099
def _parse_snapshot_restore_command ( cls , args , action ) : argparser = ArgumentParser ( prog = "cluster %s" % action ) group = argparser . add_mutually_exclusive_group ( required = True ) group . add_argument ( "--id" , dest = "cluster_id" , help = "execute on cluster with this id" ) group . add_argument ( "--label"...
Parse command line arguments for snapshot command .