idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
62,100
def get_suffix ( name ) : a = name . count ( "." ) if a : ext = name . split ( "." ) [ - 1 ] if ext in LANGS . keys ( ) : return ext return False else : return False
Check if file name have valid suffix for formatting . if have suffix return it else return False .
62,101
def _raise_for_status ( response ) : message = '' if 400 <= response . status < 500 : message = '%s Client Error: %s' % ( response . status , response . reason ) elif 500 <= response . status < 600 : message = '%s Server Error: %s' % ( response . status , response . reason ) else : return if response . status == 503 : ...
make sure that only crate . exceptions are raised that are defined in the DB - API specification
62,102
def _server_url ( server ) : if not _HTTP_PAT . match ( server ) : server = 'http://%s' % server parsed = urlparse ( server ) url = '%s://%s' % ( parsed . scheme , parsed . netloc ) return url
Normalizes a given server string to an url
62,103
def sql ( self , stmt , parameters = None , bulk_parameters = None ) : if stmt is None : return None data = _create_sql_payload ( stmt , parameters , bulk_parameters ) logger . debug ( 'Sending request to %s with payload: %s' , self . path , data ) content = self . _json_request ( 'POST' , self . path , data = data ) l...
Execute SQL stmt against the crate server .
62,104
def blob_put ( self , table , digest , data ) : response = self . _request ( 'PUT' , _blob_path ( table , digest ) , data = data ) if response . status == 201 : return True if response . status == 409 : return False if response . status in ( 400 , 404 ) : raise BlobLocationNotFoundException ( table , digest ) _raise_fo...
Stores the contents of the file like
62,105
def blob_get ( self , table , digest , chunk_size = 1024 * 128 ) : response = self . _request ( 'GET' , _blob_path ( table , digest ) , stream = True ) if response . status == 404 : raise DigestNotFoundException ( table , digest ) _raise_for_status ( response ) return response . stream ( amt = chunk_size )
Returns a file like object representing the contents of the blob with the given digest .
62,106
def blob_exists ( self , table , digest ) : response = self . _request ( 'HEAD' , _blob_path ( table , digest ) ) if response . status == 200 : return True elif response . status == 404 : return False _raise_for_status ( response )
Returns true if the blob with the given digest exists under the given table .
62,107
def _request ( self , method , path , server = None , ** kwargs ) : while True : next_server = server or self . _get_server ( ) try : response = self . server_pool [ next_server ] . request ( method , path , username = self . username , password = self . password , schema = self . schema , ** kwargs ) redirect_location...
Execute a request to the cluster
62,108
def _json_request ( self , method , path , data ) : response = self . _request ( method , path , data = data ) _raise_for_status ( response ) if len ( response . data ) > 0 : return _json_from_response ( response ) return response . data
Issue request against the crate HTTP API .
62,109
def _get_server ( self ) : with self . _lock : inactive_server_count = len ( self . _inactive_servers ) for i in range ( inactive_server_count ) : try : ts , server , message = heapq . heappop ( self . _inactive_servers ) except IndexError : pass else : if ( ts + self . retry_interval ) > time ( ) : heapq . heappush ( ...
Get server to use for request . Also process inactive server list re - add them after given interval .
62,110
def _drop_server ( self , server , message ) : try : self . _active_servers . remove ( server ) except ValueError : pass else : heapq . heappush ( self . _inactive_servers , ( time ( ) , server , message ) ) logger . warning ( "Removed server %s from active pool" , server ) if not self . _active_servers : raise Connect...
Drop server from active list and adds it to the inactive ones .
62,111
def match ( column , term , match_type = None , options = None ) : return Match ( column , term , match_type , options )
Generates match predicate for fulltext search
62,112
def put ( self , f , digest = None ) : if digest : actual_digest = digest else : actual_digest = self . _compute_digest ( f ) created = self . conn . client . blob_put ( self . container_name , actual_digest , f ) if digest : return created return actual_digest
Upload a blob
62,113
def get ( self , digest , chunk_size = 1024 * 128 ) : return self . conn . client . blob_get ( self . container_name , digest , chunk_size )
Return the contents of a blob
62,114
def delete ( self , digest ) : return self . conn . client . blob_del ( self . container_name , digest )
Delete a blob
62,115
def exists ( self , digest ) : return self . conn . client . blob_exists ( self . container_name , digest )
Check if a blob exists
62,116
def next ( self ) : if self . rows is None : raise ProgrammingError ( "No result available. " + "execute() or executemany() must be called first." ) elif not self . _closed : return next ( self . rows ) else : raise ProgrammingError ( "Cursor closed" )
Return the next row of a query result set respecting if cursor was closed .
62,117
def duration ( self ) : if self . _closed or not self . _result or "duration" not in self . _result : return - 1 return self . _result . get ( "duration" , 0 )
This read - only attribute specifies the server - side duration of a query in milliseconds .
62,118
def rewrite_update ( clauseelement , multiparams , params ) : newmultiparams = [ ] _multiparams = multiparams [ 0 ] if len ( _multiparams ) == 0 : return clauseelement , multiparams , params for _params in _multiparams : newparams = { } for key , val in _params . items ( ) : if ( not isinstance ( val , MutableDict ) or...
change the params to enable partial updates
62,119
def _get_crud_params ( compiler , stmt , ** kw ) : compiler . postfetch = [ ] compiler . insert_prefetch = [ ] compiler . update_prefetch = [ ] compiler . returning = [ ] if compiler . column_keys is None and stmt . parameters is None : return [ ( c , crud . _create_bind_param ( compiler , c , None , required = True ) ...
extract values from crud parameters
62,120
def get_tgt_for ( user ) : if not settings . CAS_PROXY_CALLBACK : raise CasConfigException ( "No proxy callback set in settings" ) try : return Tgt . objects . get ( username = user . username ) except ObjectDoesNotExist : logger . warning ( 'No ticket found for user {user}' . format ( user = user . username ) ) raise ...
Fetch a ticket granting ticket for a given user .
62,121
def get_proxy_ticket_for ( self , service ) : if not settings . CAS_PROXY_CALLBACK : raise CasConfigException ( "No proxy callback set in settings" ) params = { 'pgt' : self . tgt , 'targetService' : service } url = ( urljoin ( settings . CAS_SERVER_URL , 'proxy' ) + '?' + urlencode ( params ) ) page = urlopen ( url ) ...
Verifies CAS 2 . 0 + XML - based authentication ticket .
62,122
def _internal_verify_cas ( ticket , service , suffix ) : params = { 'ticket' : ticket , 'service' : service } if settings . CAS_PROXY_CALLBACK : params [ 'pgtUrl' ] = settings . CAS_PROXY_CALLBACK url = ( urljoin ( settings . CAS_SERVER_URL , suffix ) + '?' + urlencode ( params ) ) page = urlopen ( url ) username = Non...
Verifies CAS 2 . 0 and 3 . 0 XML - based authentication ticket .
62,123
def verify_proxy_ticket ( ticket , service ) : params = { 'ticket' : ticket , 'service' : service } url = ( urljoin ( settings . CAS_SERVER_URL , 'proxyValidate' ) + '?' + urlencode ( params ) ) page = urlopen ( url ) try : response = page . read ( ) tree = ElementTree . fromstring ( response ) if tree [ 0 ] . tag . en...
Verifies CAS 2 . 0 + XML - based proxy ticket .
62,124
def _get_pgtiou ( pgt ) : pgtIou = None retries_left = 5 if not settings . CAS_PGT_FETCH_WAIT : retries_left = 1 while not pgtIou and retries_left : try : return PgtIOU . objects . get ( tgt = pgt ) except PgtIOU . DoesNotExist : if settings . CAS_PGT_FETCH_WAIT : time . sleep ( 1 ) retries_left -= 1 logger . info ( 'D...
Returns a PgtIOU object given a pgt .
62,125
def gateway ( ) : if settings . CAS_GATEWAY == False : raise ImproperlyConfigured ( 'CAS_GATEWAY must be set to True' ) def wrap ( func ) : def wrapped_f ( * args ) : from cas . views import login request = args [ 0 ] try : is_authenticated = request . user . is_authenticated ( ) except TypeError : is_authenticated = r...
Authenticates single sign on session if ticket is available but doesn t redirect to sign in url otherwise .
62,126
def _service_url ( request , redirect_to = None , gateway = False ) : if settings . CAS_FORCE_SSL_SERVICE_URL : protocol = 'https://' else : protocol = ( 'http://' , 'https://' ) [ request . is_secure ( ) ] host = request . get_host ( ) service = protocol + host + request . path if redirect_to : if '?' in service : ser...
Generates application service URL for CAS
62,127
def proxy_callback ( request ) : pgtIou = request . GET . get ( 'pgtIou' ) tgt = request . GET . get ( 'pgtId' ) if not ( pgtIou and tgt ) : logger . info ( 'No pgtIou or tgt found in request.GET' ) return HttpResponse ( 'No pgtIOO' , content_type = "text/plain" ) try : PgtIOU . objects . create ( tgt = tgt , pgtIou = ...
Handles CAS 2 . 0 + XML - based proxy callback call . Stores the proxy granting ticket in the database for future use .
62,128
def objectify ( func ) : @ functools . wraps ( func ) def wrapper ( * args , ** kwargs ) : try : payload = func ( * args , ** kwargs ) except requests . exceptions . ConnectionError as e : raise InternetConnectionError ( e ) return EventbriteObject . create ( payload ) return wrapper
Converts the returned value from a models . Payload to a models . EventbriteObject . Used by the access methods of the client . Eventbrite object
62,129
def get_user ( self , user_id = None ) : if user_id : return self . get ( '/users/{0}/' . format ( user_id ) ) return self . get ( '/users/me/' )
Returns a user for the specified user as user .
62,130
def get_event_attendees ( self , event_id , status = None , changed_since = None ) : data = { } if status : data [ 'status' ] = status if changed_since : data [ 'changed_since' ] = changed_since return self . get ( "/events/{0}/attendees/" . format ( event_id ) , data = data )
Returns a paginated response with a key of attendees containing a list of attendee .
62,131
def webhook_to_object ( self , webhook ) : if isinstance ( webhook , string_type ) : webhook = json . dumps ( webhook ) if not isinstance ( webhook , dict ) : webhook = get_webhook_from_request ( webhook ) try : webhook [ 'api_url' ] except KeyError : raise InvalidWebhook payload = self . get ( webhook [ 'api_url' ] ) ...
Converts JSON sent by an Eventbrite Webhook to the appropriate Eventbrite object .
62,132
def get_params_from_page ( path , file_name , method_count ) : file_name = file_name . replace ( ".rst" , "" ) file_path = "{0}/../_build/html/endpoints/{1}/index.html" . format ( path , file_name ) soup = bs4 . BeautifulSoup ( open ( file_path ) ) section = soup . find_all ( 'div' , class_ = 'section' ) [ method_count...
This function accesses the rendered content . We must do this because how the params are not defined in the docs but rather the rendered HTML
62,133
def process_request ( self , request ) : restricted_request_uri = request . path . startswith ( reverse ( 'admin:index' ) or "cms-toolbar-login" in request . build_absolute_uri ( ) ) if restricted_request_uri and request . method == 'POST' : if AllowedIP . objects . count ( ) > 0 : if AllowedIP . objects . filter ( ip_...
Check if the request is made form an allowed IP
62,134
def get_settings ( editor_override = None ) : flavor = getattr ( settings , "DJANGO_WYSIWYG_FLAVOR" , "yui" ) if editor_override is not None : flavor = editor_override return { "DJANGO_WYSIWYG_MEDIA_URL" : getattr ( settings , "DJANGO_WYSIWYG_MEDIA_URL" , urljoin ( settings . STATIC_URL , flavor ) + '/' ) , "DJANGO_WYS...
Utility function to retrieve settings . py values with defaults
62,135
def get_auth ( self ) : return ( self . _cfgparse . get ( self . _section , 'username' ) , self . _cfgparse . get ( self . _section , 'password' ) )
Returns username from the configfile .
62,136
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 .
62,137
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 .
62,138
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 .
62,139
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 .
62,140
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 ..
62,141
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 .
62,142
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 .
62,143
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 .
62,144
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 .
62,145
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 .
62,146
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 .
62,147
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 .
62,148
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 .
62,149
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 .
62,150
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 .
62,151
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 .
62,152
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 .
62,153
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 .
62,154
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 .
62,155
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 .
62,156
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 .
62,157
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 .
62,158
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 .
62,159
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 .
62,160
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 .
62,161
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 .
62,162
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 .
62,163
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!
62,164
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
62,165
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
62,166
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
62,167
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
62,168
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
62,169
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
62,170
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
62,171
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
62,172
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
62,173
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
62,174
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
62,175
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
62,176
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
62,177
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
62,178
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
62,179
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
62,180
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
62,181
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
62,182
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
62,183
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
62,184
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
62,185
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
62,186
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
62,187
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
62,188
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
62,189
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
62,190
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
62,191
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
62,192
def restart ( self , * args , ** kwargs ) : self . stop ( ) try : self . start ( * args , ** kwargs ) except IOError : raise
Restart the daemon
62,193
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
62,194
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
62,195
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 .
62,196
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 .
62,197
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 .
62,198
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 .
62,199
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 .