idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
44,000
def get_jobs ( self , name = None ) : if self . applicationResource : return self . _get_elements ( self . jobs , 'jobs' , Job , None , name ) else : return [ ]
Retrieves jobs running on this resource in its instance .
44,001
def get_operator_output_port ( self ) : return OperatorOutputPort ( self . rest_client . make_request ( self . operatorOutputPort ) , self . rest_client )
Get the output port of this exported stream .
44,002
def _as_published_topic ( self ) : oop = self . get_operator_output_port ( ) if not hasattr ( oop , 'export' ) : return export = oop . export if export [ 'type' ] != 'properties' : return seen_export_type = False topic = None for p in export [ 'properties' ] : if p [ 'type' ] != 'rstring' : continue if p [ 'name' ] == ...
This stream as a PublishedTopic if it is published otherwise None
44,003
def of_service ( config ) : service = Instance . _find_service_def ( config ) if not service : raise ValueError ( ) endpoint = service [ 'connection_info' ] . get ( 'serviceRestEndpoint' ) resource_url , name = Instance . _root_from_endpoint ( endpoint ) sc = streamsx . rest . StreamsConnection ( resource_url = resourc...
Connect to an IBM Streams service instance running in IBM Cloud Private for Data .
44,004
def get_job ( self , id ) : return self . _get_element_by_id ( self . jobs , 'jobs' , Job , str ( id ) )
Retrieves a job matching the given id
44,005
def get_published_topics ( self ) : published_topics = [ ] seen_topics = { } for es in self . get_exported_streams ( ) : pt = es . _as_published_topic ( ) if pt is not None : if pt . topic in seen_topics : if pt . schema is None : continue if pt . schema in seen_topics [ pt . topic ] : continue seen_topics [ pt . topic...
Get a list of published topics for this instance .
44,006
def get_application_configurations ( self , name = None ) : if hasattr ( self , 'applicationConfigurations' ) : return self . _get_elements ( self . applicationConfigurations , 'applicationConfigurations' , ApplicationConfiguration , None , name )
Retrieves application configurations for this instance .
44,007
def create_application_configuration ( self , name , properties , description = None ) : if not hasattr ( self , 'applicationConfigurations' ) : raise NotImplementedError ( ) cv = ApplicationConfiguration . _props ( name , properties , description ) res = self . rest_client . session . post ( self . applicationConfigur...
Create an application configuration .
44,008
def _get_jobs_url ( self ) : if self . _jobs_url is None : self . get_instance_status ( ) if self . _jobs_url is None : raise ValueError ( "Cannot obtain jobs URL" ) return self . _jobs_url
Get & save jobs URL from the status call .
44,009
def start_instance ( self ) : start_url = self . _get_url ( 'start_path' ) res = self . rest_client . session . put ( start_url , json = { } ) _handle_http_errors ( res ) return res . json ( )
Start the instance for this Streaming Analytics service .
44,010
def stop_instance ( self ) : stop_url = self . _get_url ( 'stop_path' ) res = self . rest_client . session . put ( stop_url , json = { } ) _handle_http_errors ( res ) return res . json ( )
Stop the instance for this Streaming Analytics service .
44,011
def get_instance_status ( self ) : status_url = self . _get_url ( 'status_path' ) res = self . rest_client . session . get ( status_url ) _handle_http_errors ( res ) return res . json ( )
Get the status the instance for this Streaming Analytics service .
44,012
def _cancel_job ( self , job , force ) : import streamsx . st as st if st . _has_local_install : return st . _cancel_job ( job . id , force , domain_id = job . get_instance ( ) . get_domain ( ) . id , instance_id = job . get_instance ( ) . id ) return False
Cancel job using streamtool .
44,013
def update ( self , properties = None , description = None ) : cv = ApplicationConfiguration . _props ( properties = properties , description = description ) res = self . rest_client . session . patch ( self . rest_self , headers = { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' } , json = cv ) _h...
Update this application configuration .
44,014
def delete ( self ) : res = self . rest_client . session . delete ( self . rest_self ) _handle_http_errors ( res )
Delete this application configuration .
44,015
def _normalize ( schema , allow_none = True ) : if allow_none and schema is None : return schema if isinstance ( schema , CommonSchema ) : return schema if isinstance ( schema , StreamSchema ) : return schema if isinstance ( schema , basestring ) : return StreamSchema ( schema ) py_types = { _spl_object : CommonSchema ...
Normalize a schema .
44,016
def is_common ( schema ) : if isinstance ( schema , StreamSchema ) : return schema . schema ( ) in _SCHEMA_COMMON if isinstance ( schema , CommonSchema ) : return True if isinstance ( schema , basestring ) : return is_common ( StreamSchema ( schema ) ) return False
Is schema an common schema .
44,017
def _set ( self , schema ) : if isinstance ( schema , CommonSchema ) : self . _spl_type = False self . _schema = schema . schema ( ) self . _style = self . _default_style ( ) else : self . _spl_type = schema . _spl_type self . _schema = schema . _schema self . _style = schema . _style
Set a schema from another schema
44,018
def as_tuple ( self , named = None ) : if not named : return self . _copy ( tuple ) if named == True or isinstance ( named , basestring ) : return self . _copy ( self . _make_named_tuple ( name = named ) ) return self . _copy ( tuple )
Create a structured schema that will pass stream tuples into callables as tuple instances .
44,019
def extend ( self , schema ) : if self . _spl_type : raise TypeError ( "Not supported for declared SPL types" ) base = self . schema ( ) extends = schema . schema ( ) new_schema = base [ : - 1 ] + ',' + extends [ 6 : ] return StreamSchema ( new_schema )
Extend a structured schema by another .
44,020
def _fnop_style ( schema , op , name ) : if is_common ( schema ) : if name in op . params : del op . params [ name ] return if _is_pending ( schema ) : ntp = 'pending' elif schema . style is tuple : ntp = 'tuple' elif schema . style is _spl_dict : ntp = 'dict' elif _is_namedtuple ( schema . style ) and hasattr ( schema...
Set an operator s parameter representing the style of this schema .
44,021
def save ( self ) -> None : for name , field in self . fields . items ( ) : value = self . cleaned_data [ name ] if isinstance ( value , UploadedFile ) : fname = self . _s . get ( name , as_type = File ) if fname : try : default_storage . delete ( fname . name ) except OSError : logger . error ( 'Deleting file %s faile...
Saves all changed values to the database .
44,022
def _stop ( sas , cmd_args ) : if not cmd_args . force : status = sas . get_instance_status ( ) jobs = int ( status [ 'job_count' ] ) if jobs : return status return sas . stop_instance ( )
Stop the service if no jobs are running unless force is set
44,023
def main ( args = None ) : streamsx . _streams . _version . _mismatch_check ( 'streamsx.topology.context' ) try : sr = run_cmd ( args ) sr [ 'return_code' ] = 0 except : sr = { 'return_code' : 1 , 'error' : sys . exc_info ( ) } return sr
Performs an action against a Streaming Analytics service .
44,024
def source ( self , func , name = None ) : _name = name if inspect . isroutine ( func ) : pass elif callable ( func ) : pass else : if _name is None : _name = type ( func ) . __name__ func = streamsx . topology . runtime . _IterableInstance ( func ) sl = _SourceLocation ( _source_info ( ) , "source" ) _name = self . gr...
Declare a source stream that introduces tuples into the application .
44,025
def subscribe ( self , topic , schema = streamsx . topology . schema . CommonSchema . Python , name = None , connect = None , buffer_capacity = None , buffer_full_policy = None ) : schema = streamsx . topology . schema . _normalize ( schema ) _name = self . graph . _requested_name ( name , 'subscribe' ) sl = _SourceLoc...
Subscribe to a topic published by other Streams applications . A Streams application may publish a stream to allow other Streams applications to subscribe to it . A subscriber matches a publisher if the topic and schema match .
44,026
def add_file_dependency ( self , path , location ) : if location not in { 'etc' , 'opt' } : raise ValueError ( location ) if not os . path . isfile ( path ) and not os . path . isdir ( path ) : raise ValueError ( path ) path = os . path . abspath ( path ) if location not in self . _files : self . _files [ location ] = ...
Add a file or directory dependency into an Streams application bundle .
44,027
def add_pip_package ( self , requirement ) : self . _pip_packages . append ( str ( requirement ) ) pr = pkg_resources . Requirement . parse ( requirement ) self . exclude_packages . add ( pr . project_name )
Add a Python package dependency for this topology .
44,028
def create_submission_parameter ( self , name , default = None , type_ = None ) : if name in self . _submission_parameters : raise ValueError ( "Submission parameter {} already defined." . format ( name ) ) sp = streamsx . topology . runtime . _SubmissionParam ( name , default , type_ ) self . _submission_parameters [ ...
Create a submission parameter .
44,029
def _generate_requirements ( self ) : if not self . _pip_packages : return reqs = '' for req in self . _pip_packages : reqs += "{}\n" . format ( req ) reqs_include = { 'contents' : reqs , 'target' : 'opt/python/streams' , 'name' : 'requirements.txt' } if 'opt' not in self . _files : self . _files [ 'opt' ] = [ reqs_inc...
Generate the info to create requirements . txt in the toookit .
44,030
def _add_job_control_plane ( self ) : if not self . _has_jcp : jcp = self . graph . addOperator ( kind = "spl.control::JobControlPlane" , name = "JobControlPlane" ) jcp . viewable = False self . _has_jcp = True
Add a JobControlPlane operator to the topology if one has not already been added . If a JobControlPlane operator has already been added this has no effect .
44,031
def aliased_as ( self , name ) : stream = copy . copy ( self ) stream . _alias = name return stream
Create an alias of this stream .
44,032
def view ( self , buffer_time = 10.0 , sample_size = 10000 , name = None , description = None , start = False ) : if name is None : name = '' . join ( random . choice ( '0123456789abcdef' ) for x in range ( 16 ) ) if self . oport . schema == streamsx . topology . schema . CommonSchema . Python : if self . _json_stream ...
Defines a view on a stream .
44,033
def map ( self , func = None , name = None , schema = None ) : if schema is None : schema = streamsx . topology . schema . CommonSchema . Python if func is None : func = streamsx . topology . runtime . _identity if name is None : name = 'identity' ms = self . _map ( func , schema = schema , name = name ) . _layout ( 'M...
Maps each tuple from this stream into 0 or 1 stream tuples .
44,034
def flat_map ( self , func = None , name = None ) : if func is None : func = streamsx . topology . runtime . _identity if name is None : name = 'flatten' sl = _SourceLocation ( _source_info ( ) , 'flat_map' ) _name = self . topology . graph . _requested_name ( name , action = 'flat_map' , func = func ) stateful = self ...
Maps and flatterns each tuple from this stream into 0 or more tuples .
44,035
def end_parallel ( self ) : outport = self . oport if isinstance ( self . oport . operator , streamsx . topology . graph . Marker ) : if self . oport . operator . kind == "$Union$" : pto = self . topology . graph . addPassThruOperator ( ) pto . addInputPort ( outputPort = self . oport ) outport = pto . addOutputPort ( ...
Ends a parallel region by merging the channels into a single stream .
44,036
def set_parallel ( self , width , name = None ) : self . oport . operator . config [ 'parallel' ] = True self . oport . operator . config [ 'width' ] = streamsx . topology . graph . _as_spl_json ( width , int ) if name : name = self . topology . graph . _requested_name ( str ( name ) , action = 'set_parallel' ) self . ...
Set this source stream to be split into multiple channels as the start of a parallel region .
44,037
def set_consistent ( self , consistent_config ) : self . topology . _add_job_control_plane ( ) self . oport . operator . consistent ( consistent_config ) return self . _make_placeable ( )
Indicates that the stream is the start of a consistent region .
44,038
def last ( self , size = 1 ) : win = Window ( self , 'SLIDING' ) if isinstance ( size , datetime . timedelta ) : win . _evict_time ( size ) elif isinstance ( size , int ) : win . _evict_count ( size ) else : raise ValueError ( size ) return win
Declares a slding window containing most recent tuples on this stream .
44,039
def print ( self , tag = None , name = None ) : _name = name if _name is None : _name = 'print' fn = streamsx . topology . functions . print_flush if tag is not None : tag = str ( tag ) + ': ' fn = lambda v : streamsx . topology . functions . print_flush ( tag + str ( v ) ) sp = self . for_each ( fn , name = _name ) sp...
Prints each tuple to stdout flushing after each tuple .
44,040
def publish ( self , topic , schema = None , name = None ) : sl = _SourceLocation ( _source_info ( ) , 'publish' ) schema = streamsx . topology . schema . _normalize ( schema ) if schema is not None and self . oport . schema . schema ( ) != schema . schema ( ) : nc = None if schema == streamsx . topology . schema . Com...
Publish this stream on a topic for other Streams applications to subscribe to . A Streams application may publish a stream to allow other Streams applications to subscribe to it . A subscriber matches a publisher if the topic and schema match .
44,041
def as_json ( self , force_object = True , name = None ) : func = streamsx . topology . runtime . _json_force_object if force_object else None saj = self . _change_schema ( streamsx . topology . schema . CommonSchema . Json , 'as_json' , name , func ) . _layout ( 'AsJson' ) saj . oport . operator . sl = _SourceLocation...
Declares a stream converting each tuple on this stream into a JSON value .
44,042
def _change_schema ( self , schema , action , name = None , func = None ) : if self . oport . schema . schema ( ) == schema . schema ( ) : return self if func is None : func = streamsx . topology . functions . identity _name = name if _name is None : _name = action css = self . _map ( func , schema , name = _name ) if ...
Internal method to change a schema .
44,043
def _initialize_rest ( self ) : if self . _submit_context is None : raise ValueError ( "View has not been created." ) job = self . _submit_context . _job_access ( ) self . _view_object = job . get_views ( name = self . name ) [ 0 ]
Used to initialize the View object on first use .
44,044
def complete ( self , stream ) : assert not self . is_complete ( ) self . _marker . addInputPort ( outputPort = stream . oport ) self . stream . oport . schema = stream . oport . schema self . _pending_schema . _set ( self . stream . oport . schema ) stream . oport . operator . _start_op = True
Complete the pending stream .
44,045
def trigger ( self , when = 1 ) : tw = Window ( self . stream , self . _config [ 'type' ] ) tw . _config [ 'evictPolicy' ] = self . _config [ 'evictPolicy' ] tw . _config [ 'evictConfig' ] = self . _config [ 'evictConfig' ] if self . _config [ 'evictPolicy' ] == 'TIME' : tw . _config [ 'evictTimeUnit' ] = 'MILLISECONDS...
Declare a window with this window s size and a trigger policy .
44,046
def get_rest_api ( ) : assert _has_local_install url = [ ] ok = _run_st ( [ 'geturl' , '--api' ] , lines = url ) if not ok : raise ChildProcessError ( 'streamtool geturl' ) return url [ 0 ]
Get the root URL for the IBM Streams REST API .
44,047
def _is_builtin_module ( module ) : if ( not hasattr ( module , '__file__' ) ) or module . __name__ in sys . builtin_module_names : return True if module . __name__ in _stdlib . _STD_LIB_MODULES : return True amp = os . path . abspath ( module . __file__ ) if 'site-packages' in amp : return False if amp . startswith ( ...
Is builtin or part of standard library
44,048
def _find_dependent_modules ( self , module ) : dms = set ( ) for um in inspect . getmembers ( module , inspect . ismodule ) : dms . add ( um [ 1 ] ) for uc in inspect . getmembers ( module , inspect . isclass ) : self . _add_obj_module ( dms , uc [ 1 ] ) for ur in inspect . getmembers ( module , inspect . isroutine ) ...
Return the set of dependent modules for used modules classes and routines .
44,049
def add_dependencies ( self , module ) : if module in self . _processed_modules : return None if hasattr ( module , "__name__" ) : mn = module . __name__ else : mn = '<unknown>' _debug . debug ( "add_dependencies:module=%s" , module ) if mn == "__main__" : self . _processed_modules . add ( module ) elif not self . _add...
Adds a module and its dependencies to the list of dependencies .
44,050
def _include_module ( self , module , mn ) : if mn in self . topology . include_packages : _debug . debug ( "_include_module:explicit using __include_packages: module=%s" , mn ) return True if '.' in mn : for include_package in self . topology . include_packages : if mn . startswith ( include_package + '.' ) : _debug ....
See if a module should be included or excluded based upon included_packages and excluded_packages .
44,051
def _add_dependency ( self , module , mn ) : _debug . debug ( "_add_dependency:module=%s" , mn ) if _is_streamsx_module ( module ) : _debug . debug ( "_add_dependency:streamsx module=%s" , mn ) return False if _is_builtin_module ( module ) : _debug . debug ( "_add_dependency:builtin module=%s" , mn ) return False if no...
Adds a module to the list of dependencies without handling the modules dependences .
44,052
def freeze ( self ) -> dict : settings = { } for key , v in self . _h . defaults . items ( ) : settings [ key ] = self . _unserialize ( v . value , v . type ) if self . _parent : settings . update ( getattr ( self . _parent , self . _h . attribute_name ) . freeze ( ) ) for key in self . _cache ( ) : settings [ key ] = ...
Returns a dictionary of all settings set for this object including any values of its parents or hardcoded defaults .
44,053
def get ( self , key : str , default = None , as_type : type = None , binary_file = False ) : if as_type is None and key in self . _h . defaults : as_type = self . _h . defaults [ key ] . type if key in self . _cache ( ) : value = self . _cache ( ) [ key ] else : value = None if self . _parent : value = getattr ( self ...
Get a setting specified by key key . Normally settings are strings but if you put non - strings into the settings object you can request unserialization by specifying as_type . If the key does not have a harcdoded default type omitting as_type always will get you a string .
44,054
def set ( self , key : str , value : Any ) -> None : wc = self . _write_cache ( ) if key in wc : s = wc [ key ] else : s = self . _type ( object = self . _obj , key = key ) s . value = self . _serialize ( value ) s . save ( ) self . _cache ( ) [ key ] = s . value wc [ key ] = s self . _flush_external_cache ( )
Stores a setting to the database of its object . The write to the database is performed immediately and the cache in the cache backend is flushed . The cache within this object will be updated correctly .
44,055
def delete ( self , key : str ) -> None : if key in self . _write_cache ( ) : self . _write_cache ( ) [ key ] . delete ( ) del self . _write_cache ( ) [ key ] if key in self . _cache ( ) : del self . _cache ( ) [ key ] self . _flush_external_cache ( )
Deletes a setting from this object s storage . The write to the database is performed immediately and the cache in the cache backend is flushed . The cache within this object will be updated correctly .
44,056
def _get_vcap_services ( vcap_services = None ) : vcap_services = vcap_services or os . environ . get ( 'VCAP_SERVICES' ) if not vcap_services : raise ValueError ( "VCAP_SERVICES information must be supplied as a parameter or as environment variable 'VCAP_SERVICES'" ) if isinstance ( vcap_services , dict ) : return vca...
Retrieves the VCAP Services information from the ConfigParams . VCAP_SERVICES field in the config object . If vcap_services is not specified it takes the information from VCAP_SERVICES environment variable .
44,057
def _get_credentials ( vcap_services , service_name = None ) : service_name = service_name or os . environ . get ( 'STREAMING_ANALYTICS_SERVICE_NAME' , None ) services = vcap_services [ 'streaming-analytics' ] creds = None for service in services : if service [ 'name' ] == service_name : creds = service [ 'credentials'...
Retrieves the credentials of the VCAP Service of the specified service_name . If service_name is not specified it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment variable .
44,058
def get_domains ( self ) : if self . _domains is None : self . _domains = self . _get_elements ( 'domains' , Domain ) return self . _domains
Retrieves available domains .
44,059
def get_resources ( self ) : json_resources = self . rest_client . make_request ( self . resource_url ) [ 'resources' ] return [ RestResource ( resource , self . rest_client ) for resource in json_resources ]
Retrieves a list of all known Streams high - level REST resources .
44,060
def of_definition ( service_def ) : vcap_services = streamsx . topology . context . _vcap_from_service_definition ( service_def ) service_name = streamsx . topology . context . _name_from_service_definition ( service_def ) return StreamingAnalyticsConnection ( vcap_services , service_name )
Create a connection to a Streaming Analytics service .
44,061
def is_authenticated ( self , request , ** kwargs ) : log . info ( "OAuth20Authentication" ) try : key = request . GET . get ( 'oauth_consumer_key' ) if not key : for header in [ 'Authorization' , 'HTTP_AUTHORIZATION' ] : auth_header_value = request . META . get ( header ) if auth_header_value : key = auth_header_value...
Verify 2 - legged oauth request . Parameters accepted as values in the Authorization header as a GET request parameter or in a POST body .
44,062
def check_scope ( self , token , request ) : http_method = request . method if not hasattr ( self , http_method ) : raise OAuthError ( "HTTP method is not recognized" ) required_scopes = getattr ( self , http_method ) if required_scopes is None : return True if isinstance ( required_scopes , six . string_types ) : if t...
The required scope is either a string or an iterable . If string check if it is allowed for our access token otherwise iterate through the required_scopes to see which scopes are allowed
44,063
def as_dict ( self ) -> Dict [ str , str ] : items : Dict [ str , str ] = { } for k , v in self . items ( ) : if type ( v ) is str : items . update ( { k : v } ) return items
Export color register as dict .
44,064
def as_namedtuple ( self ) : d = self . as_dict ( ) return namedtuple ( 'ColorRegister' , d . keys ( ) ) ( * d . values ( ) )
Export color register as namedtuple .
44,065
def _extract_attrs ( x , n ) : try : return extract_attrs ( x , n ) except ( ValueError , IndexError ) : if PANDOCVERSION < '1.16' : assert x [ n - 1 ] [ 't' ] == 'Image' image = x [ n - 1 ] s = image [ 'c' ] [ - 1 ] [ 0 ] if '%20%7B' in s : path = s [ : s . index ( '%20%7B' ) ] attrs = unquote ( s [ s . index ( '%7B' ...
Extracts attributes for an image . n is the index where the attributes begin . Extracted elements are deleted from the element list x . Attrs are returned in pandoc format .
44,066
def process_figures ( key , value , fmt , meta ) : global has_unnumbered_figures if key == 'Para' and len ( value ) == 1 and value [ 0 ] [ 't' ] == 'Image' and value [ 0 ] [ 'c' ] [ - 1 ] [ 1 ] . startswith ( 'fig:' ) : if len ( value [ 0 ] [ 'c' ] ) == 2 : has_unnumbered_figures = True if fmt == 'latex' : return [ Raw...
Processes the figures .
44,067
def i18n_javascript ( self , request ) : if settings . USE_I18N : from django . views . i18n import javascript_catalog else : from django . views . i18n import null_javascript_catalog as javascript_catalog return javascript_catalog ( request , packages = [ 'media_tree' ] )
Displays the i18n JavaScript that the Django admin requires .
44,068
def get_results ( self , request ) : super ( MediaTreeChangeList , self ) . get_results ( request ) try : reduce_levels = abs ( int ( get_request_attr ( request , 'reduce_levels' , 0 ) ) ) except TypeError : reduce_levels = 0 is_filtered = self . is_filtered ( request ) if is_filtered or reduce_levels : for item in sel...
Temporarily decreases the level attribute of all search results in order to prevent indendation when displaying them .
44,069
def get_media_backend ( fail_silently = True , handles_media_types = None , handles_file_extensions = None , supports_thumbnails = None ) : backends = app_settings . MEDIA_TREE_MEDIA_BACKENDS if not len ( backends ) : if not fail_silently : raise ImproperlyConfigured ( 'There is no media backend configured.' + ' Please...
Returns the MediaBackend subclass that is configured for use with media_tree .
44,070
def thumbnail_size ( parser , token ) : args = token . split_contents ( ) tag = args . pop ( 0 ) if len ( args ) >= 2 and args [ - 2 ] == 'as' : context_name = args [ - 1 ] args = args [ : - 2 ] else : context_name = None if len ( args ) > 1 : raise template . TemplateSyntaxError ( "Invalid syntax. Expected " "'{%% %s ...
Returns a pre - configured thumbnail size or assigns it to a context variable .
44,071
def file_length ( file_obj ) : file_obj . seek ( 0 , 2 ) length = file_obj . tell ( ) file_obj . seek ( 0 ) return length
Returns the length in bytes of a given file object . Necessary because os . fstat only works on real files and not file - like objects . This works on more types of streams primarily StringIO .
44,072
def parse_href ( href ) : url = urlparse ( href ) path = url . path . split ( '/' ) collection_name = path [ 1 ] id_ = path [ 2 ] return collection_name , id_
Parses an Analyze Re href into collection name and ID
44,073
def vectorize ( values ) : if isinstance ( values , list ) : return ',' . join ( str ( v ) for v in values ) return values
Takes a value or list of values and returns a single result joined by if necessary .
44,074
def vectorize_range ( values ) : if isinstance ( values , tuple ) : return '_' . join ( str ( i ) for i in values ) if isinstance ( values , list ) : if not all ( [ isinstance ( item , tuple ) for item in values ] ) : raise TypeError ( 'Items in the list must be tuples' ) return ',' . join ( '_' . join ( str ( i ) for ...
This function is for url encoding . Takes a value or a tuple or list of tuples and returns a single result tuples are joined by if necessary elements in tuple are joined by _
44,075
def delete_orphaned_files ( modeladmin , request , queryset = None ) : execute = request . POST . get ( 'execute' ) storage = get_media_storage ( ) broken_node_links = [ ] orphaned_files_choices = [ ] broken_nodes , orphaned_files = get_broken_media ( ) for node in broken_nodes : link = mark_safe ( '<a href="%s">%s</a>...
Deletes orphaned files i . e . media files existing in storage that are not in the database .
44,076
def rebuild_tree ( modeladmin , request , queryset = None ) : tree = FileNode . tree . rebuild ( ) messages . success ( request , message = _ ( 'The node tree was rebuilt.' ) ) return HttpResponseRedirect ( '' )
Rebuilds whole tree in database using parent link .
44,077
def clear_cache ( modeladmin , request , queryset = None ) : execute = request . POST . get ( 'execute' ) files_in_storage = [ ] storage = get_media_storage ( ) cache_files_choices = [ ] for storage_name in get_cache_files ( ) : link = mark_safe ( '<a href="%s">%s</a>' % ( storage . url ( storage_name ) , storage_name ...
Clears media cache files such as thumbnails .
44,078
def autodiscover_media_extensions ( ) : import copy from django . conf import settings from django . utils . module_loading import module_has_submodule for app in settings . INSTALLED_APPS : mod = import_module ( app ) try : import_module ( '%s.media_extension' % app ) except : if module_has_submodule ( mod , 'media_ex...
Auto - discover INSTALLED_APPS media_extensions . py modules and fail silently when not present . This forces an import on them to register any media extension bits they may want .
44,079
def join_formatted ( text , new_text , glue_format_if_true = u'%s%s' , glue_format_if_false = u'%s%s' , condition = None , format = u'%s' , escape = False ) : if condition is None : condition = text and new_text add_text = new_text if escape : add_text = conditional_escape ( add_text ) if add_text : add_text = format %...
Joins two strings optionally escaping the second and using one of two string formats for glueing them together depending on whether a condition is True or False .
44,080
def _initialize ( self , path ) : root = os . path . abspath ( path ) try : while ".fmf" not in next ( os . walk ( root ) ) [ 1 ] : if root == "/" : raise utils . RootError ( "Unable to find tree root for '{0}'." . format ( os . path . abspath ( path ) ) ) root = os . path . abspath ( os . path . join ( root , os . par...
Find metadata tree root detect format version
44,081
def merge ( self , parent = None ) : if parent is None : parent = self . parent if parent is None : return self . sources = parent . sources + self . sources data = copy . deepcopy ( parent . data ) for key , value in sorted ( self . data . items ( ) ) : if key . endswith ( '+' ) : key = key . rstrip ( '+' ) if key in ...
Merge parent data
44,082
def update ( self , data ) : if data is None : return for key , value in sorted ( data . items ( ) ) : if key . startswith ( '/' ) : name = key . lstrip ( '/' ) match = re . search ( "([^/]+)(/.*)" , name ) if match : name = match . groups ( ) [ 0 ] value = { match . groups ( ) [ 1 ] : value } self . child ( name , val...
Update metadata handle virtual hierarchy
44,083
def get ( self , name = None , default = None ) : if name is None : return self . data if not isinstance ( name , list ) : name = [ name ] data = self . data try : for key in name : data = data [ key ] except KeyError : return default return data
Get attribute value or return default
44,084
def child ( self , name , data , source = None ) : try : if isinstance ( data , dict ) : self . children [ name ] . update ( data ) else : self . children [ name ] . grow ( data ) except KeyError : self . children [ name ] = Tree ( data , name , parent = self ) if source is not None : self . children [ name ] . sources...
Create or update child with given data
44,085
def grow ( self , path ) : if path is None : return path = path . rstrip ( "/" ) log . info ( "Walking through directory {0}" . format ( os . path . abspath ( path ) ) ) dirpath , dirnames , filenames = next ( os . walk ( path ) ) filenames = sorted ( [ filename for filename in filenames if filename . endswith ( SUFFIX...
Grow the metadata tree for the given directory path
44,086
def find ( self , name ) : for node in self . climb ( whole = True ) : if node . name == name : return node return None
Find node with given name
44,087
def prune ( self , whole = False , keys = [ ] , names = [ ] , filters = [ ] ) : for node in self . climb ( whole ) : if not all ( [ key in node . data for key in keys ] ) : continue if names and not any ( [ re . search ( name , node . name ) for name in names ] ) : continue try : if not all ( [ utils . filter ( filter ...
Filter tree nodes based on given criteria
44,088
def save ( self ) : try : self . node . move_to ( self . cleaned_data [ 'target' ] , self . cleaned_data [ 'position' ] ) return self . node except InvalidMove , e : self . errors [ NON_FIELD_ERRORS ] = ErrorList ( e ) raise
Attempts to move the node using the selected target and position .
44,089
def show ( self , brief = False ) : output = [ ] for path in self . options . paths or [ "." ] : if self . options . verbose : utils . info ( "Checking {0} for metadata." . format ( path ) ) tree = fmf . Tree ( path ) for node in tree . prune ( self . options . whole , self . options . keys , self . options . names , s...
Show metadata for each path given
44,090
def filter ( filter , data , sensitive = True , regexp = False ) : def match_value ( pattern , text ) : if regexp : return re . match ( "^{0}$" . format ( pattern ) , text ) else : return pattern == text def check_value ( dimension , value ) : for atom in re . split ( "\s*,\s*" , value ) : if atom . startswith ( "-" ) ...
Return true if provided filter matches given dictionary of values
44,091
def color ( text , color = None , background = None , light = False , enabled = "auto" ) : colors = { "black" : 30 , "red" : 31 , "green" : 32 , "yellow" : 33 , "blue" : 34 , "magenta" : 35 , "cyan" : 36 , "white" : 37 } if enabled == "auto" : enabled = Coloring ( ) . enabled ( ) if not enabled : return text if color a...
Return text in desired color if coloring enabled
44,092
def _create_logger ( name = 'fmf' , level = None ) : logger = logging . getLogger ( name ) handler = logging . StreamHandler ( ) handler . setFormatter ( Logging . ColoredFormatter ( ) ) logger . addHandler ( handler ) for level in Logging . LEVELS : setattr ( logger , level , getattr ( logging , level ) ) logger . DAT...
Create fmf logger
44,093
def get_admin_url ( self , query_params = None , use_path = False ) : if not query_params : query_params = { } url = '' if self . is_top_node ( ) : url = reverse ( 'admin:media_tree_filenode_changelist' ) elif use_path and ( self . is_folder ( ) or self . pk ) : url = reverse ( 'admin:media_tree_filenode_open_path' , a...
Returns the URL for viewing a FileNode in the admin .
44,094
def get_caption_formatted ( self , field_formats = app_settings . MEDIA_TREE_METADATA_FORMATS , escape = True ) : if self . override_caption != '' : return self . override_caption else : return mark_safe ( self . get_metadata_display ( field_formats , escape = escape ) )
Returns object metadata that has been selected to be displayed to users compiled as a string including default formatting for example bold titles .
44,095
def save ( self ) : self . success_count = 0 for node in self . get_selected_nodes ( ) : self . move_node ( node , self . cleaned_data [ 'target_node' ] )
Attempts to move the nodes using the selected target and position .
44,096
def save ( self ) : storage = get_media_storage ( ) for storage_name in self . cleaned_data [ 'selected_files' ] : full_path = storage . path ( storage_name ) try : storage . delete ( storage_name ) self . success_files . append ( full_path ) except OSError : self . error_files . append ( full_path )
Deletes the selected files from storage
44,097
def get_file_link ( node , use_metadata = False , include_size = False , include_extension = False , include_icon = False , href = None , extra_class = '' , extra = '' ) : link_text = None if use_metadata : link_text = node . get_metadata_display ( ) if not link_text : link_text = node . __unicode__ ( ) if node . node_...
Returns a formatted HTML link tag to the FileNode s file optionally including some meta information about the file .
44,098
def norm_name ( build_module : str , target_name : str ) : if ':' not in target_name : raise ValueError ( "Must provide fully-qualified target name (with `:') to avoid " "possible ambiguity - `{}' not valid" . format ( target_name ) ) mod , name = split ( target_name ) return '{}:{}' . format ( PurePath ( norm_proj_pat...
Return a normalized canonical target name for the target_name observed in build module build_module .
44,099
def hashify_targets ( targets : list , build_context ) -> list : return sorted ( build_context . targets [ target_name ] . hash ( build_context ) for target_name in listify ( targets ) )
Return sorted hashes of targets .