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' ] == '__spl_exportType' : if p [ 'values' ] == [ '"topic"' ] : seen_export_type = True else : return if p [ 'name' ] == '__spl_topic' : topic = p [ 'values' ] [ 0 ] if seen_export_type and topic is not None : schema = None if hasattr ( oop , 'tupleAttributes' ) : ta_url = oop . tupleAttributes ta_resp = self . rest_client . make_request ( ta_url ) schema = streamsx . topology . schema . StreamSchema ( ta_resp [ 'splType' ] ) return PublishedTopic ( topic [ 1 : - 1 ] , schema ) return | 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 = resource_url , auth = _ICPDAuthHandler ( name , service [ 'service_token' ] ) ) if streamsx . topology . context . ConfigParams . SSL_VERIFY in config : sc . session . verify = config [ streamsx . topology . context . ConfigParams . SSL_VERIFY ] return sc . get_instance ( name ) | 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 ] . append ( pt . schema ) else : seen_topics [ pt . topic ] = [ pt . schema ] published_topics . append ( pt ) return published_topics | 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 . applicationConfigurations , headers = { 'Accept' : 'application/json' } , json = cv ) _handle_http_errors ( res ) return ApplicationConfiguration ( res . json ( ) , self . rest_client ) | 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 ) _handle_http_errors ( res ) self . json_rep = res . json ( ) return self | 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 . Python , _spl_str : CommonSchema . String , json : CommonSchema . Json , } if schema in py_types : return py_types [ schema ] if sys . version_info . major == 3 : import typing if isinstance ( schema , type ) and issubclass ( schema , tuple ) : if hasattr ( schema , '_fields' ) and hasattr ( schema , '_field_types' ) : return _from_named_tuple ( schema ) raise ValueError ( "Unknown stream schema type:" + str ( schema ) ) | 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 . style , '_splpy_namedtuple' ) : ntp = 'namedtuple:' + schema . style . _splpy_namedtuple else : return op . params [ name ] = ntp | 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 failed.' % fname . name ) newname = default_storage . save ( self . get_new_filename ( value . name ) , value ) value . _name = newname self . _s . set ( name , value ) elif isinstance ( value , File ) : continue elif isinstance ( field , forms . FileField ) : fname = self . _s . get ( name , as_type = File ) if fname : try : default_storage . delete ( fname . name ) except OSError : logger . error ( 'Deleting file %s failed.' % fname . name ) del self . _s [ name ] elif value is None : del self . _s [ name ] elif self . _s . get ( name , as_type = type ( value ) ) != value : self . _s . set ( name , value ) | 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 . graph . _requested_name ( _name , action = 'source' , func = func ) op = self . graph . addOperator ( self . opnamespace + "::Source" , func , name = _name , sl = sl ) op . _layout ( kind = 'Source' , name = _name , orig_name = name ) oport = op . addOutputPort ( name = _name ) return Stream ( self , oport ) . _make_placeable ( ) | 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 = _SourceLocation ( _source_info ( ) , "subscribe" ) op = self . graph . addOperator ( kind = "com.ibm.streamsx.topology.topic::Subscribe" , sl = sl , name = _name , stateful = False ) oport = op . addOutputPort ( schema = schema , name = _name ) params = { 'topic' : topic , 'streamType' : schema } if connect is not None and connect != SubscribeConnection . Direct : params [ 'connect' ] = connect if buffer_capacity : params [ 'bufferCapacity' ] = int ( buffer_capacity ) if buffer_full_policy : params [ 'bufferFullPolicy' ] = buffer_full_policy op . setParameters ( params ) op . _layout_group ( 'Subscribe' , name if name else _name ) return Stream ( self , oport ) . _make_placeable ( ) | 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 ] = [ path ] else : self . _files [ location ] . append ( path ) return location + '/' + os . path . basename ( path ) | 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 [ name ] = sp return sp | 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_include ] else : self . _files [ 'opt' ] . append ( reqs_include ) | 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 : view_stream = self . _json_stream else : self . _json_stream = self . as_json ( force_object = False ) . _layout ( hidden = True ) view_stream = self . _json_stream if self . _placeable : self . _colocate ( view_stream , 'view' ) else : view_stream = self port = view_stream . oport . name view_config = { 'name' : name , 'port' : port , 'description' : description , 'bufferTime' : buffer_time , 'sampleSize' : sample_size } if start : view_config [ 'activateOption' ] = 'automatic' view_stream . oport . operator . addViewConfig ( view_config ) _view = View ( name ) self . topology . graph . _views . append ( _view ) return _view | 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 ( 'Map' ) ms . oport . operator . sl = _SourceLocation ( _source_info ( ) , 'map' ) return ms | 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 . _determine_statefulness ( func ) op = self . topology . graph . addOperator ( self . topology . opnamespace + "::FlatMap" , func , name = _name , sl = sl , stateful = stateful ) op . addInputPort ( outputPort = self . oport ) streamsx . topology . schema . StreamSchema . _fnop_style ( self . oport . schema , op , 'pyStyle' ) oport = op . addOutputPort ( name = _name ) return Stream ( self . topology , oport ) . _make_placeable ( ) . _layout ( 'FlatMap' , name = _name , orig_name = name ) | 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 ( schema = self . oport . schema ) op = self . topology . graph . addOperator ( "$EndParallel$" ) op . addInputPort ( outputPort = outport ) oport = op . addOutputPort ( schema = self . oport . schema ) endP = Stream ( self . topology , oport ) return endP | 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 . oport . operator . config [ 'regionName' ] = name return 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 . _op ( ) . sl = _SourceLocation ( _source_info ( ) , 'print' ) return 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 . CommonSchema . Json : schema_change = self . as_json ( ) elif schema == streamsx . topology . schema . CommonSchema . String : schema_change = self . as_string ( ) else : raise ValueError ( schema ) if self . _placeable : self . _colocate ( schema_change , 'publish' ) sp = schema_change . publish ( topic , schema = schema , name = name ) sp . _op ( ) . sl = sl return sp _name = self . topology . graph . _requested_name ( name , action = "publish" ) op = self . topology . graph . addOperator ( "com.ibm.streamsx.topology.topic::Publish" , params = { 'topic' : topic } , sl = sl , name = _name , stateful = False ) op . addInputPort ( outputPort = self . oport ) op . _layout_group ( 'Publish' , name if name else _name ) sink = Sink ( op ) if self . _placeable : self . _colocate ( sink , 'publish' ) return sink | 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 ( _source_info ( ) , 'as_json' ) return saj | 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 self . _placeable : self . _colocate ( css , action ) return css | 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' if isinstance ( when , datetime . timedelta ) : tw . _config [ 'triggerPolicy' ] = 'TIME' tw . _config [ 'triggerConfig' ] = int ( when . total_seconds ( ) * 1000.0 ) tw . _config [ 'triggerTimeUnit' ] = 'MILLISECONDS' elif isinstance ( when , int ) : tw . _config [ 'triggerPolicy' ] = 'COUNT' tw . _config [ 'triggerConfig' ] = when else : raise ValueError ( when ) return tw | 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 ( _STD_MODULE_DIR ) : return True if not '.' in module . __name__ : return False mn_top = module . __name__ . split ( '.' ) [ 0 ] return mn_top in _stdlib . _STD_LIB_MODULES | 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 ) : self . _add_obj_module ( dms , ur [ 1 ] ) return dms | 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_dependency ( module , mn ) : _debug . debug ( "add_dependencies:not added:module=%s" , mn ) return None _debug . debug ( "add_dependencies:ADDED:module=%s" , mn ) for dm in self . _find_dependent_modules ( module ) : _debug . debug ( "add_dependencies:adding dependent module %s for %s" , dm , mn ) self . add_dependencies ( dm ) | 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 . debug ( "_include_module:explicit pattern using __include_packages: module=%s pattern=%s" , mn , include_package + '.' ) return True if mn in self . topology . exclude_packages : _debug . debug ( "_include_module:explicit using __exclude_packages: module=%s" , mn ) return False if '.' in mn : for exclude_package in self . topology . exclude_packages : if mn . startswith ( exclude_package + '.' ) : _debug . debug ( "_include_module:explicit pattern using __exclude_packages: module=%s pattern=%s" , mn , exclude_package + '.' ) return False _debug . debug ( "_include_module:including: module=%s" , mn ) return True | 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 not self . _include_module ( module , mn ) : return False package_name = _get_package_name ( module ) top_package_name = module . __name__ . split ( '.' ) [ 0 ] if package_name and top_package_name in sys . modules : top_package = sys . modules [ top_package_name ] if "__path__" in top_package . __dict__ : seen_non_site_package = False for top_package_path in reversed ( list ( top_package . __path__ ) ) : top_package_path = os . path . abspath ( top_package_path ) if 'site-packages' in top_package_path : continue seen_non_site_package = True self . _add_package ( top_package_path ) if not seen_non_site_package : _debug . debug ( "_add_dependency:site-packages path module=%s" , mn ) return False elif hasattr ( top_package , '__file__' ) : if 'site-packages' in top_package . __file__ : _debug . debug ( "_add_dependency:site-packages module=%s" , mn ) return False self . _add_package ( os . path . abspath ( top_package . __file__ ) ) elif hasattr ( module , '__file__' ) : module_path = os . path . abspath ( module . __file__ ) if 'site-packages' in module_path : _debug . debug ( "_add_dependency:site-packages module=%s" , mn ) return False self . _modules . add ( module_path ) self . _processed_modules . add ( module ) return True | 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 ] = self . get ( key ) return settings | 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 . _parent , self . _h . attribute_name ) . get ( key , as_type = str ) if value is None and key in self . _h . defaults : value = self . _h . defaults [ key ] . value if value is None and default is not None : value = default return self . _unserialize ( value , as_type , binary_file = binary_file ) | 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 vcap_services try : vcap_services = json . loads ( vcap_services ) except json . JSONDecodeError : try : with open ( vcap_services ) as vcap_json_data : vcap_services = json . load ( vcap_json_data ) except : raise ValueError ( "VCAP_SERVICES information is not JSON or a file containing JSON:" , vcap_services ) return vcap_services | 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' ] break if creds is None : raise ValueError ( "Streaming Analytics service " + str ( service_name ) + " was not found in VCAP_SERVICES" ) return creds | 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 . split ( ' ' , 1 ) [ 1 ] break if not key and request . method == 'POST' : if request . META . get ( 'CONTENT_TYPE' ) == 'application/json' : decoded_body = request . body . decode ( 'utf8' ) key = json . loads ( decoded_body ) [ 'oauth_consumer_key' ] if not key : log . info ( 'OAuth20Authentication. No consumer_key found.' ) return None token = self . verify_access_token ( key , request , ** kwargs ) request . user = token . user request . META [ 'oauth_consumer_key' ] = key return True except KeyError : log . exception ( "Error in OAuth20Authentication." ) request . user = AnonymousUser ( ) return False except Exception : log . exception ( "Error in OAuth20Authentication." ) return False | 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 token . allow_scopes ( required_scopes . split ( ) ) : return [ required_scopes ] return [ ] allowed_scopes = [ ] try : for scope in required_scopes : if token . allow_scopes ( scope . split ( ) ) : allowed_scopes . append ( scope ) except : raise Exception ( 'Invalid required scope values' ) else : return allowed_scopes | 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' ) : ] ) image [ 'c' ] [ - 1 ] [ 0 ] = path return PandocAttributes ( attrs . strip ( ) , 'markdown' ) . to_pandoc ( ) raise | 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 [ RawBlock ( 'tex' , r'\begin{no-prefix-figure-caption}' ) , Para ( value ) , RawBlock ( 'tex' , r'\end{no-prefix-figure-caption}' ) ] return None fig = _process_figure ( value , fmt ) attrs = fig [ 'attrs' ] if fig [ 'is_unnumbered' ] : if fmt == 'latex' : return [ RawBlock ( 'tex' , r'\begin{no-prefix-figure-caption}' ) , Para ( value ) , RawBlock ( 'tex' , r'\end{no-prefix-figure-caption}' ) ] elif fmt in [ 'latex' , 'beamer' ] : key = attrs [ 0 ] if PANDOCVERSION >= '1.17' : if LABEL_PATTERN . match ( attrs [ 0 ] ) : attrs [ 0 ] = '' if fig [ 'is_tagged' ] : tex = '\n' . join ( [ r'\let\oldthefigure=\thefigure' , r'\renewcommand\thefigure{%s}' % references [ key ] ] ) pre = RawBlock ( 'tex' , tex ) tex = '\n' . join ( [ r'\let\thefigure=\oldthefigure' , r'\addtocounter{figure}{-1}' ] ) post = RawBlock ( 'tex' , tex ) return [ pre , Para ( value ) , post ] elif fig [ 'is_unreferenceable' ] : attrs [ 0 ] = '' elif PANDOCVERSION < '1.16' and fmt in ( 'html' , 'html5' ) and LABEL_PATTERN . match ( attrs [ 0 ] ) : anchor = RawBlock ( 'html' , '<a name="%s"></a>' % attrs [ 0 ] ) return [ anchor , Para ( value ) ] elif fmt == 'docx' : bookmarkstart = RawBlock ( 'openxml' , '<w:bookmarkStart w:id="0" w:name="%s"/>' % attrs [ 0 ] ) bookmarkend = RawBlock ( 'openxml' , '<w:bookmarkEnd w:id="0"/>' ) return [ bookmarkstart , Para ( value ) , bookmarkend ] return None | 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 self . result_list : item . prevent_save ( ) item . actual_level = item . level if is_filtered : item . reduce_levels = item . level item . level = 0 else : item . reduce_levels = reduce_levels item . level = max ( 0 , item . level - reduce_levels ) | 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 define `MEDIA_TREE_MEDIA_BACKENDS` in your settings.' ) else : return False for path in backends : backend = get_module_attr ( path ) if ( not handles_media_types or backend . handles_media_types ( handles_media_types ) ) and ( not handles_file_extensions or backend . handles_file_extensions ( handles_file_extensions ) ) and ( not supports_thumbnails or backend . supports_thumbnails ( ) ) : return backend if not fail_silently : raise ImproperlyConfigured ( 'There is no media backend configured to handle' ' the specified file types.' ) return False | 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 [\"size_name\"] [as context_var] %%}'" % tag ) elif len ( args ) == 1 : size_name = args [ 0 ] else : size_name = None return ThumbnailSizeNode ( size_name = size_name , context_name = context_name ) | 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 i in v ) for v in values ) return str ( values ) | 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>' % ( node . get_admin_url ( ) , node . __unicode__ ( ) ) ) broken_node_links . append ( link ) for storage_name in orphaned_files : file_path = storage . path ( storage_name ) link = mark_safe ( '<a href="%s">%s</a>' % ( storage . url ( storage_name ) , file_path ) ) orphaned_files_choices . append ( ( storage_name , link ) ) if not len ( orphaned_files_choices ) and not len ( broken_node_links ) : messages . success ( request , message = _ ( 'There are no orphaned files.' ) ) return HttpResponseRedirect ( '' ) if execute : form = DeleteOrphanedFilesForm ( queryset , orphaned_files_choices , request . POST ) if form . is_valid ( ) : form . save ( ) node = FileNode . get_top_node ( ) messages . success ( request , message = ungettext ( 'Deleted %i file from storage.' , 'Deleted %i files from storage.' , len ( form . success_files ) ) % len ( form . success_files ) ) if form . error_files : messages . error ( request , message = _ ( 'The following files could not be deleted from storage:' ) + ' ' + repr ( form . error_files ) ) return HttpResponseRedirect ( node . get_admin_url ( ) ) if not execute : if len ( orphaned_files_choices ) > 0 : form = DeleteOrphanedFilesForm ( queryset , orphaned_files_choices ) else : form = None c = get_actions_context ( modeladmin ) c . update ( { 'title' : _ ( 'Orphaned files' ) , 'submit_label' : _ ( 'Delete selected files' ) , 'form' : form , 'select_all' : 'selected_files' , 'node_list_title' : _ ( 'The following files in the database do not exist in storage. You should fix these media objects:' ) , 'node_list' : broken_node_links , } ) return render_to_response ( 'admin/media_tree/filenode/actions_form.html' , c , context_instance = RequestContext ( request ) ) | 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 ) ) cache_files_choices . append ( ( storage_name , link ) ) if not len ( cache_files_choices ) : messages . warning ( request , message = _ ( 'There are no cache files.' ) ) return HttpResponseRedirect ( '' ) if execute : form = DeleteCacheFilesForm ( queryset , cache_files_choices , request . POST ) if form . is_valid ( ) : form . save ( ) node = FileNode . get_top_node ( ) message = ungettext ( 'Deleted %i cache file.' , 'Deleted %i cache files.' , len ( form . success_files ) ) % len ( form . success_files ) if len ( form . success_files ) == len ( cache_files_choices ) : message = '%s %s' % ( _ ( 'The cache was cleared.' ) , message ) messages . success ( request , message = message ) if form . error_files : messages . error ( request , message = _ ( 'The following files could not be deleted:' ) + ' ' + repr ( form . error_files ) ) return HttpResponseRedirect ( node . get_admin_url ( ) ) if not execute : if len ( cache_files_choices ) > 0 : form = DeleteCacheFilesForm ( queryset , cache_files_choices ) else : form = None c = get_actions_context ( modeladmin ) c . update ( { 'title' : _ ( 'Clear cache' ) , 'submit_label' : _ ( 'Delete selected files' ) , 'form' : form , 'select_all' : 'selected_files' , } ) return render_to_response ( 'admin/media_tree/filenode/actions_form.html' , c , context_instance = RequestContext ( request ) ) return HttpResponseRedirect ( '' ) | 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_extension' ) : raise | 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 % add_text glue_format = glue_format_if_true if condition else glue_format_if_false return glue_format % ( text , add_text ) | 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 . pardir ) ) except StopIteration : raise utils . FileError ( "Invalid directory path: {0}" . format ( root ) ) log . info ( "Root directory found: {0}" . format ( root ) ) self . root = root try : with open ( os . path . join ( self . root , ".fmf" , "version" ) ) as version : self . version = int ( version . read ( ) ) log . info ( "Format version detected: {0}" . format ( self . version ) ) except IOError as error : raise utils . FormatError ( "Unable to detect format version: {0}" . format ( error ) ) except ValueError : raise utils . FormatError ( "Invalid version format" ) | 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 data : if type ( data [ key ] ) == type ( value ) == dict : data [ key ] . update ( value ) continue try : value = data [ key ] + value except TypeError as error : raise utils . MergeError ( "MergeError: Key '{0}' in {1} ({2})." . format ( key , self . name , str ( error ) ) ) data [ key ] = value self . data = data | 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 , value ) else : self . data [ key ] = value log . debug ( "Data for '{0}' updated." . format ( self ) ) log . data ( pretty ( self . data ) ) | 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 . append ( source ) | 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 ) ] ) try : filenames . insert ( 0 , filenames . pop ( filenames . index ( MAIN ) ) ) except ValueError : pass for filename in filenames : if filename . startswith ( "." ) : continue fullpath = os . path . abspath ( os . path . join ( dirpath , filename ) ) log . info ( "Checking file {0}" . format ( fullpath ) ) try : with open ( fullpath ) as datafile : data = yaml . load ( datafile , Loader = FullLoader ) except yaml . scanner . ScannerError as error : raise ( utils . FileError ( "Failed to parse '{0}'\n{1}" . format ( fullpath , error ) ) ) log . data ( pretty ( data ) ) if filename == MAIN : self . sources . append ( fullpath ) self . update ( data ) else : self . child ( os . path . splitext ( filename ) [ 0 ] , data , fullpath ) for dirname in sorted ( dirnames ) : if dirname . startswith ( "." ) : continue if os . path . isdir ( os . path . join ( path , dirname , SUFFIX ) ) : log . debug ( "Ignoring metadata tree '{0}'." . format ( dirname ) ) continue self . child ( dirname , os . path . join ( path , dirname ) ) for name in list ( self . children . keys ( ) ) : child = self . children [ name ] if not child . data and not child . children : del ( self . children [ name ] ) log . debug ( "Empty tree '{0}' removed." . format ( child . name ) ) if self . parent is None : self . inherit ( ) | 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 , node . data , regexp = True ) for filter in filters ] ) : continue except utils . FilterError : continue yield node | 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 , self . options . filters ) : if brief : show = node . show ( brief = True ) else : show = node . show ( brief = False , formatting = self . options . formatting , values = self . options . values ) if self . options . debug : for source in node . sources : show += utils . color ( "{0}\n" . format ( source ) , "blue" ) if show is not None : output . append ( show ) if brief or self . options . formatting : joined = "" . join ( output ) else : joined = "\n" . join ( output ) try : print ( joined , end = "" ) except UnicodeEncodeError : print ( joined . encode ( 'utf-8' ) , end = "" ) if self . options . verbose : utils . info ( "Found {0}." . format ( utils . listed ( len ( output ) , "object" ) ) ) self . output = joined | 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 ( "-" ) : atom = atom [ 1 : ] for dato in data [ dimension ] : if match_value ( atom , dato ) : break else : return True else : for dato in data [ dimension ] : if match_value ( atom , dato ) : return True return False def check_dimension ( dimension , values ) : if dimension not in data : raise FilterError ( "Invalid filter '{0}'" . format ( dimension ) ) return all ( [ check_value ( dimension , value ) for value in values ] ) def check_clause ( clause ) : literals = dict ( ) for literal in re . split ( "\s*&\s*" , clause ) : matched = re . match ( "^(.*)\s*:\s*(.*)$" , literal ) if not matched : raise FilterError ( "Invalid filter '{0}'" . format ( literal ) ) dimension , value = matched . groups ( ) values = [ value ] literals . setdefault ( dimension , [ ] ) . extend ( values ) return all ( [ check_dimension ( dimension , values ) for dimension , values in literals . items ( ) ] ) if filter is None or filter == "" : return True if not isinstance ( data , dict ) : raise FilterError ( "Invalid data type '{0}'" . format ( type ( data ) ) ) data = copy . deepcopy ( data ) try : for key in data : if isinstance ( data [ key ] , list ) : data [ key ] = [ unicode ( item ) for item in data [ key ] ] else : data [ key ] = [ unicode ( data [ key ] ) ] except NameError : for key in data : if isinstance ( data [ key ] , list ) : data [ key ] = [ str ( item ) for item in data [ key ] ] else : data [ key ] = [ str ( data [ key ] ) ] if not sensitive : filter = filter . lower ( ) lowered = dict ( ) for key , values in data . items ( ) : lowered [ key . lower ( ) ] = [ value . lower ( ) for value in values ] data = lowered return any ( [ check_clause ( clause ) for clause in re . split ( "\s*\|\s*" , filter ) ] ) | 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 and color . startswith ( "light" ) : light = True color = color [ 5 : ] color = color and ";{0}" . format ( colors [ color ] ) or "" background = background and ";{0}" . format ( colors [ background ] + 10 ) or "" light = light and 1 or 0 start = "\033[{0}{1}{2}m" . format ( light , color , background ) finish = "\033[1;m" return "" . join ( [ start , text , finish ] ) | 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 . DATA = LOG_DATA logger . CACHE = LOG_CACHE logger . ALL = LOG_ALL logger . cache = lambda message : logger . log ( LOG_CACHE , message ) logger . data = lambda message : logger . log ( LOG_DATA , message ) logger . all = lambda message : logger . log ( LOG_ALL , message ) return logger | 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' , args = ( self . get_path ( ) , ) ) elif self . is_folder ( ) : url = reverse ( 'admin:media_tree_filenode_changelist' ) query_params [ 'folder_id' ] = self . pk elif self . pk : return reverse ( 'admin:media_tree_filenode_change' , args = ( self . pk , ) ) if len ( query_params ) : params = [ '%s=%s' % ( key , value ) for key , value in query_params . items ( ) ] url = '%s?%s' % ( url , "&" . join ( params ) ) return url | 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_type != media_types . FOLDER : if include_extension : if extra != '' : extra += ' ' extra = '<span class="file-extension">%s</span>' % node . extension . upper ( ) if include_size : if extra != '' : extra += ', ' extra += '<span class="file-size">%s</span>' % filesizeformat ( node . size ) if extra : extra = ' <span class="details">(%s)</span>' % extra link_class = 'file %s' % node . extension else : link_class = 'folder' if extra_class : link_class = '%s %s' % ( link_class , extra_class ) if node . node_type != media_types . FOLDER and not href : href = node . file . url icon = '' if include_icon : icon_file = node . get_icon_file ( ) if icon_file : icon = '<span class="icon"><img src="%s" alt="%s" /></span>' % ( icon_file . url , node . alt ) if href : link = u'<a class="%s" href="%s">%s%s</a>%s' % ( link_class , href , icon , link_text , extra ) else : link = u'<span class="%s">%s%s</span>%s' % ( link_class , icon , link_text , extra ) return force_unicode ( mark_safe ( link ) ) | 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_path ( mod , build_module ) ) . as_posix ( ) . strip ( '.' ) , validate_name ( name ) ) | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.