idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
56,300 | def toseries ( self ) : from thunder . series . series import Series if self . mode == 'spark' : values = self . values . values_to_keys ( tuple ( range ( 1 , len ( self . shape ) ) ) ) . unchunk ( ) if self . mode == 'local' : values = self . values . unchunk ( ) values = rollaxis ( values , 0 , values . ndim ) return... | Converts blocks to series . |
56,301 | def toarray ( self ) : if self . mode == 'spark' : return self . values . unchunk ( ) . toarray ( ) if self . mode == 'local' : return self . values . unchunk ( ) | Convert blocks to local ndarray |
56,302 | def flatten ( self ) : size = prod ( self . shape [ : - 1 ] ) return self . reshape ( size , self . shape [ - 1 ] ) | Reshape all dimensions but the last into a single dimension |
56,303 | def tospark ( self , engine = None ) : from thunder . series . readers import fromarray if self . mode == 'spark' : logging . getLogger ( 'thunder' ) . warn ( 'images already in local mode' ) pass if engine is None : raise ValueError ( 'Must provide SparkContext' ) return fromarray ( self . toarray ( ) , index = self .... | Convert to spark mode . |
56,304 | def sample ( self , n = 100 , seed = None ) : if n < 1 : raise ValueError ( "Number of samples must be larger than 0, got '%g'" % n ) if seed is None : seed = random . randint ( 0 , 2 ** 32 ) if self . mode == 'spark' : result = asarray ( self . values . tordd ( ) . values ( ) . takeSample ( False , n , seed ) ) else :... | Extract random sample of records . |
56,305 | def map ( self , func , index = None , value_shape = None , dtype = None , with_keys = False ) : if value_shape is None and index is not None : value_shape = len ( index ) if isinstance ( value_shape , int ) : values_shape = ( value_shape , ) new = super ( Series , self ) . map ( func , value_shape = value_shape , dtyp... | Map an array - > array function over each record . |
56,306 | def mean ( self ) : return self . _constructor ( self . values . mean ( axis = self . baseaxes , keepdims = True ) ) | Compute the mean across records |
56,307 | def sum ( self ) : return self . _constructor ( self . values . sum ( axis = self . baseaxes , keepdims = True ) ) | Compute the sum across records . |
56,308 | def max ( self ) : return self . _constructor ( self . values . max ( axis = self . baseaxes , keepdims = True ) ) | Compute the max across records . |
56,309 | def min ( self ) : return self . _constructor ( self . values . min ( axis = self . baseaxes , keepdims = True ) ) | Compute the min across records . |
56,310 | def reshape ( self , * shape ) : if prod ( self . shape ) != prod ( shape ) : raise ValueError ( "Reshaping must leave the number of elements unchanged" ) if self . shape [ - 1 ] != shape [ - 1 ] : raise ValueError ( "Reshaping cannot change the size of the constituent series (last dimension)" ) if self . labels is not... | Reshape the Series object |
56,311 | def between ( self , left , right ) : crit = lambda x : left <= x < right return self . select ( crit ) | Select subset of values within the given index range . |
56,312 | def select ( self , crit ) : import types if not isinstance ( crit , types . FunctionType ) : if isinstance ( crit , string_types ) : critlist = set ( [ crit ] ) else : try : critlist = set ( crit ) except TypeError : critlist = set ( [ crit ] ) crit = lambda x : x in critlist index = self . index if size ( index ) == ... | Select subset of values that match a given index criterion . |
56,313 | def center ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x - mean ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) return self . map ( lambda x : x - meanval ) else : raise Exception ( 'Axis must be 0 or 1' ) | Subtract the mean either within or across records . |
56,314 | def standardize ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : x / std ( x ) ) elif axis == 0 : stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : x / stdval ) else : raise Exception ( 'Axis must be 0 or 1' ) | Divide by standard deviation either within or across records . |
56,315 | def zscore ( self , axis = 1 ) : if axis == 1 : return self . map ( lambda x : ( x - mean ( x ) ) / std ( x ) ) elif axis == 0 : meanval = self . mean ( ) . toarray ( ) stdval = self . std ( ) . toarray ( ) return self . map ( lambda x : ( x - meanval ) / stdval ) else : raise Exception ( 'Axis must be 0 or 1' ) | Subtract the mean and divide by standard deviation within or across records . |
56,316 | def squelch ( self , threshold ) : func = lambda x : zeros ( x . shape ) if max ( x ) < threshold else x return self . map ( func ) | Set all records that do not exceed the given threhsold to 0 . |
56,317 | def correlate ( self , signal ) : s = asarray ( signal ) if s . ndim == 1 : if size ( s ) != self . shape [ - 1 ] : raise ValueError ( "Length of signal '%g' does not match record length '%g'" % ( size ( s ) , self . shape [ - 1 ] ) ) return self . map ( lambda x : corrcoef ( x , s ) [ 0 , 1 ] , index = [ 1 ] ) elif s ... | Correlate records against one or many one - dimensional arrays . |
56,318 | def _check_panel ( self , length ) : n = len ( self . index ) if divmod ( n , length ) [ 1 ] != 0 : raise ValueError ( "Panel length '%g' must evenly divide length of series '%g'" % ( length , n ) ) if n == length : raise ValueError ( "Panel length '%g' cannot be length of series '%g'" % ( length , n ) ) | Check that given fixed panel length evenly divides index . |
56,319 | def mean_by_panel ( self , length ) : self . _check_panel ( length ) func = lambda v : v . reshape ( - 1 , length ) . mean ( axis = 0 ) newindex = arange ( length ) return self . map ( func , index = newindex ) | Compute the mean across fixed sized panels of each record . |
56,320 | def _makemasks ( self , index = None , level = 0 ) : if index is None : index = self . index try : dims = len ( array ( index ) . shape ) if dims == 1 : index = array ( index , ndmin = 2 ) . T except : raise TypeError ( 'A multi-index must be convertible to a numpy ndarray' ) try : index = index [ : , level ] except : ... | Internal function for generating masks for selecting values based on multi - index values . |
56,321 | def _map_by_index ( self , function , level = 0 ) : if type ( level ) is int : level = [ level ] masks , ind = self . _makemasks ( index = self . index , level = level ) nMasks = len ( masks ) newindex = array ( ind ) if len ( newindex [ 0 ] ) == 1 : newindex = ravel ( newindex ) return self . map ( lambda v : asarray ... | An internal function for maping a function to groups of values based on a multi - index |
56,322 | def aggregate_by_index ( self , function , level = 0 ) : result = self . _map_by_index ( function , level = level ) return result . map ( lambda v : array ( v ) , index = result . index ) | Aggregrate data in each record grouping by index values . |
56,323 | def gramian ( self ) : if self . mode == 'spark' : rdd = self . values . tordd ( ) from pyspark . accumulators import AccumulatorParam class MatrixAccumulator ( AccumulatorParam ) : def zero ( self , value ) : return zeros ( shape ( value ) ) def addInPlace ( self , val1 , val2 ) : val1 += val2 return val1 global mat i... | Compute gramian of a distributed matrix . |
56,324 | def times ( self , other ) : if isinstance ( other , ScalarType ) : other = asarray ( other ) index = self . index else : if isinstance ( other , list ) : other = asarray ( other ) if isinstance ( other , ndarray ) and other . ndim < 2 : other = expand_dims ( other , 1 ) if not self . shape [ 1 ] == other . shape [ 0 ]... | Multiply a matrix by another one . |
56,325 | def _makewindows ( self , indices , window ) : div = divmod ( window , 2 ) before = div [ 0 ] after = div [ 0 ] + div [ 1 ] index = asarray ( self . index ) indices = asarray ( indices ) if where ( index == max ( indices ) ) [ 0 ] [ 0 ] + after > len ( index ) : raise ValueError ( "Maximum requested index %g, with wind... | Make masks used by windowing functions |
56,326 | def mean_by_window ( self , indices , window ) : masks = self . _makewindows ( indices , window ) newindex = arange ( 0 , len ( masks [ 0 ] ) ) return self . map ( lambda x : mean ( [ x [ m ] for m in masks ] , axis = 0 ) , index = newindex ) | Average series across multiple windows specified by their centers . |
56,327 | def subsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) s = slice ( 0 , len ( self . index ) , sample_factor ) newindex = self . index [ s ] return self . map ( lambda v : v [ s ] , index = newindex ) | Subsample series by an integer factor . |
56,328 | def downsample ( self , sample_factor = 2 ) : if sample_factor < 0 : raise Exception ( 'Factor for subsampling must be postive, got %g' % sample_factor ) newlength = floor ( len ( self . index ) / sample_factor ) func = lambda v : v [ 0 : int ( newlength * sample_factor ) ] . reshape ( - 1 , sample_factor ) . mean ( ax... | Downsample series by an integer factor by averaging . |
56,329 | def fourier ( self , freq = None ) : def get ( y , freq ) : y = y - mean ( y ) nframes = len ( y ) ft = fft . fft ( y ) ft = ft [ 0 : int ( fix ( nframes / 2 ) ) ] ampFt = 2 * abs ( ft ) / nframes amp = ampFt [ freq ] ampSum = sqrt ( sum ( ampFt ** 2 ) ) co = amp / ampSum ph = - ( pi / 2 ) - angle ( ft [ freq ] ) if ph... | Compute statistics of a Fourier decomposition on series data . |
56,330 | def convolve ( self , signal , mode = 'full' ) : from numpy import convolve s = asarray ( signal ) n = size ( self . index ) m = size ( s ) if mode == 'same' : newmax = max ( n , m ) elif mode == 'valid' : newmax = max ( m , n ) - min ( m , n ) + 1 else : newmax = n + m - 1 newindex = arange ( 0 , newmax ) return self ... | Convolve series data against another signal . |
56,331 | def crosscorr ( self , signal , lag = 0 ) : from scipy . linalg import norm s = asarray ( signal ) s = s - mean ( s ) s = s / norm ( s ) if size ( s ) != size ( self . index ) : raise Exception ( 'Size of signal to cross correlate with, %g, ' 'does not match size of series' % size ( s ) ) if lag is not 0 : shifts = ran... | Cross correlate series data against another signal . |
56,332 | def detrend ( self , method = 'linear' , order = 5 ) : check_options ( method , [ 'linear' , 'nonlinear' ] ) if method == 'linear' : order = 1 def func ( y ) : x = arange ( len ( y ) ) p = polyfit ( x , y , order ) p [ - 1 ] = 0 yy = polyval ( p , x ) return y - yy return self . map ( func ) | Detrend series data with linear or nonlinear detrending . |
56,333 | def normalize ( self , method = 'percentile' , window = None , perc = 20 , offset = 0.1 ) : check_options ( method , [ 'mean' , 'percentile' , 'window' , 'window-exact' ] ) from warnings import warn if not ( method == 'window' or method == 'window-exact' ) and window is not None : warn ( 'Setting window without using m... | Normalize by subtracting and dividing by a baseline . |
56,334 | def toimages ( self , chunk_size = 'auto' ) : from thunder . images . images import Images if chunk_size is 'auto' : chunk_size = str ( max ( [ int ( 1e5 / prod ( self . baseshape ) ) , 1 ] ) ) n = len ( self . shape ) - 1 if self . mode == 'spark' : return Images ( self . values . swap ( tuple ( range ( n ) ) , ( 0 , ... | Converts to images data . |
56,335 | def tobinary ( self , path , prefix = 'series' , overwrite = False , credentials = None ) : from thunder . series . writers import tobinary tobinary ( self , path , prefix = prefix , overwrite = overwrite , credentials = credentials ) | Write data to binary files . |
56,336 | def addextension ( path , ext = None ) : if ext : if '*' in path : return path elif os . path . splitext ( path ) [ 1 ] : return path else : if not ext . startswith ( '.' ) : ext = '.' + ext if not path . endswith ( ext ) : if not path . endswith ( os . path . sep ) : path += os . path . sep return path + '*' + ext els... | Helper function for handling of paths given separately passed file extensions . |
56,337 | def select ( files , start , stop ) : if start or stop : if start is None : start = 0 if stop is None : stop = len ( files ) files = files [ start : stop ] return files | Helper function for handling start and stop indices |
56,338 | def listrecursive ( path , ext = None ) : filenames = set ( ) for root , dirs , files in os . walk ( path ) : if ext : if ext == 'tif' or ext == 'tiff' : tmp = fnmatch . filter ( files , '*.' + 'tiff' ) files = tmp + fnmatch . filter ( files , '*.' + 'tif' ) else : files = fnmatch . filter ( files , '*.' + ext ) for fi... | List files recurisvely |
56,339 | def listflat ( path , ext = None ) : if os . path . isdir ( path ) : if ext : if ext == 'tif' or ext == 'tiff' : files = glob . glob ( os . path . join ( path , '*.tif' ) ) files = files + glob . glob ( os . path . join ( path , '*.tiff' ) ) else : files = glob . glob ( os . path . join ( path , '*.' + ext ) ) else : f... | List files without recursion |
56,340 | def normalize_scheme ( path , ext ) : path = addextension ( path , ext ) parsed = urlparse ( path ) if parsed . scheme : return path else : import os dirname , filename = os . path . split ( path ) if not os . path . isabs ( dirname ) : dirname = os . path . abspath ( dirname ) path = os . path . join ( dirname , filen... | Normalize scheme for paths related to hdfs |
56,341 | def list ( path , ext = None , start = None , stop = None , recursive = False ) : files = listflat ( path , ext ) if not recursive else listrecursive ( path , ext ) if len ( files ) < 1 : raise FileNotFoundError ( 'Cannot find files of type "%s" in %s' % ( ext if ext else '*' , path ) ) files = select ( files , start ,... | Get sorted list of file paths matching path and extension |
56,342 | def read ( self , path , ext = None , start = None , stop = None , recursive = False , npartitions = None ) : path = uri_to_path ( path ) files = self . list ( path , ext = ext , start = start , stop = stop , recursive = recursive ) nfiles = len ( files ) self . nfiles = nfiles if spark and isinstance ( self . engine ,... | Sets up Spark RDD across files specified by dataPath on local filesystem . |
56,343 | def list ( path , filename = None , start = None , stop = None , recursive = False , directories = False ) : path = uri_to_path ( path ) if not filename and recursive : return listrecursive ( path ) if filename : if os . path . isdir ( path ) : path = os . path . join ( path , filename ) else : path = os . path . join ... | List files specified by dataPath . |
56,344 | def parse_query ( query , delim = '/' ) : key = '' prefix = '' postfix = '' parsed = urlparse ( query ) query = parsed . path . lstrip ( delim ) bucket = parsed . netloc if not parsed . scheme . lower ( ) in ( '' , "gs" , "s3" , "s3n" ) : raise ValueError ( "Query scheme must be one of '', 'gs', 's3', or 's3n'; " "got:... | Parse a boto query |
56,345 | def retrieve_keys ( bucket , key , prefix = '' , postfix = '' , delim = '/' , directories = False , recursive = False ) : if key and prefix : assert key . endswith ( delim ) key += prefix if not key . endswith ( delim ) and key : if BotoClient . check_prefix ( bucket , key + delim , delim = delim ) : key += delim listd... | Retrieve keys from a bucket |
56,346 | def getfiles ( self , path , ext = None , start = None , stop = None , recursive = False ) : from . utils import connection_with_anon , connection_with_gs parse = BotoClient . parse_query ( path ) scheme = parse [ 0 ] bucket_name = parse [ 1 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( self . ... | Get scheme bucket and keys for a set of files |
56,347 | def list ( self , dataPath , ext = None , start = None , stop = None , recursive = False ) : scheme , bucket_name , keylist = self . getfiles ( dataPath , ext = ext , start = start , stop = stop , recursive = recursive ) return [ "%s:///%s/%s" % ( scheme , bucket_name , key ) for key in keylist ] | List files from remote storage |
56,348 | def read ( self , path , ext = None , start = None , stop = None , recursive = False , npartitions = None ) : from . utils import connection_with_anon , connection_with_gs path = addextension ( path , ext ) scheme , bucket_name , keylist = self . getfiles ( path , start = start , stop = stop , recursive = recursive ) i... | Sets up Spark RDD across S3 or GS objects specified by dataPath . |
56,349 | def getkeys ( self , path , filename = None , directories = False , recursive = False ) : from . utils import connection_with_anon , connection_with_gs parse = BotoClient . parse_query ( path ) scheme = parse [ 0 ] bucket_name = parse [ 1 ] key = parse [ 2 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with... | Get matching keys for a path |
56,350 | def getkey ( self , path , filename = None ) : scheme , keys = self . getkeys ( path , filename = filename ) try : key = next ( keys ) except StopIteration : raise FileNotFoundError ( "Could not find object for: '%s'" % path ) nextKey = None try : nextKey = next ( keys ) except StopIteration : pass if nextKey : raise V... | Get single matching key for a path |
56,351 | def list ( self , path , filename = None , start = None , stop = None , recursive = False , directories = False ) : storageScheme , keys = self . getkeys ( path , filename = filename , directories = directories , recursive = recursive ) keys = [ storageScheme + ":///" + key . bucket . name + "/" + key . name for key in... | List objects specified by path . |
56,352 | def read ( self , path , filename = None , offset = None , size = - 1 ) : storageScheme , key = self . getkey ( path , filename = filename ) if offset or ( size > - 1 ) : if not offset : offset = 0 if size > - 1 : sizeStr = offset + size - 1 else : sizeStr = "" headers = { "Range" : "bytes=%d-%s" % ( offset , sizeStr )... | Read a file specified by path . |
56,353 | def open ( self , path , filename = None ) : scheme , key = self . getkey ( path , filename = filename ) return BotoReadFileHandle ( scheme , key ) | Open a file specified by path . |
56,354 | def check_path ( path , credentials = None ) : from thunder . readers import get_file_reader reader = get_file_reader ( path ) ( credentials = credentials ) existing = reader . list ( path , directories = True ) if existing : raise ValueError ( 'Path %s appears to already exist. Specify a new directory, ' 'or call with... | Check that specified output path does not already exist |
56,355 | def connection_with_anon ( credentials , anon = True ) : from boto . s3 . connection import S3Connection from boto . exception import NoAuthHandlerFound try : conn = S3Connection ( aws_access_key_id = credentials [ 'access' ] , aws_secret_access_key = credentials [ 'secret' ] ) return conn except NoAuthHandlerFound : i... | Connect to S3 with automatic handling for anonymous access . |
56,356 | def activate ( self , path , isdirectory ) : from . utils import connection_with_anon , connection_with_gs parsed = BotoClient . parse_query ( path ) scheme = parsed [ 0 ] bucket_name = parsed [ 1 ] key = parsed [ 2 ] if scheme == 's3' or scheme == 's3n' : conn = connection_with_anon ( self . credentials ) bucket = con... | Set up a boto connection . |
56,357 | def topng ( images , path , prefix = "image" , overwrite = False , credentials = None ) : value_shape = images . value_shape if not len ( value_shape ) in [ 2 , 3 ] : raise ValueError ( "Only 2D or 3D images can be exported to png, " "images are %d-dimensional." % len ( value_shape ) ) from scipy . misc import imsave f... | Write out PNG files for 2d image data . |
56,358 | def tobinary ( images , path , prefix = "image" , overwrite = False , credentials = None ) : from thunder . writers import get_parallel_writer def tobuffer ( kv ) : key , img = kv fname = prefix + "-" + "%05d.bin" % int ( key ) return fname , img . copy ( ) writer = get_parallel_writer ( path ) ( path , overwrite = ove... | Write out images as binary files . |
56,359 | def yearInfo2yearDay ( yearInfo ) : yearInfo = int ( yearInfo ) res = 29 * 12 leap = False if yearInfo % 16 != 0 : leap = True res += 29 yearInfo //= 16 for i in range ( 12 + leap ) : if yearInfo % 2 == 1 : res += 1 yearInfo //= 2 return res | calculate the days in a lunar year from the lunar year s info |
56,360 | def cleanupFilename ( self , name ) : context = self . context id = '' name = name . replace ( '\\' , '/' ) name = name . split ( '/' ) [ - 1 ] for c in name : if c . isalnum ( ) or c in '._' : id += c if context . check_id ( id ) is None and getattr ( context , id , None ) is None : return id count = 1 while 1 : if co... | Generate a unique id which doesn t match the system generated ids |
56,361 | def parse_data_slots ( value ) : value = unquote ( value ) if '>' in value : wrappers , children = value . split ( '>' , 1 ) else : wrappers = value children = '' if '*' in children : prepends , appends = children . split ( '*' , 1 ) else : prepends = children appends = '' wrappers = list ( filter ( bool , list ( map (... | Parse data - slots value into slots used to wrap node prepend to node or append to node . |
56,362 | def cook_layout ( layout , ajax ) : layout = re . sub ( '\r' , '\n' , re . sub ( '\r\n' , '\n' , layout ) ) if isinstance ( layout , six . text_type ) : result = getHTMLSerializer ( [ layout . encode ( 'utf-8' ) ] , encoding = 'utf-8' ) else : result = getHTMLSerializer ( [ layout ] , encoding = 'utf-8' ) if '<![CDATA[... | Return main_template compatible layout |
56,363 | def existing ( self ) : catalog = api . portal . get_tool ( 'portal_catalog' ) results = [ ] layout_path = self . _get_layout_path ( self . request . form . get ( 'layout' , '' ) ) for brain in catalog ( layout = layout_path ) : results . append ( { 'title' : brain . Title , 'url' : brain . getURL ( ) } ) return json .... | find existing content assigned to this layout |
56,364 | def load_reader_options ( ) : options = os . environ [ 'PANDOC_READER_OPTIONS' ] options = json . loads ( options , object_pairs_hook = OrderedDict ) return options | Retrieve Pandoc Reader options from the environment |
56,365 | def yaml_filter ( element , doc , tag = None , function = None , tags = None , strict_yaml = False ) : assert ( tag is None ) + ( tags is None ) == 1 if tags is None : tags = { tag : function } if type ( element ) == CodeBlock : for tag in tags : if tag in element . classes : function = tags [ tag ] if not strict_yaml ... | Convenience function for parsing code blocks with YAML options |
56,366 | def _set_content ( self , value , oktypes ) : if value is None : value = [ ] self . _content = ListContainer ( * value , oktypes = oktypes , parent = self ) | Similar to content . setter but when there are no existing oktypes |
56,367 | def offset ( self , n ) : idx = self . index if idx is not None : sibling = idx + n container = self . container if 0 <= sibling < len ( container ) : return container [ sibling ] | Return a sibling element offset by n |
56,368 | def search ( self , term : str , case_sensitive : bool = False ) -> 'PrettyDir' : if case_sensitive : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if term in pattr . name ] ) else : term = term . lower ( ) return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if term in pattr . name .... | Searches for names that match some pattern . |
56,369 | def properties ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if category_match ( pattr . category , AttrCategory . PROPERTY ) ] , ) | Returns all properties of the inspected object . |
56,370 | def methods ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if category_match ( pattr . category , AttrCategory . FUNCTION ) ] , ) | Returns all methods of the inspected object . |
56,371 | def public ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if not pattr . name . startswith ( '_' ) ] ) | Returns public attributes of the inspected object . |
56,372 | def own ( self ) -> 'PrettyDir' : return PrettyDir ( self . obj , [ pattr for pattr in self . pattrs if pattr . name in type ( self . obj ) . __dict__ or pattr . name in self . obj . __dict__ ] , ) | Returns attributes that are not inhterited from parent classes . |
56,373 | def get_oneline_doc ( self ) -> str : attr = self . attr_obj if self . display_group == AttrCategory . DESCRIPTOR : if isinstance ( attr , property ) : doc_list = [ '@property with getter' ] if attr . fset : doc_list . append ( SETTER ) if attr . fdel : doc_list . append ( DELETER ) else : doc_list = [ 'class %s' % att... | Doc doesn t necessarily mean doctring . It could be anything that should be put after the attr s name as an explanation . |
56,374 | def format_pattrs ( pattrs : List [ 'api.PrettyAttribute' ] ) -> str : output = [ ] pattrs . sort ( key = lambda x : ( _FORMATTER [ x . display_group ] . display_index , x . display_group , x . name , ) ) for display_group , grouped_pattrs in groupby ( pattrs , lambda x : x . display_group ) : output . append ( _FORMAT... | Generates repr string given a list of pattrs . |
56,375 | def get_attr_from_dict ( inspected_obj : Any , attr_name : str ) -> Any : if inspect . isclass ( inspected_obj ) : obj_list = [ inspected_obj ] + list ( inspected_obj . __mro__ ) else : obj_list = [ inspected_obj ] + list ( inspected_obj . __class__ . __mro__ ) for obj in obj_list : if hasattr ( obj , '__dict__' ) and ... | Ensures we get descriptor object instead of its return value . |
56,376 | def attr_category_postprocess ( get_attr_category_func ) : @ functools . wraps ( get_attr_category_func ) def wrapped ( name : str , attr : Any , obj : Any ) -> Tuple [ AttrCategory , ... ] : category = get_attr_category_func ( name , attr , obj ) category = list ( category ) if isinstance ( category , tuple ) else [ c... | Unifies attr_category to a tuple add AttrCategory . SLOT if needed . |
56,377 | def get_peak_mem ( ) : import resource rusage_denom = 1024. if sys . platform == 'darwin' : rusage_denom = rusage_denom * rusage_denom mem = resource . getrusage ( resource . RUSAGE_SELF ) . ru_maxrss / rusage_denom return mem | this returns peak memory use since process starts till the moment its called |
56,378 | def dfs_do_func_on_graph ( node , func , * args , ** kwargs ) : for _node in node . tree_iterator ( ) : func ( _node , * args , ** kwargs ) | invoke func on each node of the dr graph |
56,379 | def sparse_is_desireable ( lhs , rhs ) : return False if len ( lhs . shape ) == 1 : return False else : lhs_rows , lhs_cols = lhs . shape if len ( rhs . shape ) == 1 : rhs_rows = 1 rhs_cols = rhs . size else : rhs_rows , rhs_cols = rhs . shape result_size = lhs_rows * rhs_cols if sp . issparse ( lhs ) and sp . issparse... | Examines a pair of matrices and determines if the result of their multiplication should be sparse or not . |
56,380 | def convert_inputs_to_sparse_if_necessary ( lhs , rhs ) : if not sp . issparse ( lhs ) or not sp . issparse ( rhs ) : if sparse_is_desireable ( lhs , rhs ) : if not sp . issparse ( lhs ) : lhs = sp . csc_matrix ( lhs ) if not sp . issparse ( rhs ) : rhs = sp . csc_matrix ( rhs ) return lhs , rhs | This function checks to see if a sparse output is desireable given the inputs and if so casts the inputs to sparse in order to make it so . |
56,381 | def dr_wrt ( self , wrt , profiler = None ) : if wrt is self . x : jacs = [ ] for fvi , freevar in enumerate ( self . free_variables ) : tm = timer ( ) if isinstance ( freevar , ch . Select ) : new_jac = self . obj . dr_wrt ( freevar . a , profiler = profiler ) try : new_jac = new_jac [ : , freevar . idxs ] except : ne... | Loop over free variables and delete cache for the whole tree after finished each one |
56,382 | def J ( self ) : result = self . dr_wrt ( self . x , profiler = self . profiler ) . copy ( ) if self . profiler : self . profiler . harvest ( ) return np . atleast_2d ( result ) if not sp . issparse ( result ) else result | Compute Jacobian . Analyze dr graph first to disable unnecessary caching |
56,383 | def sid ( self ) : pnames = list ( self . terms ) + list ( self . dterms ) pnames . sort ( ) return ( self . __class__ , tuple ( [ ( k , id ( self . __dict__ [ k ] ) ) for k in pnames if k in self . __dict__ ] ) ) | Semantic id . |
56,384 | def compute_dr_wrt ( self , wrt ) : if wrt is self : return sp . eye ( self . x . size , self . x . size ) return None | Default method for objects that just contain a number or ndarray |
56,385 | def get_ubuntu_release_from_sentry ( self , sentry_unit ) : msg = None cmd = 'lsb_release -cs' release , code = sentry_unit . run ( cmd ) if code == 0 : self . log . debug ( '{} lsb_release: {}' . format ( sentry_unit . info [ 'unit_name' ] , release ) ) else : msg = ( '{} `{}` returned {} ' '{}' . format ( sentry_unit... | Get Ubuntu release codename from sentry unit . |
56,386 | def validate_services ( self , commands ) : self . log . debug ( 'Checking status of system services...' ) self . log . warn ( 'DEPRECATION WARNING: use ' 'validate_services_by_name instead of validate_services ' 'due to init system differences.' ) for k , v in six . iteritems ( commands ) : for cmd in v : output , co... | Validate that lists of commands succeed on service units . Can be used to verify system services are running on the corresponding service units . |
56,387 | def validate_services_by_name ( self , sentry_services ) : self . log . debug ( 'Checking status of system services...' ) systemd_switch = self . ubuntu_releases . index ( 'vivid' ) for sentry_unit , services_list in six . iteritems ( sentry_services ) : release , ret = self . get_ubuntu_release_from_sentry ( sentry_un... | Validate system service status by service name automatically detecting init system based on Ubuntu release codename . |
56,388 | def _get_config ( self , unit , filename ) : file_contents = unit . file_contents ( filename ) config = configparser . ConfigParser ( allow_no_value = True ) config . readfp ( io . StringIO ( file_contents ) ) return config | Get a ConfigParser object for parsing a unit s config file . |
56,389 | def validate_config_data ( self , sentry_unit , config_file , section , expected ) : self . log . debug ( 'Validating config file data ({} in {} on {})' '...' . format ( section , config_file , sentry_unit . info [ 'unit_name' ] ) ) config = self . _get_config ( sentry_unit , config_file ) if section != 'DEFAULT' and n... | Validate config file data . |
56,390 | def _validate_dict_data ( self , expected , actual ) : self . log . debug ( 'actual: {}' . format ( repr ( actual ) ) ) self . log . debug ( 'expected: {}' . format ( repr ( expected ) ) ) for k , v in six . iteritems ( expected ) : if k in actual : if ( isinstance ( v , six . string_types ) or isinstance ( v , bool ) ... | Validate dictionary data . |
56,391 | def validate_relation_data ( self , sentry_unit , relation , expected ) : actual = sentry_unit . relation ( relation [ 0 ] , relation [ 1 ] ) return self . _validate_dict_data ( expected , actual ) | Validate actual relation data based on expected relation data . |
56,392 | def _validate_list_data ( self , expected , actual ) : for e in expected : if e not in actual : return "expected item {} not found in actual list" . format ( e ) return None | Compare expected list vs actual list data . |
56,393 | def service_restarted ( self , sentry_unit , service , filename , pgrep_full = None , sleep_time = 20 ) : self . log . warn ( 'DEPRECATION WARNING: use ' 'validate_service_config_changed instead of ' 'service_restarted due to known races.' ) time . sleep ( sleep_time ) if ( self . _get_proc_start_time ( sentry_unit , ... | Check if service was restarted . |
56,394 | def service_restarted_since ( self , sentry_unit , mtime , service , pgrep_full = None , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : unit_name = sentry_unit . info [ 'unit_name' ] self . log . debug ( 'Checking that %s service restarted since %s on ' '%s' % ( service , mtime , unit_name ) ) time . sl... | Check if service was been started after a given time . |
56,395 | def config_updated_since ( self , sentry_unit , filename , mtime , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : unit_name = sentry_unit . info [ 'unit_name' ] self . log . debug ( 'Checking that %s updated since %s on ' '%s' % ( filename , mtime , unit_name ) ) time . sleep ( sleep_time ) file_mtime =... | Check if file was modified after a given time . |
56,396 | def validate_service_config_changed ( self , sentry_unit , mtime , service , filename , pgrep_full = None , sleep_time = 20 , retry_count = 30 , retry_sleep_time = 10 ) : service_restart = self . service_restarted_since ( sentry_unit , mtime , service , pgrep_full = pgrep_full , sleep_time = sleep_time , retry_count = ... | Check service and file were updated after mtime |
56,397 | def file_to_url ( self , file_rel_path ) : _abs_path = os . path . abspath ( file_rel_path ) return urlparse . urlparse ( _abs_path , scheme = 'file' ) . geturl ( ) | Convert a relative file path to a file URL . |
56,398 | def check_commands_on_units ( self , commands , sentry_units ) : self . log . debug ( 'Checking exit codes for {} commands on {} ' 'sentry units...' . format ( len ( commands ) , len ( sentry_units ) ) ) for sentry_unit in sentry_units : for cmd in commands : output , code = sentry_unit . run ( cmd ) if code == 0 : sel... | Check that all commands in a list exit zero on all sentry units in a list . |
56,399 | def get_unit_process_ids ( self , unit_processes , expect_success = True , pgrep_full = False ) : pid_dict = { } for sentry_unit , process_list in six . iteritems ( unit_processes ) : pid_dict [ sentry_unit ] = { } for process in process_list : pids = self . get_process_id_list ( sentry_unit , process , expect_success ... | Construct a dict containing unit sentries process names and process IDs . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.