idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
244,700
def _validate ( self , val ) : if not self . check_on_set : self . _ensure_value_is_in_objects ( val ) return if not ( val in self . objects or ( self . allow_None and val is None ) ) : try : attrib_name = self . name except AttributeError : attrib_name = "" items = [ ] limiter = ']' length = 0 for item in self . objec...
val must be None or one of the objects in self . objects .
244,701
def _ensure_value_is_in_objects ( self , val ) : if not ( val in self . objects ) : self . objects . append ( val )
Make sure that the provided value is present on the objects list . Subclasses can override if they support multiple items on a list to check each item instead .
244,702
def _validate ( self , val ) : if isinstance ( self . class_ , tuple ) : class_name = ( '(%s)' % ', ' . join ( cl . __name__ for cl in self . class_ ) ) else : class_name = self . class_ . __name__ if self . is_instance : if not ( isinstance ( val , self . class_ ) ) and not ( val is None and self . allow_None ) : rais...
val must be None an instance of self . class_ if self . is_instance = True or a subclass of self_class if self . is_instance = False
244,703
def get_range ( self ) : classes = concrete_descendents ( self . class_ ) d = OrderedDict ( ( name , class_ ) for name , class_ in classes . items ( ) ) if self . allow_None : d [ 'None' ] = None return d
Return the possible types for this parameter s value .
244,704
def _validate ( self , val ) : if self . allow_None and val is None : return if not isinstance ( val , list ) : raise ValueError ( "List '%s' must be a list." % ( self . name ) ) if self . bounds is not None : min_length , max_length = self . bounds l = len ( val ) if min_length is not None and max_length is not None :...
Checks that the list is of the right length and has the right contents . Otherwise an exception is raised .
244,705
def logging_level ( level ) : level = level . upper ( ) levels = [ DEBUG , INFO , WARNING , ERROR , CRITICAL , VERBOSE ] level_names = [ 'DEBUG' , 'INFO' , 'WARNING' , 'ERROR' , 'CRITICAL' , 'VERBOSE' ] if level not in level_names : raise Exception ( "Level %r not in %r" % ( level , levels ) ) param_logger = get_logger...
Temporarily modify param s logging level .
244,706
def batch_watch ( parameterized , run = True ) : BATCH_WATCH = parameterized . param . _BATCH_WATCH parameterized . param . _BATCH_WATCH = True try : yield finally : parameterized . param . _BATCH_WATCH = BATCH_WATCH if run and not BATCH_WATCH : parameterized . param . _batch_call_watchers ( )
Context manager to batch watcher events on a parameterized object . The context manager will queue any events triggered by setting a parameter on the supplied parameterized object and dispatch them all at once when the context manager exits . If run = False the queued events are not dispatched and should be processed m...
244,707
def get_all_slots ( class_ ) : all_slots = [ ] parent_param_classes = [ c for c in classlist ( class_ ) [ 1 : : ] ] for c in parent_param_classes : if hasattr ( c , '__slots__' ) : all_slots += c . __slots__ return all_slots
Return a list of slot names for slots defined in class_ and its superclasses .
244,708
def get_occupied_slots ( instance ) : return [ slot for slot in get_all_slots ( type ( instance ) ) if hasattr ( instance , slot ) ]
Return a list of slots for which values have been set .
244,709
def all_equal ( arg1 , arg2 ) : if all ( hasattr ( el , '_infinitely_iterable' ) for el in [ arg1 , arg2 ] ) : return arg1 == arg2 try : return all ( a1 == a2 for a1 , a2 in zip ( arg1 , arg2 ) ) except TypeError : return arg1 == arg2
Return a single boolean for arg1 == arg2 even for numpy arrays using element - wise comparison .
244,710
def output ( func , * output , ** kw ) : if output : outputs = [ ] for i , out in enumerate ( output ) : i = i if len ( output ) > 1 else None if isinstance ( out , tuple ) and len ( out ) == 2 and isinstance ( out [ 0 ] , str ) : outputs . append ( out + ( i , ) ) elif isinstance ( out , str ) : outputs . append ( ( o...
output allows annotating a method on a Parameterized class to declare that it returns an output of a specific type . The outputs of a Parameterized class can be queried using the Parameterized . param . outputs method . By default the output will inherit the method name but a custom name can be declared by expressing t...
244,711
def _setup_params ( self_ , ** params ) : self = self_ . param . self params_to_instantiate = { } for class_ in classlist ( type ( self ) ) : if not issubclass ( class_ , Parameterized ) : continue for ( k , v ) in class_ . __dict__ . items ( ) : if isinstance ( v , Parameter ) and v . instantiate and k != "name" : par...
Initialize default and keyword parameter values .
244,712
def deprecate ( cls , fn ) : def inner ( * args , ** kwargs ) : if cls . _disable_stubs : raise AssertionError ( 'Stubs supporting old API disabled' ) elif cls . _disable_stubs is None : pass elif cls . _disable_stubs is False : get_logger ( name = args [ 0 ] . __class__ . __name__ ) . log ( WARNING , 'Use method %r vi...
Decorator to issue warnings for API moving onto the param namespace and to add a docstring directing people to the appropriate method .
244,713
def print_param_defaults ( self_ ) : cls = self_ . cls for key , val in cls . __dict__ . items ( ) : if isinstance ( val , Parameter ) : print ( cls . __name__ + '.' + key + '=' + repr ( val . default ) )
Print the default values of all cls s Parameters .
244,714
def set_default ( self_ , param_name , value ) : cls = self_ . cls setattr ( cls , param_name , value )
Set the default value of param_name .
244,715
def _add_parameter ( self_ , param_name , param_obj ) : cls = self_ . cls type . __setattr__ ( cls , param_name , param_obj ) ParameterizedMetaclass . _initialize_parameter ( cls , param_name , param_obj ) try : delattr ( cls , '_%s__params' % cls . __name__ ) except AttributeError : pass
Add a new Parameter object into this object s class .
244,716
def set_param ( self_ , * args , ** kwargs ) : BATCH_WATCH = self_ . self_or_cls . param . _BATCH_WATCH self_ . self_or_cls . param . _BATCH_WATCH = True self_or_cls = self_ . self_or_cls if args : if len ( args ) == 2 and not args [ 0 ] in kwargs and not kwargs : kwargs [ args [ 0 ] ] = args [ 1 ] else : self_ . self_...
For each param = value keyword argument sets the corresponding parameter of this object or class to the given value .
244,717
def objects ( self_ , instance = True ) : cls = self_ . cls try : pdict = getattr ( cls , '_%s__params' % cls . __name__ ) except AttributeError : paramdict = { } for class_ in classlist ( cls ) : for name , val in class_ . __dict__ . items ( ) : if isinstance ( val , Parameter ) : paramdict [ name ] = val setattr ( cl...
Returns the Parameters of this instance or class
244,718
def trigger ( self_ , * param_names ) : events = self_ . self_or_cls . param . _events watchers = self_ . self_or_cls . param . _watchers self_ . self_or_cls . param . _events = [ ] self_ . self_or_cls . param . _watchers = [ ] param_values = dict ( self_ . get_param_values ( ) ) params = { name : param_values [ name ]...
Trigger watchers for the given set of parameter names . Watchers will be triggered whether or not the parameter values have actually changed .
244,719
def _update_event_type ( self_ , watcher , event , triggered ) : if triggered : event_type = 'triggered' else : event_type = 'changed' if watcher . onlychanged else 'set' return Event ( what = event . what , name = event . name , obj = event . obj , cls = event . cls , old = event . old , new = event . new , type = eve...
Returns an updated Event object with the type field set appropriately .
244,720
def _call_watcher ( self_ , watcher , event ) : if self_ . self_or_cls . param . _TRIGGER : pass elif watcher . onlychanged and ( not self_ . _changed ( event ) ) : return if self_ . self_or_cls . param . _BATCH_WATCH : self_ . _events . append ( event ) if watcher not in self_ . _watchers : self_ . _watchers . append ...
Invoke the given the watcher appropriately given a Event object .
244,721
def _batch_call_watchers ( self_ ) : while self_ . self_or_cls . param . _events : event_dict = OrderedDict ( [ ( ( event . name , event . what ) , event ) for event in self_ . self_or_cls . param . _events ] ) watchers = self_ . self_or_cls . param . _watchers [ : ] self_ . self_or_cls . param . _events = [ ] self_ . ...
Batch call a set of watchers based on the parameter value settings in kwargs using the queued Event and watcher objects .
244,722
def set_dynamic_time_fn ( self_ , time_fn , sublistattr = None ) : self_or_cls = self_ . self_or_cls self_or_cls . _Dynamic_time_fn = time_fn if isinstance ( self_or_cls , type ) : a = ( None , self_or_cls ) else : a = ( self_or_cls , ) for n , p in self_or_cls . param . objects ( 'existing' ) . items ( ) : if hasattr ...
Set time_fn for all Dynamic Parameters of this class or instance object that are currently being dynamically generated .
244,723
def get_param_values ( self_ , onlychanged = False ) : self_or_cls = self_ . self_or_cls vals = [ ] for name , val in self_or_cls . param . objects ( 'existing' ) . items ( ) : value = self_or_cls . param . get_value_generator ( name ) if not onlychanged or not all_equal ( value , val . default ) : vals . append ( ( na...
Return a list of name value pairs for all Parameters of this object .
244,724
def force_new_dynamic_value ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : return getattr ( cls_or_slf , name ) cls , slf = None , None if isinstance ( cls_or_slf , type ) : cls = cls_or_slf else : slf = cls_or_slf if not has...
Force a new value to be generated for the dynamic attribute name and return it .
244,725
def get_value_generator ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : value = getattr ( cls_or_slf , name ) elif hasattr ( param_obj , 'attribs' ) : value = [ cls_or_slf . param . get_value_generator ( a ) for a in param_obj...
Return the value or value - generating object of the named attribute .
244,726
def inspect_value ( self_ , name ) : cls_or_slf = self_ . self_or_cls param_obj = cls_or_slf . param . objects ( 'existing' ) . get ( name ) if not param_obj : value = getattr ( cls_or_slf , name ) elif hasattr ( param_obj , 'attribs' ) : value = [ cls_or_slf . param . inspect_value ( a ) for a in param_obj . attribs ]...
Return the current value of the named attribute without modifying it .
244,727
def outputs ( self_ ) : outputs = { } for cls in classlist ( self_ . cls ) : for name in dir ( cls ) : method = getattr ( self_ . self_or_cls , name ) dinfo = getattr ( method , '_dinfo' , { } ) if 'outputs' not in dinfo : continue for override , otype , idx in dinfo [ 'outputs' ] : if override is not None : name = ove...
Returns a mapping between any declared outputs and a tuple of the declared Parameter type the output method and the index into the output if multiple outputs are returned .
244,728
def unwatch ( self_ , watcher ) : try : self_ . _watch ( 'remove' , watcher ) except : self_ . warning ( 'No such watcher {watcher} to remove.' . format ( watcher = watcher ) )
Unwatch watchers set either with watch or watch_values .
244,729
def print_param_values ( self_ ) : self = self_ . self for name , val in self . param . get_param_values ( ) : print ( '%s.%s = %s' % ( self . name , name , val ) )
Print the values of all this object s Parameters .
244,730
def warning ( self_ , msg , * args , ** kw ) : if not warnings_as_exceptions : global warning_count warning_count += 1 self_ . __db_print ( WARNING , msg , * args , ** kw ) else : raise Exception ( "Warning: " + msg % args )
Print msg merged with args as a warning unless module variable warnings_as_exceptions is True then raise an Exception containing the arguments .
244,731
def message ( self_ , msg , * args , ** kw ) : self_ . __db_print ( INFO , msg , * args , ** kw )
Print msg merged with args as a message .
244,732
def verbose ( self_ , msg , * args , ** kw ) : self_ . __db_print ( VERBOSE , msg , * args , ** kw )
Print msg merged with args as a verbose message .
244,733
def debug ( self_ , msg , * args , ** kw ) : self_ . __db_print ( DEBUG , msg , * args , ** kw )
Print msg merged with args as a debugging statement .
244,734
def __class_docstring_signature ( mcs , max_repr_len = 15 ) : processed_kws , keyword_groups = set ( ) , [ ] for cls in reversed ( mcs . mro ( ) ) : keyword_group = [ ] for ( k , v ) in sorted ( cls . __dict__ . items ( ) ) : if isinstance ( v , Parameter ) and k not in processed_kws : param_type = v . __class__ . __na...
Autogenerate a keyword signature in the class docstring for all available parameters . This is particularly useful in the IPython Notebook as IPython will parse this signature to allow tab - completion of keywords .
244,735
def __param_inheritance ( mcs , param_name , param ) : slots = { } for p_class in classlist ( type ( param ) ) [ 1 : : ] : slots . update ( dict . fromkeys ( p_class . __slots__ ) ) setattr ( param , 'owner' , mcs ) del slots [ 'owner' ] if 'objtype' in slots : setattr ( param , 'objtype' , mcs ) del slots [ 'objtype' ...
Look for Parameter values in superclasses of this Parameterized class .
244,736
def _check_params ( self , params ) : overridden_object_params = list ( self . _overridden . param ) for item in params : if item not in overridden_object_params : self . param . warning ( "'%s' will be ignored (not a Parameter)." , item )
Print a warning if params contains something that is not a Parameter of the overridden object .
244,737
def _extract_extra_keywords ( self , params ) : extra_keywords = { } overridden_object_params = list ( self . _overridden . param ) for name , val in params . items ( ) : if name not in overridden_object_params : extra_keywords [ name ] = val return extra_keywords
Return any items in params that are not also parameters of the overridden object .
244,738
def instance ( self_or_cls , ** params ) : if isinstance ( self_or_cls , ParameterizedMetaclass ) : cls = self_or_cls else : p = params params = dict ( self_or_cls . get_param_values ( ) ) params . update ( p ) params . pop ( 'name' ) cls = self_or_cls . __class__ inst = Parameterized . __new__ ( cls ) Parameterized . ...
Return an instance of this class copying parameters from any existing instance provided .
244,739
def script_repr ( self , imports = [ ] , prefix = " " ) : return self . pprint ( imports , prefix , unknown_value = '' , qualify = True , separator = "\n" )
Same as Parameterized . script_repr except that X . classname ( Y is replaced with X . classname . instance ( Y
244,740
def pprint ( self , imports = None , prefix = "\n " , unknown_value = '<?>' , qualify = False , separator = "" ) : r = Parameterized . pprint ( self , imports , prefix , unknown_value = unknown_value , qualify = qualify , separator = separator ) classname = self . __class__ . __name__ return r . replace ( ".%s(" % c...
Same as Parameterized . pprint except that X . classname ( Y is replaced with X . classname . instance ( Y
244,741
def resolve_filename ( self , package_dir , filename ) : sass_path = os . path . join ( package_dir , self . sass_path , filename ) if self . strip_extension : filename , _ = os . path . splitext ( filename ) css_filename = filename + '.css' css_path = os . path . join ( package_dir , self . css_path , css_filename ) r...
Gets a proper full relative path of Sass source and CSS source that will be generated according to package_dir and filename .
244,742
def unresolve_filename ( self , package_dir , filename ) : filename , _ = os . path . splitext ( filename ) if self . strip_extension : for ext in ( '.scss' , '.sass' ) : test_path = os . path . join ( package_dir , self . sass_path , filename + ext , ) if os . path . exists ( test_path ) : return filename + ext else :...
Retrieves the probable source path from the output filename . Pass in a . css path to get out a . scss path .
244,743
def _validate_importers ( importers ) : if importers is None : return None def _to_importer ( priority , func ) : assert isinstance ( priority , int ) , priority assert callable ( func ) , func return ( priority , _importer_callback_wrapper ( func ) ) return tuple ( _to_importer ( priority , func ) for priority , func ...
Validates the importers and decorates the callables with our output formatter .
244,744
def and_join ( strings ) : last = len ( strings ) - 1 if last == 0 : return strings [ 0 ] elif last < 0 : return '' iterator = enumerate ( strings ) return ', ' . join ( 'and ' + s if i == last else s for i , s in iterator )
Join the given strings by commas with last and conjuction .
244,745
def allow_staff_or_superuser ( func ) : is_object_permission = "has_object" in func . __name__ @ wraps ( func ) def func_wrapper ( * args , ** kwargs ) : request = args [ 0 ] if is_object_permission : request = args [ 1 ] if request . user . is_staff or request . user . is_superuser : return True return func ( * args ,...
This decorator is used to abstract common is_staff and is_superuser functionality out of permission checks . It determines which parameter is the request based on name .
244,746
def authenticated_users ( func ) : is_object_permission = "has_object" in func . __name__ @ wraps ( func ) def func_wrapper ( * args , ** kwargs ) : request = args [ 0 ] if is_object_permission : request = args [ 1 ] if not ( request . user and request . user . is_authenticated ) : return False return func ( * args , *...
This decorator is used to abstract common authentication checking functionality out of permission checks . It determines which parameter is the request based on name .
244,747
def filter_queryset ( self , request , queryset , view ) : if view . lookup_field not in view . kwargs : if not self . action_routing : return self . filter_list_queryset ( request , queryset , view ) else : method_name = "filter_{action}_queryset" . format ( action = view . action ) return getattr ( self , method_name...
This method overrides the standard filter_queryset method . This method will check to see if the view calling this is from a list type action . This function will also route the filter by action type if action_routing is set to True .
244,748
def has_permission ( self , request , view ) : if not self . global_permissions : return True serializer_class = view . get_serializer_class ( ) assert serializer_class . Meta . model is not None , ( "global_permissions set to true without a model " "set on the serializer for '%s'" % view . __class__ . __name__ ) model...
Overrides the standard function and figures out methods to call for global permissions .
244,749
def has_object_permission ( self , request , view , obj ) : if not self . object_permissions : return True serializer_class = view . get_serializer_class ( ) model_class = serializer_class . Meta . model action_method_name = None if hasattr ( view , 'action' ) : action = self . _get_action ( view . action ) action_meth...
Overrides the standard function and figures out methods to call for object permissions .
244,750
def _get_action ( self , action ) : return_action = action if self . partial_update_is_update and action == 'partial_update' : return_action = 'update' return return_action
Utility function that consolidates actions if necessary .
244,751
def _get_error_message ( self , model_class , method_name , action_method_name ) : if action_method_name : return "'{}' does not have '{}' or '{}' defined." . format ( model_class , method_name , action_method_name ) else : return "'{}' does not have '{}' defined." . format ( model_class , method_name )
Get assertion error message depending if there are actions permissions methods defined .
244,752
def bind ( self , field_name , parent ) : assert parent . Meta . model is not None , "DRYPermissions is used on '{}' without a model" . format ( parent . __class__ . __name__ ) for action in self . actions : if not self . object_only : global_method_name = "has_{action}_permission" . format ( action = action ) if hasat...
Check the model attached to the serializer to see what methods are defined and save them .
244,753
def skip_prepare ( func ) : @ wraps ( func ) def _wrapper ( self , * args , ** kwargs ) : value = func ( self , * args , ** kwargs ) return Data ( value , should_prepare = False ) return _wrapper
A convenience decorator for indicating the raw data should not be prepared .
244,754
def build_error ( self , err ) : data = { 'error' : err . args [ 0 ] , } if self . is_debug ( ) : data [ 'traceback' ] = format_traceback ( sys . exc_info ( ) ) body = self . serializer . serialize ( data ) status = getattr ( err , 'status' , 500 ) return self . build_response ( body , status = status )
When an exception is encountered this generates a JSON error message for display to the user .
244,755
def deserialize ( self , method , endpoint , body ) : if endpoint == 'list' : return self . deserialize_list ( body ) return self . deserialize_detail ( body )
A convenience method for deserializing the body of a request .
244,756
def serialize ( self , method , endpoint , data ) : if endpoint == 'list' : if method == 'POST' : return self . serialize_detail ( data ) return self . serialize_list ( data ) return self . serialize_detail ( data )
A convenience method for serializing data for a response .
244,757
def _method ( self , * args , ** kwargs ) : yield self . resource_handler . handle ( self . __resource_view_type__ , * args , ** kwargs )
the body of those http - methods used in tornado . web . RequestHandler
244,758
def as_view ( cls , view_type , * init_args , ** init_kwargs ) : global _method new_cls = type ( cls . __name__ + '_' + _BridgeMixin . __name__ + '_restless' , ( _BridgeMixin , cls . _request_handler_base_ , ) , dict ( __resource_cls__ = cls , __resource_args__ = init_args , __resource_kwargs__ = init_kwargs , __resour...
Return a subclass of tornado . web . RequestHandler and apply required setting .
244,759
def handle ( self , endpoint , * args , ** kwargs ) : method = self . request_method ( ) try : if not method in self . http_methods . get ( endpoint , { } ) : raise MethodNotImplemented ( "Unsupported method '{}' for {} endpoint." . format ( method , endpoint ) ) if not self . is_authenticated ( ) : raise Unauthorized ...
almost identical to Resource . handle except the way we handle the return value of view_method .
244,760
def prepare ( self , data ) : result = { } if not self . fields : return data for fieldname , lookup in self . fields . items ( ) : if isinstance ( lookup , SubPreparer ) : result [ fieldname ] = lookup . prepare ( data ) else : result [ fieldname ] = self . lookup_data ( lookup , data ) return result
Handles transforming the provided data into the fielded data that should be exposed to the end user .
244,761
def lookup_data ( self , lookup , data ) : value = data parts = lookup . split ( '.' ) if not parts or not parts [ 0 ] : return value part = parts [ 0 ] remaining_lookup = '.' . join ( parts [ 1 : ] ) if callable ( getattr ( data , 'keys' , None ) ) and hasattr ( data , '__getitem__' ) : value = data [ part ] elif data...
Given a lookup string attempts to descend through nested data looking for the value .
244,762
def prepare ( self , data ) : result = [ ] for item in self . get_inner_data ( data ) : result . append ( self . preparer . prepare ( item ) ) return result
Handles passing each item in the collection data to the configured subpreparer .
244,763
def build_url_name ( cls , name , name_prefix = None ) : if name_prefix is None : name_prefix = 'api_{}' . format ( cls . __name__ . replace ( 'Resource' , '' ) . lower ( ) ) name_prefix = name_prefix . rstrip ( '_' ) return '_' . join ( [ name_prefix , name ] )
Given a name & an optional name_prefix this generates a name for a URL .
244,764
def build_endpoint_name ( cls , name , endpoint_prefix = None ) : if endpoint_prefix is None : endpoint_prefix = 'api_{}' . format ( cls . __name__ . replace ( 'Resource' , '' ) . lower ( ) ) endpoint_prefix = endpoint_prefix . rstrip ( '_' ) return '_' . join ( [ endpoint_prefix , name ] )
Given a name & an optional endpoint_prefix this generates a name for a URL .
244,765
def build_routename ( cls , name , routename_prefix = None ) : if routename_prefix is None : routename_prefix = 'api_{}' . format ( cls . __name__ . replace ( 'Resource' , '' ) . lower ( ) ) routename_prefix = routename_prefix . rstrip ( '_' ) return '_' . join ( [ routename_prefix , name ] )
Given a name & an optional routename_prefix this generates a name for a URL .
244,766
def add_views ( cls , config , rule_prefix , routename_prefix = None ) : methods = ( 'GET' , 'POST' , 'PUT' , 'DELETE' ) config . add_route ( cls . build_routename ( 'list' , routename_prefix ) , rule_prefix ) config . add_view ( cls . as_list ( ) , route_name = cls . build_routename ( 'list' , routename_prefix ) , req...
A convenience method for registering the routes and views in pyramid .
244,767
def deserialize ( self , body ) : try : if isinstance ( body , bytes ) : return json . loads ( body . decode ( 'utf-8' ) ) return json . loads ( body ) except ValueError : raise BadRequest ( 'Request body is not valid JSON' )
The low - level deserialization .
244,768
def convert_mnist ( directory , output_directory , output_filename = None , dtype = None ) : if not output_filename : if dtype : output_filename = 'mnist_{}.hdf5' . format ( dtype ) else : output_filename = 'mnist.hdf5' output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_...
Converts the MNIST dataset to HDF5 .
244,769
def fill_subparser ( subparser ) : subparser . add_argument ( "--dtype" , help = "dtype to save to; by default, images will be " + "returned in their original unsigned byte format" , choices = ( 'float32' , 'float64' , 'bool' ) , type = str , default = None ) return convert_mnist
Sets up a subparser to convert the MNIST dataset files .
244,770
def read_mnist_images ( filename , dtype = None ) : with gzip . open ( filename , 'rb' ) as f : magic , number , rows , cols = struct . unpack ( '>iiii' , f . read ( 16 ) ) if magic != MNIST_IMAGE_MAGIC : raise ValueError ( "Wrong magic number reading MNIST image file" ) array = numpy . frombuffer ( f . read ( ) , dtyp...
Read MNIST images from the original ubyte file format .
244,771
def read_mnist_labels ( filename ) : with gzip . open ( filename , 'rb' ) as f : magic , _ = struct . unpack ( '>ii' , f . read ( 8 ) ) if magic != MNIST_LABEL_MAGIC : raise ValueError ( "Wrong magic number reading MNIST label file" ) array = numpy . frombuffer ( f . read ( ) , dtype = 'uint8' ) array = array . reshape...
Read MNIST labels from the original ubyte file format .
244,772
def prepare_hdf5_file ( hdf5_file , n_train , n_valid , n_test ) : n_total = n_train + n_valid + n_test splits = create_splits ( n_train , n_valid , n_test ) hdf5_file . attrs [ 'split' ] = H5PYDataset . create_split_array ( splits ) vlen_dtype = h5py . special_dtype ( vlen = numpy . dtype ( 'uint8' ) ) hdf5_file . cre...
Create datasets within a given HDF5 file .
244,773
def process_train_set ( hdf5_file , train_archive , patch_archive , n_train , wnid_map , shuffle_seed = None ) : producer = partial ( train_set_producer , train_archive = train_archive , patch_archive = patch_archive , wnid_map = wnid_map ) consumer = partial ( image_consumer , hdf5_file = hdf5_file , num_expected = n_...
Process the ILSVRC2010 training set .
244,774
def image_consumer ( socket , hdf5_file , num_expected , shuffle_seed = None , offset = 0 ) : with progress_bar ( 'images' , maxval = num_expected ) as pb : if shuffle_seed is None : index_gen = iter ( xrange ( num_expected ) ) else : rng = numpy . random . RandomState ( shuffle_seed ) index_gen = iter ( rng . permutat...
Fill an HDF5 file with incoming images from a socket .
244,775
def process_other_set ( hdf5_file , which_set , image_archive , patch_archive , groundtruth , offset ) : producer = partial ( other_set_producer , image_archive = image_archive , patch_archive = patch_archive , groundtruth = groundtruth , which_set = which_set ) consumer = partial ( image_consumer , hdf5_file = hdf5_fi...
Process the validation or test set .
244,776
def load_from_tar_or_patch ( tar , image_filename , patch_images ) : patched = True image_bytes = patch_images . get ( os . path . basename ( image_filename ) , None ) if image_bytes is None : patched = False try : image_bytes = tar . extractfile ( image_filename ) . read ( ) numpy . array ( Image . open ( io . BytesIO...
Do everything necessary to process an image inside a TAR .
244,777
def read_devkit ( f ) : with tar_open ( f ) as tar : meta_mat = tar . extractfile ( DEVKIT_META_PATH ) synsets , cost_matrix = read_metadata_mat_file ( meta_mat ) raw_valid_groundtruth = numpy . loadtxt ( tar . extractfile ( DEVKIT_VALID_GROUNDTRUTH_PATH ) , dtype = numpy . int16 ) return synsets , cost_matrix , raw_va...
Read relevant information from the development kit archive .
244,778
def extract_patch_images ( f , which_set ) : if which_set not in ( 'train' , 'valid' , 'test' ) : raise ValueError ( 'which_set must be one of train, valid, or test' ) which_set = 'val' if which_set == 'valid' else which_set patch_images = { } with tar_open ( f ) as tar : for info_obj in tar : if not info_obj . name . ...
Extracts a dict of the patch images for ILSVRC2010 .
244,779
def convert_cifar10 ( directory , output_directory , output_filename = 'cifar10.hdf5' ) : output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_path , mode = 'w' ) input_file = os . path . join ( directory , DISTRIBUTION_FILE ) tar_file = tarfile . open ( input_file , 'r:gz...
Converts the CIFAR - 10 dataset to HDF5 .
244,780
def check_exists ( required_files ) : def function_wrapper ( f ) : @ wraps ( f ) def wrapped ( directory , * args , ** kwargs ) : missing = [ ] for filename in required_files : if not os . path . isfile ( os . path . join ( directory , filename ) ) : missing . append ( filename ) if len ( missing ) > 0 : raise MissingI...
Decorator that checks if required files exist before running .
244,781
def fill_hdf5_file ( h5file , data ) : split_names = set ( split_tuple [ 0 ] for split_tuple in data ) for name in split_names : lengths = [ len ( split_tuple [ 2 ] ) for split_tuple in data if split_tuple [ 0 ] == name ] if not all ( le == lengths [ 0 ] for le in lengths ) : raise ValueError ( "split '{}' has sources ...
Fills an HDF5 file in a H5PYDataset - compatible manner .
244,782
def progress_bar ( name , maxval , prefix = 'Converting' ) : widgets = [ '{} {}: ' . format ( prefix , name ) , Percentage ( ) , ' ' , Bar ( marker = '=' , left = '[' , right = ']' ) , ' ' , ETA ( ) ] bar = ProgressBar ( widgets = widgets , max_value = maxval , fd = sys . stdout ) . start ( ) try : yield bar finally : ...
Manages a progress bar for a conversion .
244,783
def convert_iris ( directory , output_directory , output_filename = 'iris.hdf5' ) : classes = { b'Iris-setosa' : 0 , b'Iris-versicolor' : 1 , b'Iris-virginica' : 2 } data = numpy . loadtxt ( os . path . join ( directory , 'iris.data' ) , converters = { 4 : lambda x : classes [ x ] } , delimiter = ',' ) features = data ...
Convert the Iris dataset to HDF5 .
244,784
def fill_subparser ( subparser ) : urls = ( [ None ] * len ( ALL_FILES ) ) filenames = list ( ALL_FILES ) subparser . set_defaults ( urls = urls , filenames = filenames ) subparser . add_argument ( '-P' , '--url-prefix' , type = str , default = None , help = "URL prefix to prepend to the filenames of " "non-public file...
Sets up a subparser to download the ILSVRC2012 dataset files .
244,785
def _get_target_index ( self ) : return ( self . index + self . source_window * ( not self . overlapping ) + self . offset )
Return the index where the target window starts .
244,786
def _get_end_index ( self ) : return max ( self . index + self . source_window , self . _get_target_index ( ) + self . target_window )
Return the end of both windows .
244,787
def convert_svhn ( which_format , directory , output_directory , output_filename = None ) : if which_format not in ( 1 , 2 ) : raise ValueError ( "SVHN format needs to be either 1 or 2." ) if not output_filename : output_filename = 'svhn_format_{}.hdf5' . format ( which_format ) if which_format == 1 : return convert_sv...
Converts the SVHN dataset to HDF5 .
244,788
def open_ ( filename , mode = 'r' , encoding = None ) : if filename . endswith ( '.gz' ) : if six . PY2 : zf = io . BufferedReader ( gzip . open ( filename , mode ) ) if encoding : return codecs . getreader ( encoding ) ( zf ) else : return zf else : return io . BufferedReader ( gzip . open ( filename , mode , encoding...
Open a text file with encoding and optional gzip compression .
244,789
def tar_open ( f ) : if isinstance ( f , six . string_types ) : return tarfile . open ( name = f ) else : return tarfile . open ( fileobj = f )
Open either a filename or a file - like object as a TarFile .
244,790
def copy_from_server_to_local ( dataset_remote_dir , dataset_local_dir , remote_fname , local_fname ) : log . debug ( "Copying file `{}` to a local directory `{}`." . format ( remote_fname , dataset_local_dir ) ) head , tail = os . path . split ( local_fname ) head += os . path . sep if not os . path . exists ( head ) ...
Copies a remote file locally .
244,791
def convert_to_one_hot ( y ) : max_value = max ( y ) min_value = min ( y ) length = len ( y ) one_hot = numpy . zeros ( ( length , ( max_value - min_value + 1 ) ) ) one_hot [ numpy . arange ( length ) , y ] = 1 return one_hot
converts y into one hot reprsentation .
244,792
def convert_binarized_mnist ( directory , output_directory , output_filename = 'binarized_mnist.hdf5' ) : output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_path , mode = 'w' ) train_set = numpy . loadtxt ( os . path . join ( directory , TRAIN_FILE ) ) . reshape ( ( - 1 ...
Converts the binarized MNIST dataset to HDF5 .
244,793
def fill_subparser ( subparser ) : url = 'http://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz' filename = 'cifar-10-python.tar.gz' subparser . set_defaults ( urls = [ url ] , filenames = [ filename ] ) return default_downloader
Sets up a subparser to download the CIFAR - 10 dataset file .
244,794
def convert_celeba_aligned_cropped ( directory , output_directory , output_filename = OUTPUT_FILENAME ) : output_path = os . path . join ( output_directory , output_filename ) h5file = _initialize_conversion ( directory , output_path , ( 218 , 178 ) ) features_dataset = h5file [ 'features' ] image_file_path = os . path...
Converts the aligned and cropped CelebA dataset to HDF5 .
244,795
def convert_celeba ( which_format , directory , output_directory , output_filename = None ) : if which_format not in ( 'aligned_cropped' , '64' ) : raise ValueError ( "CelebA format needs to be either " "'aligned_cropped' or '64'." ) if not output_filename : output_filename = 'celeba_{}.hdf5' . format ( which_format ) ...
Converts the CelebA dataset to HDF5 .
244,796
def disk_usage ( path ) : st = os . statvfs ( path ) total = st . f_blocks * st . f_frsize used = ( st . f_blocks - st . f_bfree ) * st . f_frsize return total , used
Return free usage about the given path in bytes .
244,797
def safe_mkdir ( folder_name , force_perm = None ) : if os . path . exists ( folder_name ) : return intermediary_folders = folder_name . split ( os . path . sep ) if intermediary_folders [ - 1 ] == "" : intermediary_folders = intermediary_folders [ : - 1 ] if force_perm : force_perm_path = folder_name . split ( os . pa...
Create the specified folder .
244,798
def check_enough_space ( dataset_local_dir , remote_fname , local_fname , max_disk_usage = 0.9 ) : storage_need = os . path . getsize ( remote_fname ) storage_total , storage_used = disk_usage ( dataset_local_dir ) return ( ( storage_used + storage_need ) < ( storage_total * max_disk_usage ) )
Check if the given local folder has enough space .
244,799
def convert_cifar100 ( directory , output_directory , output_filename = 'cifar100.hdf5' ) : output_path = os . path . join ( output_directory , output_filename ) h5file = h5py . File ( output_path , mode = "w" ) input_file = os . path . join ( directory , 'cifar-100-python.tar.gz' ) tar_file = tarfile . open ( input_fi...
Converts the CIFAR - 100 dataset to HDF5 .