idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
38,600 | def get ( self , cluster_id , show_progress = False ) : url = ( '/clusters/%(cluster_id)s?%(params)s' % { "cluster_id" : cluster_id , "params" : parse . urlencode ( { "show_progress" : show_progress } ) } ) return self . _get ( url , 'cluster' ) | Get information about a Cluster . |
38,601 | def update ( self , cluster_id , name = NotUpdated , description = NotUpdated , is_public = NotUpdated , is_protected = NotUpdated , shares = NotUpdated ) : data = { } self . _copy_if_updated ( data , name = name , description = description , is_public = is_public , is_protected = is_protected , shares = shares ) return self . _patch ( '/clusters/%s' % cluster_id , data ) | Update a Cluster . |
38,602 | def verification_update ( self , cluster_id , status ) : data = { 'verification' : { 'status' : status } } return self . _patch ( "/clusters/%s" % cluster_id , data ) | Start a verification for a Cluster . |
38,603 | def create ( self , name , plugin_name , plugin_version , cluster_template_id = None , default_image_id = None , is_transient = None , description = None , cluster_configs = None , node_groups = None , user_keypair_id = None , anti_affinity = None , net_id = None , count = None , use_autoconfig = None , shares = None , is_public = None , is_protected = None ) : data = { 'name' : name , 'plugin_name' : plugin_name , 'plugin_version' : plugin_version , } return self . _do_create ( data , cluster_template_id , default_image_id , is_transient , description , cluster_configs , node_groups , user_keypair_id , anti_affinity , net_id , count , use_autoconfig , shares , is_public , is_protected , api_ver = 2 ) | Launch a Cluster . |
38,604 | def _get_command ( classes ) : commands = { } setup_file = os . path . join ( os . path . abspath ( os . path . join ( os . path . dirname ( __file__ ) , '../..' ) ) , 'setup.cfg' ) for line in open ( setup_file , 'r' ) : for cl in classes : if cl in line : commands [ cl ] = line . split ( ' = ' ) [ 0 ] . strip ( ) . replace ( '_' , ' ' ) return commands | Associates each command class with command depending on setup . cfg |
38,605 | def get_json ( response ) : json_field_or_function = getattr ( response , 'json' , None ) if callable ( json_field_or_function ) : return response . json ( ) else : return jsonutils . loads ( response . content ) | Provide backward compatibility with old versions of requests library . |
38,606 | def create ( self , name , data ) : return self . _update ( '/job-binary-internals/%s' % urlparse . quote ( name . encode ( 'utf-8' ) ) , data , 'job_binary_internal' , dump_json = False ) | Create a Job Binary Internal . |
38,607 | def update ( self , job_binary_id , name = NotUpdated , is_public = NotUpdated , is_protected = NotUpdated ) : data = { } self . _copy_if_updated ( data , name = name , is_public = is_public , is_protected = is_protected ) return self . _patch ( '/job-binary-internals/%s' % job_binary_id , data ) | Update a Job Binary Internal . |
38,608 | def autoconvert ( string ) : for fn in ( boolify , int , float ) : try : return fn ( string ) except ValueError : pass return string | Try to convert variables into datatypes . |
38,609 | def call_plugin ( plugin , f , * args , ** kwargs ) : try : getattr ( plugin , f ) except AttributeError : return None if kwargs : getattr ( plugin , f ) ( * args , ** kwargs ) else : return getattr ( plugin , f ) ( * args ) | Calls function f from plugin returns None if plugin does not implement f . |
38,610 | def create ( self , job_id , cluster_id , input_id = None , output_id = None , configs = None , interface = None , is_public = None , is_protected = None ) : url = "/jobs/%s/execute" % job_id data = { "cluster_id" : cluster_id , } self . _copy_if_defined ( data , input_id = input_id , output_id = output_id , job_configs = configs , interface = interface , is_public = is_public , is_protected = is_protected ) return self . _create ( url , data , 'job_execution' ) | Launch a Job . |
38,611 | def update ( self , obj_id , is_public = NotUpdated , is_protected = NotUpdated ) : data = { } self . _copy_if_updated ( data , is_public = is_public , is_protected = is_protected ) return self . _patch ( '/job-executions/%s' % obj_id , data ) | Update a Job Execution . |
38,612 | def visitTerminal ( self , ctx ) : text = str ( super ( ) . visitTerminal ( ctx ) ) quotes = [ "'" , '"' ] if not ( text [ 0 ] in quotes and text [ - 1 ] in quotes ) : text = text . lower ( ) return Terminal . from_text ( text , ctx ) | Converts case insensitive keywords and identifiers to lowercase Identifiers in quotes are not lowercased even though there is case sensitivity in quotes for identifiers to prevent lowercasing quoted values . |
38,613 | def list ( self , search_opts = None ) : query = base . get_query_string ( search_opts ) return self . _list ( '/plugins%s' % query , 'plugins' ) | Get a list of Plugins . |
38,614 | def convert_to_cluster_template ( self , plugin_name , hadoop_version , template_name , filecontent ) : resp = self . api . post ( '/plugins/%s/%s/convert-config/%s' % ( plugin_name , hadoop_version , urlparse . quote ( template_name ) ) , data = filecontent ) if resp . status_code != 202 : raise RuntimeError ( 'Failed to upload template file for plugin "%s"' ' and version "%s"' % ( plugin_name , hadoop_version ) ) else : return base . get_json ( resp ) [ 'cluster_template' ] | Convert to cluster template |
38,615 | def create ( self , name , type , mains = None , libs = None , description = None , interface = None , is_public = None , is_protected = None ) : data = { 'name' : name , 'type' : type } self . _copy_if_defined ( data , description = description , mains = mains , libs = libs , interface = interface , is_public = is_public , is_protected = is_protected ) return self . _create ( '/jobs' , data , 'job' ) | Create a Job . |
38,616 | def list ( self , search_opts = None , limit = None , marker = None , sort_by = None , reverse = None ) : query = base . get_query_string ( search_opts , limit = limit , marker = marker , sort_by = sort_by , reverse = reverse ) url = "/jobs%s" % query return self . _page ( url , 'jobs' , limit ) | Get a list of Jobs . |
38,617 | def update ( self , job_id , name = NotUpdated , description = NotUpdated , is_public = NotUpdated , is_protected = NotUpdated ) : data = { } self . _copy_if_updated ( data , name = name , description = description , is_public = is_public , is_protected = is_protected ) return self . _patch ( '/jobs/%s' % job_id , data ) | Update a Job . |
38,618 | def _query_for_reverse_geocoding ( lat , lng ) : return "{0:f},{1:f}" . format ( Decimal ( str ( lat ) ) , Decimal ( str ( lng ) ) ) | Given a lat & lng what s the string search query . |
38,619 | def geocode ( self , query , ** kwargs ) : if six . PY2 : try : query = unicode ( query ) except UnicodeDecodeError : raise InvalidInputError ( bad_value = query ) if not isinstance ( query , six . text_type ) : raise InvalidInputError ( bad_value = query ) data = { 'q' : query , 'key' : self . key } data . update ( kwargs ) url = self . url response = requests . get ( url , params = data ) if ( response . status_code == 402 or response . status_code == 429 ) : reset_time = datetime . utcfromtimestamp ( response . json ( ) [ 'rate' ] [ 'reset' ] ) raise RateLimitExceededError ( reset_to = int ( response . json ( ) [ 'rate' ] [ 'limit' ] ) , reset_time = reset_time ) elif response . status_code == 500 : raise UnknownError ( "500 status code from API" ) try : response_json = response . json ( ) except ValueError : raise UnknownError ( "Non-JSON result from server" ) if 'results' not in response_json : raise UnknownError ( "JSON from API doesn't have a 'results' key" ) return floatify_latlng ( response_json [ 'results' ] ) | Given a string to search for return the results from OpenCage s Geocoder . |
38,620 | def reverse_geocode ( self , lat , lng , ** kwargs ) : return self . geocode ( _query_for_reverse_geocoding ( lat , lng ) , ** kwargs ) | Given a latitude & longitude return an address for that point from OpenCage s Geocoder . |
38,621 | def acquire ( self ) : self . _condition . acquire ( ) try : if self . _maxsize is not None and self . _block : while not self . _pool and self . _nconnections == self . _maxsize : self . _condition . wait ( timeout = None ) while self . _pool : pooledconn = self . _pool . pop ( 0 ) if self . _idlettl is not None and ( pooledconn . released + self . _idlettl ) < time . time ( ) : pooledconn . connection . close ( ) self . _nconnections -= 1 else : return pooledconn . connection connection = self . _dbapi2 . connect ( * ( ) , ** self . _connection_args . copy ( ) ) self . _nconnections += 1 return connection finally : self . _condition . release ( ) | Get a new connection from the pool . This will return an existing connection if one is available in the pool or create a new connection . |
38,622 | def release ( self , connection ) : try : connection . rollback ( ) except self . _dbapi2 . Error : self . _close ( connection ) return self . _condition . acquire ( ) try : if self . _maxsize is None or self . _maxsize > len ( self . _pool ) : self . _pool . append ( PooledConnection ( connection , time . time ( ) ) ) self . _condition . notify ( ) else : self . _close ( connection ) finally : self . _condition . release ( ) | Return a connection back to the pool . |
38,623 | def finalize ( self ) : self . _condition . acquire ( ) try : if self . _nconnections != len ( self . _pool ) : warnings . warn ( 'finalize() called with unreleased connections' , RuntimeWarning , 2 ) while self . _pool : self . _close ( self . _pool . pop ( ) . connection ) self . _nconnections = 0 finally : self . _condition . release ( ) | Release all connections contained in the pool . |
38,624 | def _dict_merge ( dct , merge_dct ) : for k , v in merge_dct . items ( ) : if ( k in dct and isinstance ( dct [ k ] , dict ) and isinstance ( merge_dct [ k ] , collections . Mapping ) ) : _dict_merge ( dct [ k ] , merge_dct [ k ] ) else : dct [ k ] = merge_dct [ k ] | Recursive dict merge . |
38,625 | def _parse_schema ( schema , method ) : if method and schema . get ( 'readOnly' , False ) : return _READONLY_PROPERTY if 'allOf' in schema : schema_ = copy . deepcopy ( schema [ 'allOf' ] [ 0 ] ) for x in schema [ 'allOf' ] [ 1 : ] : _dict_merge ( schema_ , x ) return _parse_schema ( schema_ , method ) if 'oneOf' in schema : return _parse_schema ( schema [ 'oneOf' ] [ 0 ] , method ) if 'enum' in schema : return schema [ 'enum' ] [ 0 ] schema_type = schema . get ( 'type' , 'object' ) if schema_type == 'array' : if 'oneOf' in schema [ 'items' ] : return [ _parse_schema ( x , method ) for x in schema [ 'items' ] [ 'oneOf' ] ] return [ _parse_schema ( schema [ 'items' ] , method ) ] if schema_type == 'object' : if method and all ( v . get ( 'readOnly' , False ) for v in schema [ 'properties' ] . values ( ) ) : return _READONLY_PROPERTY results = [ ] for name , prop in schema . get ( 'properties' , { } ) . items ( ) : result = _parse_schema ( prop , method ) if result != _READONLY_PROPERTY : results . append ( ( name , result ) ) return collections . OrderedDict ( results ) if ( schema_type , schema . get ( 'format' ) ) in _TYPE_MAPPING : return _TYPE_MAPPING [ ( schema_type , schema . get ( 'format' ) ) ] return _TYPE_MAPPING [ ( schema_type , None ) ] | Convert a Schema Object to a Python object . |
38,626 | def _example ( media_type_objects , method = None , endpoint = None , status = None , nb_indent = 0 ) : indent = ' ' extra_indent = indent * nb_indent if method is not None : method = method . upper ( ) else : try : status_text = http_status_codes [ int ( status ) ] except ( ValueError , KeyError ) : status_text = '-' for content_type , content in media_type_objects . items ( ) : examples = content . get ( 'examples' ) example = content . get ( 'example' ) if examples is None : examples = { } if not example : if content_type != 'application/json' : LOG . info ( 'skipping non-JSON example generation.' ) continue example = _parse_schema ( content [ 'schema' ] , method = method ) if method is None : examples [ 'Example response' ] = { 'value' : example , } else : examples [ 'Example request' ] = { 'value' : example , } for example in examples . values ( ) : if not isinstance ( example [ 'value' ] , six . string_types ) : example [ 'value' ] = json . dumps ( example [ 'value' ] , indent = 4 , separators = ( ',' , ': ' ) ) for example_name , example in examples . items ( ) : if 'summary' in example : example_title = '{example_name} - {example[summary]}' . format ( ** locals ( ) ) else : example_title = example_name yield '' yield '{extra_indent}**{example_title}:**' . format ( ** locals ( ) ) yield '' yield '{extra_indent}.. sourcecode:: http' . format ( ** locals ( ) ) yield '' if method : yield '{extra_indent}{indent}{method} {endpoint} HTTP/1.1' . format ( ** locals ( ) ) yield '{extra_indent}{indent}Host: example.com' . format ( ** locals ( ) ) yield '{extra_indent}{indent}Content-Type: {content_type}' . format ( ** locals ( ) ) else : yield '{extra_indent}{indent}HTTP/1.1 {status} {status_text}' . format ( ** locals ( ) ) yield '{extra_indent}{indent}Content-Type: {content_type}' . format ( ** locals ( ) ) yield '' for example_line in example [ 'value' ] . splitlines ( ) : yield '{extra_indent}{indent}{example_line}' . format ( ** locals ( ) ) yield '' | Format examples in Media Type Object openapi v3 to HTTP request or HTTP response example . If method and endpoint is provided this fonction prints a request example else status should be provided to print a response example . |
38,627 | def connect ( self ) : if ( self . __ser is not None ) : serial = importlib . import_module ( "serial" ) if self . __stopbits == 0 : self . __ser . stopbits = serial . STOPBITS_ONE elif self . __stopbits == 1 : self . __ser . stopbits = serial . STOPBITS_TWO elif self . __stopbits == 2 : self . __ser . stopbits = serial . STOPBITS_ONE_POINT_FIVE if self . __parity == 0 : self . __ser . parity = serial . PARITY_EVEN elif self . __parity == 1 : self . __ser . parity = serial . PARITY_ODD elif self . __parity == 2 : self . __ser . parity = serial . PARITY_NONE self . __ser = serial . Serial ( self . serialPort , self . __baudrate , timeout = self . __timeout , parity = self . __ser . parity , stopbits = self . __ser . stopbits , xonxoff = 0 , rtscts = 0 ) self . __ser . writeTimeout = self . __timeout if ( self . __tcpClientSocket is not None ) : self . __tcpClientSocket . settimeout ( 5 ) self . __tcpClientSocket . connect ( ( self . __ipAddress , self . __port ) ) self . __connected = True self . __thread = threading . Thread ( target = self . __listen , args = ( ) ) self . __thread . start ( ) | Connects to a Modbus - TCP Server or a Modbus - RTU Slave with the given Parameters |
38,628 | def close ( self ) : if ( self . __ser is not None ) : self . __ser . close ( ) if ( self . __tcpClientSocket is not None ) : self . __stoplistening = True self . __tcpClientSocket . shutdown ( socket . SHUT_RDWR ) self . __tcpClientSocket . close ( ) self . __connected = False | Closes Serial port or TCP - Socket connection |
38,629 | def run_plugins ( context_obj , boto3_clients ) : def print_if_verbose ( message ) : if context_obj . verbose : print ( message ) service_name = os . path . basename ( sys . argv [ 0 ] ) . replace ( ".py" , "" ) try : import plugins except ImportError : print_if_verbose ( "no plugins detected." ) return else : for plugin_importer , plugin_name , plugin_ispkg in pkgutil . iter_modules ( plugins . __path__ ) : if plugin_ispkg : plugin_package = importlib . import_module ( "plugins.{}" . format ( plugin_name ) ) for importer , modname , ispkg in pkgutil . iter_modules ( plugin_package . __path__ ) : plugin_module = importlib . import_module ( "plugins.{}.{}" . format ( plugin_name , modname ) ) for name , obj in inspect . getmembers ( plugin_module ) : if inspect . isclass ( obj ) and obj . __name__ == "EFPlugin" : plugin_class = getattr ( plugin_module , name ) plugin_instance = plugin_class ( context = context_obj , clients = boto3_clients ) if plugin_instance . service == service_name : print_if_verbose ( "plugin '{}' loaded" . format ( plugin_name ) ) if not context_obj . commit : print_if_verbose ( "dryrun: skipping plugin execution." ) else : try : plugin_instance . run ( ) except AttributeError : print ( "error executing plugin '{}'" . format ( modname ) ) | Executes all loaded plugins designated for the service calling the function . |
38,630 | def diff_string_templates ( string_a , string_b ) : s1 = string_a . strip ( ) . splitlines ( ) s2 = string_b . strip ( ) . splitlines ( ) diffs = unified_diff ( s2 , s1 , fromfile = 'deployed' , tofile = 'local' , lineterm = '' ) return '\n' . join ( diffs ) | Determine the diff of two strings . Return an empty string if the strings are identical and the diff output string if they are not . |
38,631 | def render_local_template ( service_name , environment , repo_root , template_file ) : cmd = 'cd {} && ef-cf {} {} --devel --verbose' . format ( repo_root , template_file , environment ) p = subprocess . Popen ( cmd , shell = True , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) stdout , stderr = p . communicate ( ) if p . returncode != 0 : stderr = indentify ( '\n{}' . format ( stderr ) ) stdout = indentify ( '\n{}' . format ( stdout ) ) raise Exception ( 'Service: `{}`, Env: `{}`, Msg: `{}{}`' . format ( service_name , environment , stderr , stdout ) ) logger . debug ( 'Rendered template for `%s` in `%s`' , template_file , environment ) r = re . match ( r".*(^{.*^})$" , stdout , re . MULTILINE | re . DOTALL ) return jsonify ( json . loads ( r . group ( 1 ) ) ) | Render a given service s template for a given environment and return it |
38,632 | def fetch_current_cloudformation_template ( service_name , environment , cf_client ) : stack_name = get_stack_name ( environment , service_name ) logger . debug ( 'Fetching template for `%s`' , stack_name ) result = cf_client . get_template ( StackName = stack_name ) return jsonify ( result [ 'TemplateBody' ] ) | Fetch the currently - deployed template for the given service in the given environment and return it . |
38,633 | def diff_sevice_by_text ( service_name , service , environment , cf_client , repo_root ) : global ret_code logger . info ( 'Investigating textual diff for `%s`:`%s` in environment `%s`' , service [ 'type' ] , service_name , environment ) try : local_template = render_local_template ( service_name , environment , repo_root , service [ 'template_file' ] ) current_template = fetch_current_cloudformation_template ( service_name , environment , cf_client ) except Exception as e : ret_code = 2 logger . error ( e ) return ret = diff_string_templates ( local_template , current_template ) if not ret : logger . info ( 'Deployed service `%s` in environment `%s` matches ' 'the local template.' , service_name , environment ) else : ret_code = 1 logger . error ( 'Service `%s` in environment `%s` differs from ' 'the local template.' , service_name , environment ) logger . info ( 'Change details:\n %s' , indentify ( ret ) ) | Render the local template and compare it to the template that was last applied in the target environment . |
38,634 | def diff_sevice_by_changeset ( service_name , service , environment , cf_client , repo_root ) : global ret_code logger . info ( 'Investigating changeset for `%s`:`%s` in environment `%s`' , service [ 'type' ] , service_name , environment ) delete_any_existing_changesets ( cf_client , service_name , environment ) try : changeset = generate_changeset ( service_name , environment , repo_root , service [ 'template_file' ] ) except Exception as e : ret_code = 2 logger . error ( e ) return wait_for_changeset_creation ( cf_client , changeset [ 'Id' ] , changeset [ 'StackId' ] ) logger . info ( 'Created Changeset ID: `%s`' , changeset [ 'Id' ] ) desc = cf_client . describe_change_set ( ChangeSetName = changeset [ 'Id' ] , StackName = changeset [ 'StackId' ] ) cf_client . delete_change_set ( ChangeSetName = changeset [ 'Id' ] , StackName = changeset [ 'StackId' ] ) if changeset_is_empty ( desc ) : logger . info ( 'Deployed service `%s` in environment `%s` matches ' 'the local template.' , service_name , environment ) else : ret_code = 1 logger . error ( 'Service `%s` in environment `%s` differs from ' 'the local template.' , service_name , environment ) details = jsonify ( desc [ 'Changes' ] ) logger . info ( 'Change details:\n %s' , indentify ( details ) ) | If an ef - cf call fails the error will be logged the retcode set to 2 but the function will run to completion and return the list of non - error results . |
38,635 | def get_cloudformation_client ( service_name , environment_name ) : region = service_registry . service_region ( service_name ) if whereami ( ) == 'ec2' : profile = None else : profile = get_account_alias ( environment_name ) clients = create_aws_clients ( region , profile , 'cloudformation' ) return clients [ 'cloudformation' ] | Given a service name and an environment name return a boto CloudFormation client object . |
38,636 | def evaluate_service_changes ( services , envs , repo_root , func ) : for service_name , service in services . iteritems ( ) : for env_category in service [ 'environments' ] : if env_category not in get_env_categories ( envs ) : logger . debug ( 'Skipping not-included environment `%s` for service `%s`' , env_category , service_name ) continue environment = generate_test_environment_name ( env_category ) cf_client = get_cloudformation_client ( service_name , environment ) func ( service_name , service , environment , cf_client , repo_root ) | Given a dict of services and a list of environments apply the diff function to evaluate the differences between the target environments and the rendered templates . |
38,637 | def get_matching_service_template_file ( service_name , template_files ) : service_name = service_name . split ( '.' ) [ 0 ] if service_name in template_files : return template_files [ service_name ] return None | Return the template file that goes with the given service name or return None if there s no match . Subservices return the parent service s file . |
38,638 | def inverse_tile_2d ( input , k_x , k_y , name ) : batch_size , h , w , c = input . get_shape ( ) . as_list ( ) if batch_size is None : batch_size = - 1 assert w % k_x == 0 and h % k_y == 0 with tf . variable_scope ( name ) as scope : tmp = input tmp = tf . reshape ( tmp , ( batch_size , int ( h * k_y ) , w , int ( c * k_x ) ) ) tmp = tf . transpose ( tmp , [ 0 , 2 , 1 , 3 ] ) tmp = tf . reshape ( tmp , ( batch_size , w , h , int ( c * k_y * k_x ) ) ) tmp = tf . transpose ( tmp , [ 0 , 2 , 1 , 3 ] ) return tmp | An inverse tiling layer . |
38,639 | def feature_passthrough ( early_feat , late_feat , filters , name , kernel_size = ( 1 , 1 ) ) : _ , h_early , w_early , c_early = early_feat . get_shape ( ) . as_list ( ) _ , h_late , w_late , c_late = late_feat . get_shape ( ) . as_list ( ) s_x = int ( w_early / w_late ) s_y = int ( h_early / h_late ) assert h_late * s_y == h_early and w_late * s_x == w_early with tf . variable_scope ( name ) as scope : early_conv = tf . layers . conv2d ( early_feat , filters = filters , kernel_size = ( s_x * kernel_size [ 0 ] , s_y * kernel_size [ 1 ] ) , strides = ( s_x , s_y ) , padding = "same" ) late_conv = tf . layers . conv2d ( late_feat , filters = filters , kernel_size = kernel_size , strides = ( 1 , 1 ) , padding = "same" ) return early_conv + late_conv | A feature passthrough layer inspired by yolo9000 and the inverse tiling layer . |
38,640 | def upsampling_feature_passthrough ( early_feat , late_feat , filters , name , kernel_size = ( 1 , 1 ) ) : _ , h_early , w_early , c_early = early_feat . get_shape ( ) . as_list ( ) _ , h_late , w_late , c_late = late_feat . get_shape ( ) . as_list ( ) s_x = int ( w_early / w_late ) s_y = int ( h_early / h_late ) assert h_late * s_y == h_early and w_late * s_x == w_early with tf . variable_scope ( name ) as scope : tiled = tile_2d ( late_feat , s_x , s_y , "tile_2d" , reorder_required = False ) concated = tf . concat ( [ early_feat , tiled ] , axis = - 1 ) return tf . layers . conv2d ( concated , filters = filters , kernel_size = kernel_size , strides = ( 1 , 1 ) , padding = "same" ) | An upsampling feature passthrough layer inspired by yolo9000 and the tiling layer . |
38,641 | def load ( self ) : try : with open ( self . _ef_site_config , 'r' ) as yml_file : return yaml . safe_load ( yml_file ) except ( IOError , yaml . parser . ParserError ) as error : print ( "Error: {}" . format ( error ) , file = sys . stderr ) sys . exit ( 1 ) | Loads the config |
38,642 | def interpolate_loss ( labels , loss1 , loss2 , interpolation_values ) : with tf . variable_scope ( "interpolate_focus_loss" ) : t = tf . reduce_sum ( labels * interpolation_values , axis = - 1 ) return ( 1 - t ) * loss1 + t * loss2 | Interpolate two losses linearly . |
38,643 | def mask_loss ( input_tensor , binary_tensor ) : with tf . variable_scope ( "mask_loss" ) : mask = tf . cast ( tf . cast ( binary_tensor , tf . bool ) , tf . float32 ) return input_tensor * mask | Mask a loss by using a tensor filled with 0 or 1 . |
38,644 | def mean_on_masked ( loss , mask , epsilon = 1e-8 , axis = None ) : mask = tf . cast ( tf . cast ( mask , tf . bool ) , tf . float32 ) active_pixels = tf . reduce_sum ( mask ) active_pixels = tf_if ( tf . equal ( active_pixels , 0 ) , epsilon , active_pixels ) return tf . reduce_sum ( loss , axis = axis ) / active_pixels | Average a loss correctly when it was masked . |
38,645 | def mask_and_mean_loss ( input_tensor , binary_tensor , axis = None ) : return mean_on_masked ( mask_loss ( input_tensor , binary_tensor ) , binary_tensor , axis = axis ) | Mask a loss by using a tensor filled with 0 or 1 and average correctly . |
38,646 | def variance_corrected_loss ( loss , sigma_2 = None ) : with tf . variable_scope ( "variance_corrected_loss" ) : sigma_cost = 0 if sigma_2 is None : sigma = tf . get_variable ( name = "sigma" , dtype = tf . float32 , initializer = tf . constant ( 1.0 ) , trainable = True ) sigma_2 = tf . pow ( sigma , 2 ) tf . summary . scalar ( "sigma2" , sigma_2 ) sigma_cost = tf . log ( sigma_2 + 1.0 ) return 0.5 / sigma_2 * loss + sigma_cost | Create a variance corrected loss . |
38,647 | def focus_loss ( labels , probs , loss , gamma ) : with tf . variable_scope ( "focus_loss" ) : p_t = tf . reduce_sum ( probs * labels , axis = - 1 ) focal_factor = tf . pow ( 1.0 - p_t , gamma ) if gamma > 0 else 1 return tf . stop_gradient ( focal_factor ) * loss | Calculate the alpha balanced focal loss . |
38,648 | def get_unique_name ( self , prefix ) : ident = sum ( t . startswith ( prefix ) for t , _ in self . layers . items ( ) ) + 1 return '%s_%d' % ( prefix , ident ) | Returns an index - suffixed unique name for the given prefix . This is used for auto - generating layer names based on the type - prefix . |
38,649 | def make_var ( self , op_name , name , shape ) : if op_name in self . weights and name in self . weights [ op_name ] : if self . verbose : print ( "Using: {} {}" . format ( op_name , name ) ) initializer = tf . constant ( self . weights [ op_name ] [ name ] , shape = shape ) return tf . get_variable ( name , initializer = initializer , trainable = self . trainable ) return tf . get_variable ( name , shape , trainable = self . trainable ) | Creates a new TensorFlow variable . |
38,650 | def write_data ( hyper_params , mode , sequence , num_threads ) : if not isinstance ( sequence , Sequence ) and not ( callable ( getattr ( sequence , "__getitem__" , None ) ) and callable ( getattr ( sequence , "__len__" , None ) ) ) : raise ValueError ( "sequence must be tf.keras.utils.Sequence or a subtype or implement __len__(self) and __getitem__(self, idx)" ) prefix = os . path . join ( hyper_params . train . get ( "tf_records_path" , "tfrecords" ) , mode ) prefix = prefix . replace ( "\\" , "/" ) data_tmp_folder = "/" . join ( prefix . split ( "/" ) [ : - 1 ] ) if not os . path . exists ( data_tmp_folder ) : os . makedirs ( data_tmp_folder ) args = [ ( hyper_params , sequence , num_threads , i , ( prefix + "_%d.tfrecords" ) % i ) for i in range ( num_threads ) ] sample_feature , sample_label = sequence [ 0 ] config = { "num_threads" : num_threads } for k in sample_feature . keys ( ) : config [ "feature_" + k ] = { "shape" : sample_feature [ k ] . shape [ 1 : ] , "dtype" : sample_feature [ k ] . dtype . name } for k in sample_label . keys ( ) : config [ "label_" + k ] = { "shape" : sample_label [ k ] . shape [ 1 : ] , "dtype" : sample_label [ k ] . dtype . name } with open ( prefix + '_config.json' , 'w' ) as outfile : json . dump ( config , outfile ) pool = Pool ( processes = num_threads ) pool . map ( _write_tf_record_pool_helper , args ) | Write a tf record containing a feature dict and a label dict . |
38,651 | def account_id ( self , value ) : if type ( value ) is not str : raise TypeError ( "commit value must be string" ) self . _account_id = value | Sets the current account id |
38,652 | def learn ( self , steps = 1 , ** kwargs ) : for i in range ( steps ) : self . step ( ** kwargs ) | Train the model using the environment and the agent . |
38,653 | def fail ( message , exception_data = None ) : print ( message , file = sys . stderr ) if exception_data : print ( repr ( exception_data ) ) sys . exit ( 1 ) | Print a failure message and exit nonzero |
38,654 | def is_in_virtualbox ( ) : if not isfile ( __VIRT_WHAT ) or not access ( __VIRT_WHAT , X_OK ) : raise IOError ( "virt-what not available" ) try : return subprocess . check_output ( [ "sudo" , "-n" , __VIRT_WHAT ] ) . split ( '\n' ) [ 0 : 2 ] == __VIRT_WHAT_VIRTUALBOX_WITH_KVM except subprocess . CalledProcessError as e : raise IOError ( "virt-what failed execution with {}" . format ( e ) ) | Is the current environment a virtualbox instance? Returns a boolean Raises IOError if the necessary tooling isn t available |
38,655 | def sum_abs_distance ( labels , preds ) : with tf . variable_scope ( "sum_abs_distance" ) : return tf . reduce_sum ( tf . abs ( preds - labels ) , axis = - 1 ) | Compute the sum of abs distances . |
38,656 | def l1_distance ( labels , preds ) : with tf . variable_scope ( "l1_distance" ) : return tf . norm ( preds - labels , ord = 1 ) | Compute the l1_distance . |
38,657 | def smooth_l1_distance ( labels , preds , delta = 1.0 ) : with tf . variable_scope ( "smooth_l1" ) : return tf . reduce_sum ( tf . losses . huber_loss ( labels = labels , predictions = preds , delta = delta , loss_collection = None , reduction = tf . losses . Reduction . NONE ) , axis = - 1 ) | Compute the smooth l1_distance . |
38,658 | def l2_distance ( labels , preds ) : with tf . variable_scope ( "l2_distance" ) : return tf . norm ( preds - labels , ord = 2 ) | Compute the l2_distance . |
38,659 | def cross_entropy ( labels , logits ) : with tf . variable_scope ( "cross_entropy" ) : return tf . nn . softmax_cross_entropy_with_logits ( labels = labels , logits = logits ) | Calculate the cross_entropy . |
38,660 | def alert_policy_exists ( self , policy_name ) : if next ( ( policy for policy in self . all_alerts if policy [ 'name' ] == policy_name ) , False ) : return True | Check to see if an alert policy exists in NewRelic . Return True if so False if not |
38,661 | def create_alert_policy ( self , policy_name ) : policy_data = { 'policy' : { 'incident_preference' : 'PER_POLICY' , 'name' : policy_name } } create_policy = requests . post ( 'https://api.newrelic.com/v2/alerts_policies.json' , headers = self . auth_header , data = json . dumps ( policy_data ) ) create_policy . raise_for_status ( ) policy_id = create_policy . json ( ) [ 'policy' ] [ 'id' ] self . refresh_all_alerts ( ) return policy_id | Creates an alert policy in NewRelic |
38,662 | def element_href ( name ) : if name : element = fetch_meta_by_name ( name ) if element . href : return element . href | Get specified element href by element name |
38,663 | def element_as_json ( name ) : if name : element = fetch_json_by_name ( name ) if element . json : return element . json | Get specified element json data by name |
38,664 | def element_as_json_with_filter ( name , _filter ) : if name : element_href = element_href_use_filter ( name , _filter ) if element_href : return element_by_href_as_json ( element_href ) | Get specified element json data by name with filter . Filter can be any valid element type . |
38,665 | def element_href_use_wildcard ( name ) : if name : element = fetch_meta_by_name ( name , exact_match = False ) return element . json | Get element href using a wildcard rather than matching only on the name field . This will likely return multiple results . |
38,666 | def element_href_use_filter ( name , _filter ) : if name and _filter : element = fetch_meta_by_name ( name , filter_context = _filter ) if element . json : return element . json . pop ( ) . get ( 'href' ) | Get element href using filter |
38,667 | def element_by_href_as_json ( href , params = None ) : if href : element = fetch_json_by_href ( href , params = params ) if element : return element . json | Get specified element by href |
38,668 | def element_name_by_href ( href ) : if href : element = fetch_json_by_href ( href ) if element . json : return element . json . get ( 'name' ) | The element href is known possibly from a reference in an elements json . You want to retrieve the name of this element . |
38,669 | def element_name_and_type_by_href ( href ) : if href : element = fetch_json_by_href ( href ) if element . json : for entries in element . json . get ( 'link' ) : if entries . get ( 'rel' ) == 'self' : typeof = entries . get ( 'type' ) return ( element . json . get ( 'name' ) , typeof ) | Retrieve the element name and type of element based on the href . You may have a href that is within another element reference and want more information on that reference . |
38,670 | def element_attribute_by_href ( href , attr_name ) : if href : element = fetch_json_by_href ( href ) if element . json : return element . json . get ( attr_name ) | The element href is known and you want to retrieve a specific attribute from that element . |
38,671 | def element_by_href_as_smcresult ( href , params = None ) : if href : element = fetch_json_by_href ( href , params = params ) if element : return element | Get specified element returned as an SMCResult object |
38,672 | def element_as_smcresult_use_filter ( name , _filter ) : if name : element = fetch_meta_by_name ( name , filter_context = _filter ) if element . msg : return element if element . json : return element_by_href_as_smcresult ( element . json . pop ( ) . get ( 'href' ) ) | Return SMCResult object and use search filter to find object |
38,673 | def element_href_by_batch ( list_to_find , filter = None ) : try : if filter : return [ { k : element_href_use_filter ( k , filter ) for k in list_to_find } ] return [ { k : element_href ( k ) for k in list_to_find } ] except TypeError : logger . error ( "{} is not iterable" . format ( list_to_find ) ) | Find batch of entries by name . Reduces number of find calls from calling class . |
38,674 | def fetch_json_by_name ( name ) : result = fetch_meta_by_name ( name ) if result . href : result = fetch_json_by_href ( result . href ) return result | Fetch json based on the element name First gets the href based on a search by name then makes a second query to obtain the element json |
38,675 | def create ( cls , name , negotiation_expiration = 200000 , negotiation_retry_timer = 500 , negotiation_retry_max_number = 32 , negotiation_retry_timer_max = 7000 , certificate_cache_crl_validity = 90000 , mobike_after_sa_update = False , mobike_before_sa_update = False , mobike_no_rrc = True ) : json = { 'name' : name , 'negotiation_expiration' : negotiation_expiration , 'negotiation_retry_timer' : negotiation_retry_timer , 'negotiation_retry_max_number' : negotiation_retry_max_number , 'negotiation_retry_timer_max' : negotiation_retry_timer_max , 'certificate_cache_crl_validity' : certificate_cache_crl_validity , 'mobike_after_sa_update' : mobike_after_sa_update , 'mobike_before_sa_update' : mobike_before_sa_update , 'mobike_no_rrc' : mobike_no_rrc } return ElementCreator ( cls , json ) | Create a new gateway setting profile . |
38,676 | def create ( cls , name , trust_all_cas = True ) : json = { 'name' : name , 'trust_all_cas' : trust_all_cas } return ElementCreator ( cls , json ) | Create new External Gateway |
38,677 | def create ( self , name , address = None , enabled = True , balancing_mode = 'active' , ipsec_vpn = True , nat_t = False , force_nat_t = False , dynamic = False , ike_phase1_id_type = None , ike_phase1_id_value = None ) : json = { 'name' : name , 'address' : address , 'balancing_mode' : balancing_mode , 'dynamic' : dynamic , 'enabled' : enabled , 'nat_t' : nat_t , 'force_nat_t' : force_nat_t , 'ipsec_vpn' : ipsec_vpn } if dynamic : json . pop ( 'address' ) json . update ( ike_phase1_id_type = ike_phase1_id_type , ike_phase1_id_value = ike_phase1_id_value ) return ElementCreator ( self . __class__ , href = self . href , json = json ) | Create an test_external endpoint . Define common settings for that specify the address enabled nat_t name etc . You can also omit the IP address if the endpoint is dynamic . In that case you must also specify the ike_phase1 settings . |
38,678 | def enable_disable ( self ) : if self . enabled : self . data [ 'enabled' ] = False else : self . data [ 'enabled' ] = True self . update ( ) | Enable or disable this endpoint . If enabled it will be disabled and vice versa . |
38,679 | def enable_disable_force_nat_t ( self ) : if self . force_nat_t : self . data [ 'force_nat_t' ] = False else : self . data [ 'force_nat_t' ] = True self . update ( ) | Enable or disable NAT - T on this endpoint . If enabled it will be disabled and vice versa . |
38,680 | def create ( self , name , site_element ) : site_element = element_resolver ( site_element ) json = { 'name' : name , 'site_element' : site_element } return ElementCreator ( self . __class__ , href = self . href , json = json ) | Create a VPN site for an internal or external gateway |
38,681 | def add_site_element ( self , element ) : element = element_resolver ( element ) self . data [ 'site_element' ] . extend ( element ) self . update ( ) | Add a site element or list of elements to this VPN . |
38,682 | def location_helper ( name , search_only = False ) : try : return name . href except AttributeError : if name and name . startswith ( 'http' ) : return name except ElementNotFound : return Location . create ( name = name . name ) . href if not search_only else None if name is not None : locations = [ location for location in Search . objects . entry_point ( 'location' ) if location . name == name ] if not locations : return Location . create ( name = name ) . href if not search_only else None return locations [ 0 ] . href | Location finder by name . If location doesn t exist create it and return the href |
38,683 | def zone_helper ( zone ) : if zone is None : return None elif isinstance ( zone , Zone ) : return zone . href elif zone . startswith ( 'http' ) : return zone return Zone . get_or_create ( name = zone ) . href | Zone finder by name . If zone doesn t exist create it and return the href |
38,684 | def logical_intf_helper ( interface ) : if interface is None : return LogicalInterface . get_or_create ( name = 'default_eth' ) . href elif isinstance ( interface , LogicalInterface ) : return interface . href elif interface . startswith ( 'http' ) : return interface return LogicalInterface . get_or_create ( name = interface ) . href | Logical Interface finder by name . Create if it doesn t exist . This is useful when adding logical interfaces to for inline or capture interfaces . |
38,685 | def change_password ( self , password ) : self . make_request ( ModificationFailed , method = 'update' , resource = 'change_password' , params = { 'password' : password } ) | Change user password . Change is committed immediately . |
38,686 | def change_engine_password ( self , password ) : self . make_request ( ModificationFailed , method = 'update' , resource = 'change_engine_password' , params = { 'password' : password } ) | Change Engine password for engines on allowed list . |
38,687 | def location ( self ) : location = Element . from_href ( self . location_ref ) if location and location . name == 'Default' : return None return location | The location for this engine . May be None if no specific location has been assigned . |
38,688 | def pending_changes ( self ) : if 'pending_changes' in self . data . links : return PendingChanges ( self ) raise UnsupportedEngineFeature ( 'Pending changes is an unsupported feature on this engine: {}' . format ( self . type ) ) | Pending changes provides insight into changes on an engine that are pending approval or disapproval . Feature requires SMC > = v6 . 2 . |
38,689 | def virtual_resource ( self ) : resource = create_collection ( self . get_relation ( 'virtual_resources' , UnsupportedEngineFeature ) , VirtualResource ) resource . _load_from_engine ( self , 'virtualResources' ) return resource | Available on a Master Engine only . |
38,690 | def generate_snapshot ( self , filename = 'snapshot.zip' ) : try : self . make_request ( EngineCommandFailed , resource = 'generate_snapshot' , filename = filename ) except IOError as e : raise EngineCommandFailed ( 'Generate snapshot failed: {}' . format ( e ) ) | Generate and retrieve a policy snapshot from the engine This is blocking as file is downloaded |
38,691 | def generate_certificate ( self , common_name , public_key_algorithm = 'rsa' , signature_algorithm = 'rsa_sha_512' , key_length = 2048 , signing_ca = None ) : return GatewayCertificate . _create ( self , common_name , public_key_algorithm , signature_algorithm , key_length , signing_ca ) | Generate an internal gateway certificate used for VPN on this engine . Certificate request should be an instance of VPNCertificate . |
38,692 | def enable ( self , interface_id , dns_relay_profile = None ) : if not dns_relay_profile : href = DNSRelayProfile ( 'Cache Only' ) . href else : href = element_resolver ( dns_relay_profile ) intf = self . engine . interface . get ( interface_id ) self . engine . data . update ( dns_relay_profile_ref = href ) self . engine . data . update ( dns_relay_interface = intf . ndi_interfaces ) | Enable the DNS Relay service on this engine . |
38,693 | def create ( cls , name , template = 'High-Security IPS Template' ) : try : if cls . typeof == 'ips_template_policy' and template is None : fw_template = None else : fw_template = IPSTemplatePolicy ( template ) . href except ElementNotFound : raise LoadPolicyFailed ( 'Cannot find specified firewall template: {}' . format ( template ) ) json = { 'name' : name , 'template' : fw_template } try : return ElementCreator ( cls , json ) except CreateElementFailed as err : raise CreatePolicyFailed ( err ) | Create an IPS Policy |
38,694 | def upload_as_zip ( name , filename ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . upload ( filename = filename ) | Upload an IPList as a zip file . Useful when IPList is very large . This is the default upload format for IPLists . |
38,695 | def upload_as_text ( name , filename ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . upload ( filename = filename , as_type = 'txt' ) | Upload the IPList as text from a file . |
38,696 | def upload_as_json ( name , mylist ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . upload ( json = mylist , as_type = 'json' ) | Upload the IPList as json payload . |
38,697 | def download_as_zip ( name , filename ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . download ( filename = filename ) | Download IPList with zip compression . Recommended for IPLists of larger sizes . This is the default format for downloading IPLists . |
38,698 | def download_as_text ( name , filename ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . download ( filename = filename , as_type = 'txt' ) | Download IPList as text to specified filename . |
38,699 | def download_as_json ( name ) : location = list ( IPList . objects . filter ( name ) ) if location : iplist = location [ 0 ] return iplist . download ( as_type = 'json' ) | Download IPList as json . This would allow for easily manipulation of the IPList but generally recommended only for smaller lists |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.