signature:
def load_all_variables ( self ) :
    """Loads all variables from CDF .
 Note this routine is called automatically
 upon instantiation ."""

implementation:
self . data = { }
# need to add r variable names
file_var_names = self . z_variable_info . keys ( )
# collect variable information for each
# organize it neatly for fortran call
dim_sizes = [ ]
rec_nums = [ ]
data_types = [ ]
names = [ ]
for i , name in enumerate ( file_var_names ) :
    dim_sizes . extend ( self . z_variable_info [ name ] [ 'dim_sizes' ] )
    rec_nums . append ( self . z_variable_info [ name ] [ 'rec_num' ] )
    data_types . append ( self . z_variable_info [ name ] [ 'data_type' ] )
    names . append ( name . ljust ( 256 ) )
dim_sizes = np . array ( dim_sizes )
rec_nums = np . array ( rec_nums )
data_types = np . array ( data_types )
# individually load all variables by each data type
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'real4' ] , fortran_cdf . get_multi_z_real4 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'float' ] , fortran_cdf . get_multi_z_real4 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'real8' ] , fortran_cdf . get_multi_z_real8 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'double' ] , fortran_cdf . get_multi_z_real8 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'int4' ] , fortran_cdf . get_multi_z_int4 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'uint4' ] , fortran_cdf . get_multi_z_int4 , data_offset = 2 ** 32 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'int2' ] , fortran_cdf . get_multi_z_int2 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'uint2' ] , fortran_cdf . get_multi_z_int2 , data_offset = 2 ** 16 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'int1' ] , fortran_cdf . get_multi_z_int1 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'uint1' ] , fortran_cdf . get_multi_z_int1 , data_offset = 2 ** 8 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'byte' ] , fortran_cdf . get_multi_z_int1 )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'epoch' ] , fortran_cdf . get_multi_z_real8 , epoch = True )
self . _call_multi_fortran_z ( names , data_types , rec_nums , 2 * dim_sizes , self . cdf_data_types [ 'epoch16' ] , fortran_cdf . get_multi_z_epoch16 , epoch16 = True )
self . _call_multi_fortran_z ( names , data_types , rec_nums , dim_sizes , self . cdf_data_types [ 'TT2000' ] , fortran_cdf . get_multi_z_tt2000 , epoch = True )
# mark data has been loaded
self . data_loaded = True


signature:
def _call_multi_fortran_z ( self , names , data_types , rec_nums , dim_sizes , input_type_code , func , epoch = False , data_offset = None , epoch16 = False ) :
    """Calls fortran functions to load CDF variable data
 Parameters
 names : list _ like
 list of variables names
 data _ types : list _ like
 list of all loaded data type codes as used by CDF
 rec _ nums : list _ like
 list of record numbers in CDF file . Provided by variable _ info
 dim _ sizes :
 list of dimensions as provided by variable _ info .
 input _ type _ code : int
 Specific type code to load
 func : function
 Fortran function via python interface that will be used for actual loading .
 epoch : bool
 Flag indicating type is epoch . Translates things to datetime standard .
 data _ offset :
 Offset value to be applied to data . Required for unsigned integers in CDF .
 epoch16 : bool
 Flag indicating type is epoch16 . Translates things to datetime standard ."""

implementation:
# isolate input type code variables from total supplied types
idx , = np . where ( data_types == input_type_code )
if len ( idx ) > 0 : # read all data of a given type at once
    max_rec = rec_nums [ idx ] . max ( )
    sub_names = np . array ( names ) [ idx ]
    sub_sizes = dim_sizes [ idx ]
    status , data = func ( self . fname , sub_names . tolist ( ) , sub_sizes , sub_sizes . sum ( ) , max_rec , len ( sub_names ) )
    if status == 0 : # account for quirks of CDF data storage for certain types
        if data_offset is not None :
            data = data . astype ( int )
            idx , idy , = np . where ( data < 0 )
            data [ idx , idy ] += data_offset
        if epoch : # account for difference in seconds between
        # CDF epoch and python ' s epoch , leap year in there
        # ( datetime ( 1971,1,2 ) -
        # datetime ( 1,1,1 ) ) . total _ seconds ( ) * 1000
            data -= 62167219200000
            data = data . astype ( '<M8[ms]' )
        if epoch16 :
            data [ 0 : : 2 , : ] -= 62167219200
            data = data [ 0 : : 2 , : ] * 1E9 + data [ 1 : : 2 , : ] / 1.E3
            data = data . astype ( 'datetime64[ns]' )
            sub_sizes /= 2
        # all data of a type has been loaded and tweaked as necessary
        # parse through returned array to break out the individual variables
        # as appropriate
        self . _process_return_multi_z ( data , sub_names , sub_sizes )
    else :
        raise IOError ( fortran_cdf . statusreporter ( status ) )


signature:
def _process_return_multi_z ( self , data , names , dim_sizes ) :
    """process and attach data from fortran _ cdf . get _ multi _ *"""

implementation:
# process data
d1 = 0
d2 = 0
for name , dim_size in zip ( names , dim_sizes ) :
    d2 = d1 + dim_size
    if dim_size == 1 :
        self . data [ name . rstrip ( ) ] = data [ d1 , : ]
    else :
        self . data [ name . rstrip ( ) ] = data [ d1 : d2 , : ]
    d1 += dim_size


signature:
def _read_all_attribute_info ( self ) :
    """Read all attribute properties , g , r , and z attributes"""

implementation:
num = copy . deepcopy ( self . _num_attrs )
fname = copy . deepcopy ( self . fname )
out = fortran_cdf . inquire_all_attr ( fname , num , len ( fname ) )
status = out [ 0 ]
names = out [ 1 ] . astype ( 'U' )
scopes = out [ 2 ]
max_gentries = out [ 3 ]
max_rentries = out [ 4 ]
max_zentries = out [ 5 ]
attr_nums = out [ 6 ]
global_attrs_info = { }
var_attrs_info = { }
if status == 0 :
    for name , scope , gentry , rentry , zentry , num in zip ( names , scopes , max_gentries , max_rentries , max_zentries , attr_nums ) :
        name = '' . join ( name )
        name = name . rstrip ( )
        nug = { }
        nug [ 'scope' ] = scope
        nug [ 'max_gentry' ] = gentry
        nug [ 'max_rentry' ] = rentry
        nug [ 'max_zentry' ] = zentry
        nug [ 'attr_num' ] = num
        flag = ( gentry == 0 ) & ( rentry == 0 ) & ( zentry == 0 )
        if not flag :
            if scope == 1 :
                global_attrs_info [ name ] = nug
            elif scope == 2 :
                var_attrs_info [ name ] = nug
    self . global_attrs_info = global_attrs_info
    self . var_attrs_info = var_attrs_info
else :
    raise IOError ( fortran_cdf . statusreporter ( status ) )


signature:
def _read_all_z_attribute_data ( self ) :
    """Read all CDF z - attribute data"""

implementation:
self . meta = { }
# collect attribute info needed to get more info from
# fortran routines
max_entries = [ ]
attr_nums = [ ]
names = [ ]
attr_names = [ ]
names = self . var_attrs_info . keys ( )
num_z_attrs = len ( names )
exp_attr_nums = [ ]
for key in names :
    max_entries . append ( self . var_attrs_info [ key ] [ 'max_zentry' ] )
    attr_nums . append ( self . var_attrs_info [ key ] [ 'attr_num' ] )
attr_nums = np . array ( attr_nums )
max_entries = np . array ( max_entries )
info = fortran_cdf . z_attr_all_inquire ( self . fname , attr_nums , num_z_attrs , max_entries , self . _num_z_vars , len ( self . fname ) )
status = info [ 0 ]
data_types = info [ 1 ]
num_elems = info [ 2 ]
entry_nums = info [ 3 ]
if status == 0 :
    for i , name in enumerate ( names ) :
        self . var_attrs_info [ name ] [ 'data_type' ] = data_types [ i ]
        self . var_attrs_info [ name ] [ 'num_elems' ] = num_elems [ i ]
        self . var_attrs_info [ name ] [ 'entry_num' ] = entry_nums [ i ]
        exp_attr_nums . extend ( [ self . var_attrs_info [ name ] [ 'attr_num' ] ] * len ( entry_nums [ i ] ) )
        attr_names . extend ( [ name ] * len ( entry_nums [ i ] ) )
else :
    raise IOError ( fortran_cdf . statusreporter ( status ) )
# all the info is now packed up
# need to break it out to make it easier to load via fortran
# all of this junk
# attribute id , entry id ( zVariable ID ) , data _ type , num _ elems
# should just need to flatten this stuff
data_types = data_types . flatten ( )
num_elems = num_elems . flatten ( )
entry_nums = entry_nums . flatten ( )
attr_nums = np . array ( exp_attr_nums )
# drop everything that isn ' t valid
idx , = np . where ( entry_nums > 0 )
data_types = data_types [ idx ]
num_elems = num_elems [ idx ]
entry_nums = entry_nums [ idx ]
attr_nums = attr_nums [ idx ]
attr_names = np . array ( attr_names ) [ idx ]
# grad corresponding variable name for each attribute
var_names = [ self . z_variable_names_by_num [ i ] . rstrip ( ) for i in entry_nums ]
# the names that go along with this are already set up
# in attr _ names
# chunk by data type , grab largest num _ elems
# get data back , shorten to num _ elems , add to structure
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'real4' ] , fortran_cdf . get_multi_z_attr_real4 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'float' ] , fortran_cdf . get_multi_z_attr_real4 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'real8' ] , fortran_cdf . get_multi_z_attr_real8 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'double' ] , fortran_cdf . get_multi_z_attr_real8 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'byte' ] , fortran_cdf . get_multi_z_attr_int1 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'int1' ] , fortran_cdf . get_multi_z_attr_int1 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'uint1' ] , fortran_cdf . get_multi_z_attr_int1 , data_offset = 256 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'int2' ] , fortran_cdf . get_multi_z_attr_int2 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'uint2' ] , fortran_cdf . get_multi_z_attr_int2 , data_offset = 65536 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'int4' ] , fortran_cdf . get_multi_z_attr_int4 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'uint4' ] , fortran_cdf . get_multi_z_attr_int4 , data_offset = 2 ** 32 )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'char' ] , fortran_cdf . get_multi_z_attr_char )
self . _call_multi_fortran_z_attr ( attr_names , data_types , num_elems , entry_nums , attr_nums , var_names , self . cdf_data_types [ 'uchar' ] , fortran_cdf . get_multi_z_attr_char )


signature:
def _call_multi_fortran_z_attr ( self , names , data_types , num_elems , entry_nums , attr_nums , var_names , input_type_code , func , data_offset = None ) :
    """Calls Fortran function that reads attribute data .
 data _ offset translates unsigned into signed .
 If number read in is negative , offset added ."""

implementation:
# isolate input type code variables
idx , = np . where ( data_types == input_type_code )
if len ( idx ) > 0 : # maximimum array dimension
    max_num = num_elems [ idx ] . max ( )
    sub_num_elems = num_elems [ idx ]
    sub_names = np . array ( names ) [ idx ]
    sub_var_names = np . array ( var_names ) [ idx ]
    # zVariable numbers , ' entry ' number
    sub_entry_nums = entry_nums [ idx ]
    # attribute number
    sub_attr_nums = attr_nums [ idx ]
    status , data = func ( self . fname , sub_attr_nums , sub_entry_nums , len ( sub_attr_nums ) , max_num , len ( self . fname ) )
    if ( status == 0 ) . all ( ) :
        if data_offset is not None :
            data = data . astype ( int )
            idx , idy , = np . where ( data < 0 )
            data [ idx , idy ] += data_offset
        self . _process_return_multi_z_attr ( data , sub_names , sub_var_names , sub_num_elems )
    else : # raise ValueError ( ' CDF Error code : ' , status )
        idx , = np . where ( status != 0 )
        # raise first error
        raise IOError ( fortran_cdf . statusreporter ( status [ idx ] [ 0 ] ) )


signature:
def _process_return_multi_z_attr ( self , data , attr_names , var_names , sub_num_elems ) :
    '''process and attach data from fortran _ cdf . get _ multi _ *'''

implementation:
# process data
for i , ( attr_name , var_name , num_e ) in enumerate ( zip ( attr_names , var_names , sub_num_elems ) ) :
    if var_name not in self . meta . keys ( ) :
        self . meta [ var_name ] = { }
    if num_e == 1 :
        self . meta [ var_name ] [ attr_name ] = data [ i , 0 ]
    else :
        if data [ i ] . dtype == '|S1' :
            self . meta [ var_name ] [ attr_name ] = '' . join ( data [ i , 0 : num_e ] . astype ( 'U' ) ) . rstrip ( )
        else :
            self . meta [ var_name ] [ attr_name ] = data [ i , 0 : num_e ]


signature:
def to_pysat ( self , flatten_twod = True , units_label = 'UNITS' , name_label = 'long_name' , fill_label = 'FILLVAL' , plot_label = 'FieldNam' , min_label = 'ValidMin' , max_label = 'ValidMax' , notes_label = 'Var_Notes' , desc_label = 'CatDesc' , axis_label = 'LablAxis' ) :
    """Exports loaded CDF data into data , meta for pysat module
 Notes
 The * _ labels should be set to the values in the file , if present .
 Note that once the meta object returned from this function is attached
 to a pysat . Instrument object then the * _ labels on the Instrument
 are assigned to the newly attached Meta object .
 The pysat Meta object will use data with labels that match the patterns
 in * _ labels even if the case does not match .
 Parameters
 flatten _ twod : bool ( True )
 If True , then two dimensional data is flattened across
 columns . Name mangling is used to group data , first column
 is ' name ' , last column is ' name _ end ' . In between numbers are
 appended ' name _ 1 ' , ' name _ 2 ' , etc . All data for a given 2D array
 may be accessed via , data . ix [ : , ' item ' : ' item _ end ' ]
 If False , then 2D data is stored as a series of DataFrames ,
 indexed by Epoch . data . ix [ 0 , ' item ' ]
 units _ label : str
 Identifier within metadata for units . Defults to CDAWab standard .
 name _ label : str
 Identifier within metadata for variable name . Defults to ' long _ name ' ,
 not normally present within CDAWeb files . If not , will use values
 from the variable name in the file .
 fill _ label : str
 Identifier within metadata for Fill Values . Defults to CDAWab standard .
 plot _ label : str
 Identifier within metadata for variable name used when plotting .
 Defults to CDAWab standard .
 min _ label : str
 Identifier within metadata for minimim variable value .
 Defults to CDAWab standard .
 max _ label : str
 Identifier within metadata for maximum variable value .
 Defults to CDAWab standard .
 notes _ label : str
 Identifier within metadata for notes . Defults to CDAWab standard .
 desc _ label : str
 Identifier within metadata for a variable description .
 Defults to CDAWab standard .
 axis _ label : str
 Identifier within metadata for axis name used when plotting .
 Defults to CDAWab standard .
 Returns
 pandas . DataFrame , pysat . Meta
 Data and Metadata suitable for attachment to a pysat . Instrument
 object ."""

implementation:
import string
import pysat
import pandas
# copy data
cdata = self . data . copy ( )
# create pysat . Meta object using data above
# and utilizing the attribute labels provided by the user
meta = pysat . Meta ( pysat . DataFrame . from_dict ( self . meta , orient = 'index' ) , units_label = units_label , name_label = name_label , fill_label = fill_label , plot_label = plot_label , min_label = min_label , max_label = max_label , notes_label = notes_label , desc_label = desc_label , axis_label = axis_label )
# account for different possible cases for Epoch , epoch , EPOCH , epOch
lower_names = [ name . lower ( ) for name in meta . keys ( ) ]
for name , true_name in zip ( lower_names , meta . keys ( ) ) :
    if name == 'epoch' :
        meta . data . rename ( index = { true_name : 'Epoch' } , inplace = True )
        epoch = cdata . pop ( true_name )
        cdata [ 'Epoch' ] = epoch
# ready to format data , iterate over all of the data names
# and put into a pandas DataFrame
two_d_data = [ ]
drop_list = [ ]
for name in cdata . keys ( ) :
    temp = np . shape ( cdata [ name ] )
    # treat 2 dimensional data differently
    if len ( temp ) == 2 :
        if not flatten_twod : # put 2D data into a Frame at each time
        # remove data from dict when adding to the DataFrame
            frame = pysat . DataFrame ( cdata [ name ] . flatten ( ) , columns = [ name ] )
            drop_list . append ( name )
            step = temp [ 0 ]
            new_list = [ ]
            new_index = np . arange ( step )
            for i in np . arange ( len ( epoch ) ) :
                new_list . append ( frame . iloc [ i * step : ( i + 1 ) * step , : ] )
                new_list [ - 1 ] . index = new_index
            # new _ frame = pandas . DataFrame . from _ records ( new _ list , index = epoch , columns = [ name ] )
            new_frame = pandas . Series ( new_list , index = epoch , name = name )
            two_d_data . append ( new_frame )
        else : # flatten 2D into series of 1D columns
            new_names = [ name + '_{i}' . format ( i = i ) for i in np . arange ( temp [ 0 ] - 2 ) ]
            new_names . append ( name + '_end' )
            new_names . insert ( 0 , name )
            # remove data from dict when adding to the DataFrame
            drop_list . append ( name )
            frame = pysat . DataFrame ( cdata [ name ] . T , index = epoch , columns = new_names )
            two_d_data . append ( frame )
for name in drop_list :
    _ = cdata . pop ( name )
# all of the data left over is 1D , add as Series
data = pysat . DataFrame ( cdata , index = epoch )
two_d_data . append ( data )
data = pandas . concat ( two_d_data , axis = 1 )
data . drop ( 'Epoch' , axis = 1 , inplace = True )
return data , meta


signature:
def _uptime_linux ( ) :
    """Returns uptime in seconds or None , on Linux ."""

implementation:
# With procfs
try :
    f = open ( '/proc/uptime' , 'r' )
    up = float ( f . readline ( ) . split ( ) [ 0 ] )
    f . close ( )
    return up
except ( IOError , ValueError ) :
    pass
# Without procfs ( really ? )
try :
    libc = ctypes . CDLL ( 'libc.so' )
except AttributeError :
    return None
except OSError : # Debian and derivatives do the wrong thing because / usr / lib / libc . so
# is a GNU ld script rather than an ELF object . To get around this , we
# have to be more specific .
# We don ' t want to use ctypes . util . find _ library because that creates a
# new process on Linux . We also don ' t want to try too hard because at
# this point we ' re already pretty sure this isn ' t Linux .
    try :
        libc = ctypes . CDLL ( 'libc.so.6' )
    except OSError :
        return None
if not hasattr ( libc , 'sysinfo' ) : # Not Linux .
    return None
buf = ctypes . create_string_buffer ( 128 )
# 64 suffices on 32 - bit , whatever .
if libc . sysinfo ( buf ) < 0 :
    return None
up = struct . unpack_from ( '@l' , buf . raw ) [ 0 ]
if up < 0 :
    up = None
return up


signature:
def _boottime_linux ( ) :
    """A way to figure out the boot time directly on Linux ."""

implementation:
global __boottime
try :
    f = open ( '/proc/stat' , 'r' )
    for line in f :
        if line . startswith ( 'btime' ) :
            __boottime = int ( line . split ( ) [ 1 ] )
    if datetime is None :
        raise NotImplementedError ( 'datetime module required.' )
    return datetime . fromtimestamp ( __boottime )
except ( IOError , IndexError ) :
    return None


signature:
def _uptime_amiga ( ) :
    """Returns uptime in seconds or None , on AmigaOS ."""

implementation:
global __boottime
try :
    __boottime = os . stat ( 'RAM:' ) . st_ctime
    return time . time ( ) - __boottime
except ( NameError , OSError ) :
    return None


signature:
def _uptime_beos ( ) :
    """Returns uptime in seconds on None , on BeOS / Haiku ."""

implementation:
try :
    libroot = ctypes . CDLL ( 'libroot.so' )
except ( AttributeError , OSError ) :
    return None
if not hasattr ( libroot , 'system_time' ) :
    return None
libroot . system_time . restype = ctypes . c_int64
return libroot . system_time ( ) / 1000000.


signature:
def _uptime_bsd ( ) :
    """Returns uptime in seconds or None , on BSD ( including OS X ) ."""

implementation:
global __boottime
try :
    libc = ctypes . CDLL ( 'libc.so' )
except AttributeError :
    return None
except OSError : # OS X ; can ' t use ctypes . util . find _ library because that creates
# a new process on Linux , which is undesirable .
    try :
        libc = ctypes . CDLL ( 'libc.dylib' )
    except OSError :
        return None
if not hasattr ( libc , 'sysctlbyname' ) : # Not BSD .
    return None
# Determine how much space we need for the response .
sz = ctypes . c_uint ( 0 )
libc . sysctlbyname ( 'kern.boottime' , None , ctypes . byref ( sz ) , None , 0 )
if sz . value != struct . calcsize ( '@LL' ) : # Unexpected , let ' s give up .
    return None
# For real now .
buf = ctypes . create_string_buffer ( sz . value )
libc . sysctlbyname ( 'kern.boottime' , buf , ctypes . byref ( sz ) , None , 0 )
sec , usec = struct . unpack ( '@LL' , buf . raw )
# OS X disagrees what that second value is .
if usec > 1000000 :
    usec = 0.
__boottime = sec + usec / 1000000.
up = time . time ( ) - __boottime
if up < 0 :
    up = None
return up


signature:
def _uptime_minix ( ) :
    """Returns uptime in seconds or None , on MINIX ."""

implementation:
try :
    f = open ( '/proc/uptime' , 'r' )
    up = float ( f . read ( ) )
    f . close ( )
    return up
except ( IOError , ValueError ) :
    return None


signature:
def _uptime_plan9 ( ) :
    """Returns uptime in seconds or None , on Plan 9."""

implementation:
# Apparently Plan 9 only has Python 2.2 , which I ' m not prepared to
# support . Maybe some Linuxes implement / dev / time , though , someone was
# talking about it somewhere .
try : # The time file holds one 32 - bit number representing the sec -
# onds since start of epoch and three 64 - bit numbers , repre -
# senting nanoseconds since start of epoch , clock ticks , and
# clock frequency .
# - - cons ( 3)
    f = open ( '/dev/time' , 'r' )
    s , ns , ct , cf = f . read ( ) . split ( )
    f . close ( )
    return float ( ct ) / float ( cf )
except ( IOError , ValueError ) :
    return None


signature:
def _uptime_solaris ( ) :
    """Returns uptime in seconds or None , on Solaris ."""

implementation:
global __boottime
try :
    kstat = ctypes . CDLL ( 'libkstat.so' )
except ( AttributeError , OSError ) :
    return None
# kstat doesn ' t have uptime , but it does have boot time .
# Unfortunately , getting at it isn ' t perfectly straightforward .
# First , let ' s pretend to be kstat . h
# Constant
KSTAT_STRLEN = 31
# According to every kstat . h I could find .
# Data structures
class anon_union ( ctypes . Union ) : # The ` ` value ' ' union in kstat _ named _ t actually has a bunch more
# members , but we ' re only using it for boot _ time , so we only need
# the padding and the one we ' re actually using .
    _fields_ = [ ( 'c' , ctypes . c_char * 16 ) , ( 'time' , ctypes . c_int ) ]
class kstat_named_t ( ctypes . Structure ) :
    _fields_ = [ ( 'name' , ctypes . c_char * KSTAT_STRLEN ) , ( 'data_type' , ctypes . c_char ) , ( 'value' , anon_union ) ]
# Function signatures
kstat . kstat_open . restype = ctypes . c_void_p
kstat . kstat_lookup . restype = ctypes . c_void_p
kstat . kstat_lookup . argtypes = [ ctypes . c_void_p , ctypes . c_char_p , ctypes . c_int , ctypes . c_char_p ]
kstat . kstat_read . restype = ctypes . c_int
kstat . kstat_read . argtypes = [ ctypes . c_void_p , ctypes . c_void_p , ctypes . c_void_p ]
kstat . kstat_data_lookup . restype = ctypes . POINTER ( kstat_named_t )
kstat . kstat_data_lookup . argtypes = [ ctypes . c_void_p , ctypes . c_char_p ]
# Now , let ' s do something useful .
# Initialise kstat control structure .
kc = kstat . kstat_open ( )
if not kc :
    return None
# We ' re looking for unix : 0 : system _ misc : boot _ time .
ksp = kstat . kstat_lookup ( kc , 'unix' , 0 , 'system_misc' )
if ksp and kstat . kstat_read ( kc , ksp , None ) != - 1 :
    data = kstat . kstat_data_lookup ( ksp , 'boot_time' )
    if data :
        __boottime = data . contents . value . time
# Clean - up .
kstat . kstat_close ( kc )
if __boottime is not None :
    return time . time ( ) - __boottime
return None


signature:
def _uptime_syllable ( ) :
    """Returns uptime in seconds or None , on Syllable ."""

implementation:
global __boottime
try :
    __boottime = os . stat ( '/dev/pty/mst/pty0' ) . st_mtime
    return time . time ( ) - __boottime
except ( NameError , OSError ) :
    return None


signature:
def _uptime_windows ( ) :
    """Returns uptime in seconds or None , on Windows . Warning : may return
 incorrect answers after 49.7 days on versions older than Vista ."""

implementation:
if hasattr ( ctypes , 'windll' ) and hasattr ( ctypes . windll , 'kernel32' ) :
    lib = ctypes . windll . kernel32
else :
    try : # Windows CE uses the cdecl calling convention .
        lib = ctypes . CDLL ( 'coredll.lib' )
    except ( AttributeError , OSError ) :
        return None
if hasattr ( lib , 'GetTickCount64' ) : # Vista / Server 2008 or later .
    lib . GetTickCount64 . restype = ctypes . c_uint64
    return lib . GetTickCount64 ( ) / 1000.
if hasattr ( lib , 'GetTickCount' ) : # WinCE and Win2k or later ; gives wrong answers after 49.7 days .
    lib . GetTickCount . restype = ctypes . c_uint32
    return lib . GetTickCount ( ) / 1000.
return None


signature:
def uptime ( ) :
    """Returns uptime in seconds if even remotely possible , or None if not ."""

implementation:
if __boottime is not None :
    return time . time ( ) - __boottime
return { 'amiga' : _uptime_amiga , 'aros12' : _uptime_amiga , 'beos5' : _uptime_beos , 'cygwin' : _uptime_linux , 'darwin' : _uptime_osx , 'haiku1' : _uptime_beos , 'linux' : _uptime_linux , 'linux-armv71' : _uptime_linux , 'linux2' : _uptime_linux , 'mac' : _uptime_mac , 'minix3' : _uptime_minix , 'riscos' : _uptime_riscos , 'sunos5' : _uptime_solaris , 'syllable' : _uptime_syllable , 'win32' : _uptime_windows , 'wince' : _uptime_windows } . get ( sys . platform , _uptime_bsd ) ( ) or _uptime_bsd ( ) or _uptime_plan9 ( ) or _uptime_linux ( ) or _uptime_windows ( ) or _uptime_solaris ( ) or _uptime_beos ( ) or _uptime_amiga ( ) or _uptime_riscos ( ) or _uptime_posix ( ) or _uptime_syllable ( ) or _uptime_mac ( ) or _uptime_osx ( )


signature:
def boottime ( ) :
    """Returns boot time if remotely possible , or None if not ."""

implementation:
global __boottime
if __boottime is None :
    up = uptime ( )
    if up is None :
        return None
if __boottime is None :
    _boottime_linux ( )
if datetime is None :
    raise RuntimeError ( 'datetime module required.' )
return datetime . fromtimestamp ( __boottime or time . time ( ) - up )


signature:
def _initfile ( path , data = "dict" ) :
    """Initialize an empty JSON file ."""

implementation:
data = { } if data . lower ( ) == "dict" else [ ]
# The file will need to be created if it doesn ' t exist
if not os . path . exists ( path ) : # The file doesn ' t exist
# Raise exception if the directory that should contain the file doesn ' t
# exist
    dirname = os . path . dirname ( path )
    if dirname and not os . path . exists ( dirname ) :
        raise IOError ( ( "Could not initialize empty JSON file in non-existant " "directory '{}'" ) . format ( os . path . dirname ( path ) ) )
    # Write an empty file there
    with open ( path , "w" ) as f :
        json . dump ( data , f )
    return True
elif os . path . getsize ( path ) == 0 : # The file is empty
    with open ( path , "w" ) as f :
        json . dump ( data , f )
else : # The file exists and contains content
    return False


signature:
def _data ( self ) :
    """A simpler version of data to avoid infinite recursion in some cases .
 Don ' t use this ."""

implementation:
if self . is_caching :
    return self . cache
with open ( self . path , "r" ) as f :
    return json . load ( f )


signature:
def data ( self , data ) :
    """Overwrite the file with new data . You probably shouldn ' t do
 this yourself , it ' s easy to screw up your whole file with this ."""

implementation:
if self . is_caching :
    self . cache = data
else :
    fcontents = self . file_contents
    with open ( self . path , "w" ) as f :
        try : # Write the file . Keep user settings about indentation , etc
            indent = self . indent if self . pretty else None
            json . dump ( data , f , sort_keys = self . sort_keys , indent = indent )
        except Exception as e : # Rollback to prevent data loss
            f . seek ( 0 )
            f . truncate ( )
            f . write ( fcontents )
            # And re - raise the exception
            raise e
self . _updateType ( )


signature:
def _updateType ( self ) :
    """Make sure that the class behaves like the data structure that it
 is , so that we don ' t get a ListFile trying to represent a dict ."""

implementation:
data = self . _data ( )
# Change type if needed
if isinstance ( data , dict ) and isinstance ( self , ListFile ) :
    self . __class__ = DictFile
elif isinstance ( data , list ) and isinstance ( self , DictFile ) :
    self . __class__ = ListFile


signature:
def with_data ( path , data ) :
    """Initialize a new file that starts out with some data . Pass data
 as a list , dict , or JSON string ."""

implementation:
# De - jsonize data if necessary
if isinstance ( data , str ) :
    data = json . loads ( data )
# Make sure this is really a new file
if os . path . exists ( path ) :
    raise ValueError ( "File exists, not overwriting data. Set the " "'data' attribute on a normally-initialized " "'livejson.File' instance if you really " "want to do this." )
else :
    f = File ( path )
    f . data = data
    return f


signature:
def is_configured ( self , project , ** kwargs ) :
    """Check if plugin is configured ."""

implementation:
params = self . get_option
return bool ( params ( 'server_host' , project ) and params ( 'server_port' , project ) )


signature:
def post_process ( self , group , event , is_new , is_sample , ** kwargs ) :
    """Process error ."""

implementation:
if not self . is_configured ( group . project ) :
    return
host = self . get_option ( 'server_host' , group . project )
port = int ( self . get_option ( 'server_port' , group . project ) )
prefix = self . get_option ( 'prefix' , group . project )
hostname = self . get_option ( 'hostname' , group . project ) or socket . gethostname ( )
resolve_age = group . project . get_option ( 'sentry:resolve_age' , None )
now = int ( time . time ( ) )
template = '%s.%%s[%s]' % ( prefix , group . project . slug )
level = group . get_level_display ( )
label = template % level
groups = group . project . group_set . filter ( status = STATUS_UNRESOLVED )
if resolve_age :
    oldest = timezone . now ( ) - timedelta ( hours = int ( resolve_age ) )
    groups = groups . filter ( last_seen__gt = oldest )
num_errors = groups . filter ( level = group . level ) . count ( )
metric = Metric ( hostname , label , num_errors , now )
log . info ( 'will send %s=%s to zabbix' , label , num_errors )
send_to_zabbix ( [ metric ] , host , port )


signature:
def as_dict ( self ) :
    """ping statistics .
 Returns :
 | dict | :
 Examples :
 > > > import pingparsing
 > > > parser = pingparsing . PingParsing ( )
 > > > parser . parse ( ping _ result )
 > > > parser . as _ dict ( )
 " destination " : " google . com " ,
 " packet _ transmit " : 60,
 " packet _ receive " : 60,
 " packet _ loss _ rate " : 0.0,
 " packet _ loss _ count " : 0,
 " rtt _ min " : 61.425,
 " rtt _ avg " : 99.731,
 " rtt _ max " : 212.597,
 " rtt _ mdev " : 27.566,
 " packet _ duplicate _ rate " : 0.0,
 " packet _ duplicate _ count " : 0"""

implementation: return { "destination" : self . destination , "packet_transmit" : self . packet_transmit , "packet_receive" : self . packet_receive , "packet_loss_count" : self . packet_loss_count , "packet_loss_rate" : self . packet_loss_rate , "rtt_min" : self . rtt_min , "rtt_avg" : self . rtt_avg , "rtt_max" : self . rtt_max , "rtt_mdev" : self . rtt_mdev , "packet_duplicate_count" : self . packet_duplicate_count , "packet_duplicate_rate" : self . packet_duplicate_rate , }


signature:
def as_tuple ( self ) :
    """ping statistics .
 Returns :
 | namedtuple | :
 Examples :
 > > > import pingparsing
 > > > parser = pingparsing . PingParsing ( )
 > > > parser . parse ( ping _ result )
 > > > parser . as _ tuple ( )
 PingResult ( destination = ' google . com ' , packet _ transmit = 60 , packet _ receive = 60 , packet _ loss _ rate = 0.0 , packet _ loss _ count = 0 , rtt _ min = 61.425 , rtt _ avg = 99.731 , rtt _ max = 212.597 , rtt _ mdev = 27.566 , packet _ duplicate _ rate = 0.0 , packet _ duplicate _ count = 0)"""

implementation:
from collections import namedtuple
ping_result = self . as_dict ( )
return namedtuple ( "PingStatsTuple" , ping_result . keys ( ) ) ( ** ping_result )


signature:
def ping ( self ) :
    """Sending ICMP packets .
 : return : ` ` ping ` ` command execution result .
 : rtype : : py : class : ` . PingResult `
 : raises ValueError : If parameters not valid ."""

implementation:
self . __validate_ping_param ( )
ping_proc = subprocrunner . SubprocessRunner ( self . __get_ping_command ( ) )
ping_proc . run ( )
return PingResult ( ping_proc . stdout , ping_proc . stderr , ping_proc . returncode )


signature:
def parse ( self , ping_message ) :
    """Parse ping command output .
 Args :
 ping _ message ( str or : py : class : ` ~ pingparsing . PingResult ` ) :
 ` ` ping ` ` command output .
 Returns :
 : py : class : ` ~ pingparsing . PingStats ` : Parsed result ."""

implementation:
try : # accept PingResult instance as an input
    if typepy . is_not_null_string ( ping_message . stdout ) :
        ping_message = ping_message . stdout
except AttributeError :
    pass
logger . debug ( "parsing ping result: {}" . format ( ping_message ) )
self . __parser = NullPingParser ( )
if typepy . is_null_string ( ping_message ) :
    logger . debug ( "ping_message is empty" )
    self . __stats = PingStats ( )
    return self . __stats
ping_lines = _to_unicode ( ping_message ) . splitlines ( )
parser_class_list = ( LinuxPingParser , WindowsPingParser , MacOsPingParser , AlpineLinuxPingParser , )
for parser_class in parser_class_list :
    self . __parser = parser_class ( )
    try :
        self . __stats = self . __parser . parse ( ping_lines )
        return self . __stats
    except ParseError as e :
        if e . reason != ParseErrorReason . HEADER_NOT_FOUND :
            raise e
    except pp . ParseException :
        pass
self . __parser = NullPingParser ( )
return self . __stats


signature:
def send_confirmation ( self ) :
    """Send a verification email for the email address ."""

implementation:
confirmation = EmailConfirmation . objects . create ( email = self )
confirmation . send ( )


signature:
def send_duplicate_notification ( self ) :
    """Send a notification about a duplicate signup ."""

implementation:
email_utils . send_email ( from_email = settings . DEFAULT_FROM_EMAIL , recipient_list = [ self . email ] , subject = _ ( "Registration Attempt" ) , template_name = "rest_email_auth/emails/duplicate-email" , )
logger . info ( "Sent duplicate email notification to: %s" , self . email )


signature:
def set_primary ( self ) :
    """Set this email address as the user ' s primary email ."""

implementation:
query = EmailAddress . objects . filter ( is_primary = True , user = self . user )
query = query . exclude ( pk = self . pk )
# The transaction is atomic so there is never a gap where a user
# has no primary email address .
with transaction . atomic ( ) :
    query . update ( is_primary = False )
    self . is_primary = True
    self . save ( )
logger . info ( "Set %s as the primary email address for %s." , self . email , self . user , )


signature:
def confirm ( self ) :
    """Mark the instance ' s email as verified ."""

implementation:
self . email . is_verified = True
self . email . save ( )
signals . email_verified . send ( email = self . email , sender = self . __class__ )
logger . info ( "Verified email address: %s" , self . email . email )


signature:
def is_expired ( self ) :
    """Determine if the confirmation has expired .
 Returns :
 bool :
 ` ` True ` ` if the confirmation has expired and ` ` False ` `
 otherwise ."""

implementation:
expiration_time = self . created_at + datetime . timedelta ( days = 1 )
return timezone . now ( ) > expiration_time


signature:
def send ( self ) :
    """Send a verification email to the user ."""

implementation:
context = { "verification_url" : app_settings . EMAIL_VERIFICATION_URL . format ( key = self . key ) }
email_utils . send_email ( context = context , from_email = settings . DEFAULT_FROM_EMAIL , recipient_list = [ self . email . email ] , subject = _ ( "Please Verify Your Email Address" ) , template_name = "rest_email_auth/emails/verify-email" , )
logger . info ( "Sent confirmation email to %s for user #%d" , self . email . email , self . email . user . id , )


signature:
def _create ( cls , model_class , * args , ** kwargs ) :
    """Create a new user instance .
 Args :
 model _ class :
 The type of model to create an instance of .
 args :
 Positional arguments to create the instance with .
 kwargs :
 Keyword arguments to create the instance with .
 Returns :
 A new user instance of the type specified by
 ` ` model _ class ` ` ."""

implementation:
manager = cls . _get_manager ( model_class )
return manager . create_user ( * args , ** kwargs )


signature:
def create ( self , validated_data ) :
    """Create a new email and send a confirmation to it .
 Returns :
 The newly creating ` ` EmailAddress ` ` instance ."""

implementation:
email_query = models . EmailAddress . objects . filter ( email = self . validated_data [ "email" ] )
if email_query . exists ( ) :
    email = email_query . get ( )
    email . send_duplicate_notification ( )
else :
    email = super ( EmailSerializer , self ) . create ( validated_data )
    email . send_confirmation ( )
    user = validated_data . get ( "user" )
    query = models . EmailAddress . objects . filter ( is_primary = True , user = user )
    if not query . exists ( ) :
        email . set_primary ( )
return email


signature:
def update ( self , instance , validated_data ) :
    """Update the instance the serializer is bound to .
 Args :
 instance :
 The instance the serializer is bound to .
 validated _ data :
 The data to update the serializer with .
 Returns :
 The updated instance ."""

implementation:
is_primary = validated_data . pop ( "is_primary" , False )
instance = super ( EmailSerializer , self ) . update ( instance , validated_data )
if is_primary :
    instance . set_primary ( )
return instance


signature:
def validate_email ( self , email ) :
    """Validate the provided email address .
 The email address is first modified to match the RFC spec .
 Namely , the domain portion of the email is lowercased .
 Returns :
 The validated email address .
 Raises :
 serializers . ValidationError :
 If the serializer is bound and the provided email
 doesn ' t match the existing address ."""

implementation:
user , domain = email . rsplit ( "@" , 1 )
email = "@" . join ( [ user , domain . lower ( ) ] )
if self . instance and email and self . instance . email != email :
    raise serializers . ValidationError ( _ ( "Existing emails may not be edited. Create a new one " "instead." ) )
return email


signature:
def validate_is_primary ( self , is_primary ) :
    """Validate the provided ' is _ primary ' parameter .
 Returns :
 The validated ' is _ primary ' value .
 Raises :
 serializers . ValidationError :
 If the user attempted to mark an unverified email as
 their primary email address ."""

implementation:
# TODO : Setting ' is _ primary ' to ' False ' should probably not be
# allowed .
if is_primary and not ( self . instance and self . instance . is_verified ) :
    raise serializers . ValidationError ( _ ( "Unverified email addresses may not be used as the " "primary address." ) )
return is_primary


signature:
def validate ( self , data ) :
    """Validate the provided data .
 Returns :
 dict :
 The validated data .
 Raises :
 serializers . ValidationError :
 If the provided password is invalid ."""

implementation:
user = self . _confirmation . email . user
if ( app_settings . EMAIL_VERIFICATION_PASSWORD_REQUIRED and not user . check_password ( data [ "password" ] ) ) :
    raise serializers . ValidationError ( _ ( "The provided password is invalid." ) )
# Add email to returned data
data [ "email" ] = self . _confirmation . email . email
return data


signature:
def validate_key ( self , key ) :
    """Validate the provided confirmation key .
 Returns :
 str :
 The validated confirmation key .
 Raises :
 serializers . ValidationError :
 If there is no email confirmation with the given key or
 the confirmation has expired ."""

implementation:
try :
    confirmation = models . EmailConfirmation . objects . select_related ( "email__user" ) . get ( key = key )
except models . EmailConfirmation . DoesNotExist :
    raise serializers . ValidationError ( _ ( "The provided verification key is invalid." ) )
if confirmation . is_expired :
    raise serializers . ValidationError ( _ ( "That verification code has expired." ) )
# Cache confirmation instance
self . _confirmation = confirmation
return key


signature:
def save ( self ) :
    """Send out a password reset if the provided data is valid .
 If the provided email address exists and is verified , a reset
 email is sent to the address .
 Returns :
 The password reset token if it was returned and ` ` None ` `
 otherwise ."""

implementation:
try :
    email = models . EmailAddress . objects . get ( email = self . validated_data [ "email" ] , is_verified = True )
except models . EmailAddress . DoesNotExist :
    return None
token = models . PasswordResetToken . objects . create ( email = email )
token . send ( )
return token


signature:
def save ( self ) :
    """Reset the user ' s password if the provided information is valid ."""

implementation:
token = models . PasswordResetToken . objects . get ( key = self . validated_data [ "key" ] )
token . email . user . set_password ( self . validated_data [ "password" ] )
token . email . user . save ( )
logger . info ( "Reset password for %s" , token . email . user )
token . delete ( )


signature:
def validate_key ( self , key ) :
    """Validate the provided reset key .
 Returns :
 The validated key .
 Raises :
 serializers . ValidationError :
 If the provided key does not exist ."""

implementation:
if not models . PasswordResetToken . valid_tokens . filter ( key = key ) . exists ( ) :
    raise serializers . ValidationError ( _ ( "The provided reset token does not exist, or is expired." ) )
return key


signature:
def create ( self , validated_data ) :
    """Create a new user from the data passed to the serializer .
 If the provided email has not been verified yet , the user is
 created and a verification email is sent to the address .
 Otherwise we send a notification to the email address that
 someone attempted to register with an email that ' s already been
 verified .
 Args :
 validated _ data ( dict ) :
 The data passed to the serializer after it has been
 validated .
 Returns :
 A new user created from the provided data ."""

implementation:
email = validated_data . pop ( "email" )
password = validated_data . pop ( "password" )
# We don ' t save the user instance yet in case the provided email
# address already exists .
user = get_user_model ( ) ( ** validated_data )
user . set_password ( password )
# We set an ephemeral email property so that it is included in
# the data returned by the serializer .
user . email = email
email_query = models . EmailAddress . objects . filter ( email = email )
if email_query . exists ( ) :
    existing_email = email_query . get ( )
    existing_email . send_duplicate_notification ( )
else :
    user . save ( )
    email_instance = models . EmailAddress . objects . create ( email = email , user = user )
    email_instance . send_confirmation ( )
    signals . user_registered . send ( sender = self . __class__ , user = user )
return user


signature:
def validate_email ( self , email ) :
    """Validate the provided email address .
 Args :
 email :
 The email address to validate .
 Returns :
 The provided email address , transformed to match the RFC
 spec . Namely , the domain portion of the email must be
 lowercase ."""

implementation:
user , domain = email . rsplit ( "@" , 1 )
return "@" . join ( [ user , domain . lower ( ) ] )


signature:
def save ( self ) :
    """Resend a verification email to the provided address .
 If the provided email is already verified no action is taken ."""

implementation:
try :
    email = models . EmailAddress . objects . get ( email = self . validated_data [ "email" ] , is_verified = False )
    logger . debug ( "Resending verification email to %s" , self . validated_data [ "email" ] , )
    email . send_confirmation ( )
except models . EmailAddress . DoesNotExist :
    logger . debug ( "Not resending verification email to %s because the address " "doesn't exist in the database." , self . validated_data [ "email" ] , )


signature:
def create ( self , * args , ** kwargs ) :
    """Create a new email address ."""

implementation:
is_primary = kwargs . pop ( "is_primary" , False )
with transaction . atomic ( ) :
    email = super ( EmailAddressManager , self ) . create ( * args , ** kwargs )
    if is_primary :
        email . set_primary ( )
return email


signature:
def get_queryset ( self ) :
    """Return all unexpired password reset tokens ."""

implementation:
oldest = timezone . now ( ) - app_settings . PASSWORD_RESET_EXPIRATION
queryset = super ( ValidPasswordResetTokenManager , self ) . get_queryset ( )
return queryset . filter ( created_at__gt = oldest )


signature:
def handle ( self , * args , ** kwargs ) :
    """Handle execution of the command ."""

implementation:
cutoff = timezone . now ( )
cutoff -= app_settings . CONFIRMATION_EXPIRATION
cutoff -= app_settings . CONFIRMATION_SAVE_PERIOD
queryset = models . EmailConfirmation . objects . filter ( created_at__lte = cutoff )
count = queryset . count ( )
queryset . delete ( )
if count :
    self . stdout . write ( self . style . SUCCESS ( "Removed {count} old email confirmation(s)" . format ( count = count ) ) )
else :
    self . stdout . write ( "No email confirmations to remove." )


signature:
def get_user ( self , user_id ) :
    """Get a user by their ID .
 Args :
 user _ id :
 The ID of the user to fetch .
 Returns :
 The user with the specified ID if they exist and ` ` None ` `
 otherwise ."""

implementation:
try :
    return get_user_model ( ) . objects . get ( id = user_id )
except get_user_model ( ) . DoesNotExist :
    return None


signature:
def authenticate ( self , request , email = None , password = None , username = None ) :
    """Attempt to authenticate a set of credentials .
 Args :
 request :
 The request associated with the authentication attempt .
 email :
 The user ' s email address .
 password :
 The user ' s password .
 username :
 An alias for the ` ` email ` ` field . This is provided for
 compatability with Django ' s built in authentication
 views .
 Returns :
 The user associated with the provided credentials if they
 are valid . Returns ` ` None ` ` otherwise ."""

implementation:
email = email or username
try :
    email_instance = models . EmailAddress . objects . get ( is_verified = True , email = email )
except models . EmailAddress . DoesNotExist :
    return None
user = email_instance . user
if user . check_password ( password ) :
    return user
return None


signature:
def post ( self , request ) :
    """Save the provided data using the class ' serializer .
 Args :
 request :
 The request being made .
 Returns :
 An ` ` APIResponse ` ` instance . If the request was successful
 the response will have a 200 status code and contain the
 serializer ' s data . Otherwise a 400 status code and the
 request ' s errors will be returned ."""

implementation:
serializer = self . get_serializer ( data = request . data )
if serializer . is_valid ( ) :
    serializer . save ( )
    return Response ( serializer . data )
return Response ( serializer . errors , status = status . HTTP_400_BAD_REQUEST )


signature:
def get_repr ( self , obj , referent = None ) :
    """Return an HTML tree block describing the given object ."""

implementation:
objtype = type ( obj )
typename = str ( objtype . __module__ ) + "." + objtype . __name__
prettytype = typename . replace ( "__builtin__." , "" )
name = getattr ( obj , "__name__" , "" )
if name :
    prettytype = "%s %r" % ( prettytype , name )
key = ""
if referent :
    key = self . get_refkey ( obj , referent )
url = reverse ( 'dowser_trace_object' , args = ( typename , id ( obj ) ) )
return ( '%s ' '%s%s
' '%s' % ( url , id ( obj ) , prettytype , key , get_repr ( obj , 100 ) ) )


signature:
def get_refkey ( self , obj , referent ) :
    """Return the dict key or attribute name of obj which refers to
 referent ."""

implementation:
if isinstance ( obj , dict ) :
    for k , v in obj . items ( ) :
        if v is referent :
            return " (via its %r key)" % k
for k in dir ( obj ) + [ '__dict__' ] :
    if getattr ( obj , k , None ) is referent :
        return " (via its %r attribute)" % k
return ""


signature:
def walk ( self , maxresults = 100 , maxdepth = None ) :
    """Walk the object tree , ignoring duplicates and circular refs ."""

implementation:
log . debug ( "step" )
self . seen = { }
self . ignore ( self , self . __dict__ , self . obj , self . seen , self . _ignore )
# Ignore the calling frame , its builtins , globals and locals
self . ignore_caller ( )
self . maxdepth = maxdepth
count = 0
log . debug ( "will iterate results" )
for result in self . _gen ( self . obj ) :
    log . debug ( "will yeld" )
    yield result
    count += 1
    if maxresults and count >= maxresults :
        yield 0 , 0 , "==== Max results reached ===="
        return


signature:
def print_tree ( self , maxresults = 100 , maxdepth = None ) :
    """Walk the object tree , pretty - printing each branch ."""

implementation:
self . ignore_caller ( )
for depth , refid , rep in self . walk ( maxresults , maxdepth ) :
    print ( ( "%9d" % refid ) , ( " " * depth * 2 ) , rep )


implementation:
self . ignore_caller ( )
for trail in self . walk ( maxresults , maxdepth ) :
    print ( trail )
if self . stops :
    print ( "%s paths stopped because max depth reached" % self . stops )


signature:
def get_finders ( ) :
    """Set the media fixtures finders on settings . py .
 Example :
 MEDIA _ FIXTURES _ FILES _ FINDERS = (
 ' django _ media _ fixtures . finders . FileSystemFinder ' ,
 ' django _ media _ fixtures . finders . AppDirectoriesFinder ' , # default"""

implementation:
if hasattr ( settings , 'MEDIA_FIXTURES_FILES_FINDERS' ) :
    finders = settings . MEDIA_FIXTURES_FILES_FINDERS
else :
    finders = ( 'django_media_fixtures.finders.AppDirectoriesFinder' , )
for finder_path in finders :
    yield get_finder ( finder_path )


signature:
def get_finder ( import_path ) :
    """Imports the media fixtures files finder class described by import _ path , where
 import _ path is the full Python path to the class ."""

implementation:
Finder = import_string ( import_path )
if not issubclass ( Finder , BaseFinder ) :
    raise ImproperlyConfigured ( 'Finder "%s" is not a subclass of "%s"' % ( Finder , BaseFinder ) )
return Finder ( )


signature:
def find ( self , path , all = False ) :
    """Looks for files in the extra locations
 as defined in ` ` MEDIA _ FIXTURES _ FILES _ DIRS ` ` ."""

implementation:
matches = [ ]
for prefix , root in self . locations :
    if root not in searched_locations :
        searched_locations . append ( root )
    matched_path = self . find_location ( root , path , prefix )
    if matched_path :
        if not all :
            return matched_path
        matches . append ( matched_path )
return matches


signature:
def find_location ( self , root , path , prefix = None ) :
    """Finds a requested media file in a location , returning the found
 absolute path ( or ` ` None ` ` if no match ) ."""

implementation:
if prefix :
    prefix = '%s%s' % ( prefix , os . sep )
    if not path . startswith ( prefix ) :
        return None
    path = path [ len ( prefix ) : ]
path = safe_join ( root , path )
if os . path . exists ( path ) :
    return path


signature:
def list ( self , ignore_patterns ) :
    """List all files in all locations ."""

implementation:
for prefix , root in self . locations :
    storage = self . storages [ root ]
    for path in utils . get_files ( storage , ignore_patterns ) :
        yield path , storage


signature:
def list ( self , ignore_patterns ) :
    """List all files in all app storages ."""

implementation:
for storage in six . itervalues ( self . storages ) :
    if storage . exists ( '' ) : # check if storage location exists
        for path in utils . get_files ( storage , ignore_patterns ) :
            yield path , storage


signature:
def find ( self , path , all = False ) :
    """Looks for files in the app directories ."""

implementation:
matches = [ ]
for app in self . apps :
    app_location = self . storages [ app ] . location
    if app_location not in searched_locations :
        searched_locations . append ( app_location )
    match = self . find_in_app ( app , path )
    if match :
        if not all :
            return match
        matches . append ( match )
return matches


signature:
def find_in_app ( self , app , path ) :
    """Find a requested media file in an app ' s media fixtures locations ."""

implementation:
storage = self . storages . get ( app , None )
if storage : # only try to find a file if the source dir actually exists
    if storage . exists ( path ) :
        matched_path = storage . path ( path )
        if matched_path :
            return matched_path


signature:
def set_options ( self , ** options ) :
    """Set instance variables based on an options dict"""

implementation:
self . interactive = options [ 'interactive' ]
self . verbosity = options [ 'verbosity' ]
self . symlink = options [ 'link' ]
self . clear = options [ 'clear' ]
self . dry_run = options [ 'dry_run' ]
ignore_patterns = options [ 'ignore_patterns' ]
if options [ 'use_default_ignore_patterns' ] :
    ignore_patterns += [ 'CVS' , '.*' , '*~' ]
self . ignore_patterns = list ( set ( ignore_patterns ) )
self . post_process = options [ 'post_process' ]


signature:
def collect ( self ) :
    """Perform the bulk of the work of collectmedia .
 Split off from handle ( ) to facilitate testing ."""

implementation:
if self . symlink and not self . local :
    raise CommandError ( "Can't symlink to a remote destination." )
if self . clear :
    self . clear_dir ( '' )
if self . symlink :
    handler = self . link_file
else :
    handler = self . copy_file
found_files = OrderedDict ( )
for finder in get_finders ( ) :
    for path , storage in finder . list ( self . ignore_patterns ) : # Prefix the relative path if the source storage contains it
        if getattr ( storage , 'prefix' , None ) :
            prefixed_path = os . path . join ( storage . prefix , path )
        else :
            prefixed_path = path
        if prefixed_path not in found_files :
            found_files [ prefixed_path ] = ( storage , path )
            handler ( path , prefixed_path , storage )
# Here we check if the storage backend has a post _ process
# method and pass it the list of modified files .
if self . post_process and hasattr ( self . storage , 'post_process' ) :
    processor = self . storage . post_process ( found_files , dry_run = self . dry_run )
    for original_path , processed_path , processed in processor :
        if isinstance ( processed , Exception ) :
            self . stderr . write ( "Post-processing '%s' failed!" % original_path )
            # Add a blank line before the traceback , otherwise it ' s
            # too easy to miss the relevant part of the error message .
            self . stderr . write ( "" )
            raise processed
        if processed :
            self . log ( "Post-processed '%s' as '%s'" % ( original_path , processed_path ) , level = 1 )
            self . post_processed_files . append ( original_path )
        else :
            self . log ( "Skipped post-processing '%s'" % original_path )
return { 'modified' : self . copied_files + self . symlinked_files , 'unmodified' : self . unmodified_files , 'post_processed' : self . post_processed_files , }


signature:
def clear_dir ( self , path ) :
    """Deletes the given relative path using the destination storage backend ."""

implementation:
dirs , files = self . storage . listdir ( path )
for f in files :
    fpath = os . path . join ( path , f )
    if self . dry_run :
        self . log ( "Pretending to delete '%s'" % smart_text ( fpath ) , level = 1 )
    else :
        self . log ( "Deleting '%s'" % smart_text ( fpath ) , level = 1 )
        self . storage . delete ( fpath )
for d in dirs :
    self . clear_dir ( os . path . join ( path , d ) )


signature:
def delete_file ( self , path , prefixed_path , source_storage ) :
    """Checks if the target file should be deleted if it already exists"""

implementation:
if self . storage . exists ( prefixed_path ) :
    try : # When was the target file modified last time ?
        target_last_modified = self . storage . modified_time ( prefixed_path )
    except ( OSError , NotImplementedError , AttributeError ) : # The storage doesn ' t support ` ` modified _ time ` ` or failed
        pass
    else :
        try : # When was the source file modified last time ?
            source_last_modified = source_storage . modified_time ( path )
        except ( OSError , NotImplementedError , AttributeError ) :
            pass
        else : # The full path of the target file
            if self . local :
                full_path = self . storage . path ( prefixed_path )
            else :
                full_path = None
            # Skip the file if the source file is younger
            # Avoid sub - second precision ( see # 14665 , # 19540)
            if ( target_last_modified . replace ( microsecond = 0 ) >= source_last_modified . replace ( microsecond = 0 ) ) :
                if not ( ( self . symlink and full_path and not os . path . islink ( full_path ) ) or ( not self . symlink and full_path and os . path . islink ( full_path ) ) ) :
                    if prefixed_path not in self . unmodified_files :
                        self . unmodified_files . append ( prefixed_path )
                    self . log ( "Skipping '%s' (not modified)" % path )
                    return False
    # Then delete the existing file if really needed
    if self . dry_run :
        self . log ( "Pretending to delete '%s'" % path )
    else :
        self . log ( "Deleting '%s'" % path )
        self . storage . delete ( prefixed_path )
return True


signature:
def link_file ( self , path , prefixed_path , source_storage ) :
    """Attempt to link ` ` path ` `"""

implementation:
# Skip this file if it was already copied earlier
if prefixed_path in self . symlinked_files :
    return self . log ( "Skipping '%s' (already linked earlier)" % path )
# Delete the target file if needed or break
if not self . delete_file ( path , prefixed_path , source_storage ) :
    return
# The full path of the source file
source_path = source_storage . path ( path )
# Finally link the file
if self . dry_run :
    self . log ( "Pretending to link '%s'" % source_path , level = 1 )
else :
    self . log ( "Linking '%s'" % source_path , level = 1 )
    full_path = self . storage . path ( prefixed_path )
    try :
        os . makedirs ( os . path . dirname ( full_path ) )
    except OSError :
        pass
    try :
        if os . path . lexists ( full_path ) :
            os . unlink ( full_path )
        os . symlink ( source_path , full_path )
    except AttributeError :
        import platform
        raise CommandError ( "Symlinking is not supported by Python %s." % platform . python_version ( ) )
    except NotImplementedError :
        import platform
        raise CommandError ( "Symlinking is not supported in this " "platform (%s)." % platform . platform ( ) )
    except OSError as e :
        raise CommandError ( e )
if prefixed_path not in self . symlinked_files :
    self . symlinked_files . append ( prefixed_path )


signature:
def copy_file ( self , path , prefixed_path , source_storage ) :
    """Attempt to copy ` ` path ` ` with storage"""

implementation:
# Skip this file if it was already copied earlier
if prefixed_path in self . copied_files :
    return self . log ( "Skipping '%s' (already copied earlier)" % path )
# Delete the target file if needed or break
if not self . delete_file ( path , prefixed_path , source_storage ) :
    return
# The full path of the source file
source_path = source_storage . path ( path )
# Finally start copying
if self . dry_run :
    self . log ( "Pretending to copy '%s'" % source_path , level = 1 )
else :
    self . log ( "Copying '%s'" % source_path , level = 1 )
    with source_storage . open ( path ) as source_file :
        self . storage . save ( prefixed_path , source_file )
self . copied_files . append ( prefixed_path )


signature:
def reorderChild ( self , parent , newitem ) :
    """Reorder a list to match target by moving a sequence at a time .
 Written for QtAbstractItemModel . moveRows ."""

implementation:
source = self . getItem ( parent ) . childItems
target = newitem . childItems
i = 0
while i < len ( source ) :
    if source [ i ] == target [ i ] :
        i += 1
        continue
    else :
        i0 = i
        j0 = source . index ( target [ i0 ] )
        j = j0 + 1
        while j < len ( source ) :
            if source [ j ] == target [ j - j0 + i0 ] :
                j += 1
                continue
            else :
                break
        self . moveRows ( parent , i0 , j0 , j - j0 )
        i += j - j0


signature:
def moveRows ( self , parent , index_to , index_from , length ) :
    """Move a sub sequence in a list
 index _ to must be smaller than index _ from"""

implementation:
source = self . getItem ( parent ) . childItems
self . beginMoveRows ( parent , index_from , index_from + length - 1 , parent , index_to )
sublist = [ source . pop ( index_from ) for _ in range ( length ) ]
for _ in range ( length ) :
    source . insert ( index_to , sublist . pop ( ) )
self . endMoveRows ( )


signature:
def cur_space ( self , name = None ) :
    """Set the current space to Space ` ` name ` ` and return it .
 If called without arguments , the current space is returned .
 Otherwise , the current space is set to the space named ` ` name ` `
 and the space is returned ."""

implementation:
if name is None :
    return self . _impl . model . currentspace . interface
else :
    self . _impl . model . currentspace = self . _impl . spaces [ name ]
    return self . cur_space ( )


signature:
def _baseattrs ( self ) :
    """A dict of members expressed in literals"""

implementation:
result = super ( ) . _baseattrs
result [ "spaces" ] = self . spaces . _baseattrs
return result


signature:
def new_space ( self , name = None , bases = None , formula = None , refs = None ) :
    """Create a child space .
 Args :
 name ( str , optional ) : Name of the space . Defaults to ` ` SpaceN ` ` ,
 where ` ` N ` ` is a number determined automatically .
 bases ( optional ) : A space or a sequence of spaces to be the base
 space ( s ) of the created space .
 formula ( optional ) : Function to specify the parameters of
 dynamic child spaces . The signature of this function is used
 for setting parameters for dynamic child spaces .
 This function should return a mapping of keyword arguments
 to be passed to this method when the dynamic child spaces
 are created .
 Returns :
 The new child space ."""

implementation:
space = self . _impl . model . currentspace = self . _impl . new_space ( name = name , bases = get_impls ( bases ) , formula = formula , refs = refs )
return space . interface


signature:
def import_module ( self , module = None , recursive = False , ** params ) :
    """Create a child space from an module .
 Args :
 module : a module object or name of the module object .
 recursive : Not yet implemented .
 * * params : arguments to pass to ` ` new _ space ` `
 Returns :
 The new child space created from the module ."""

implementation:
if module is None :
    if "module_" in params :
        warnings . warn ( "Parameter 'module_' is deprecated. Use 'module' instead." )
        module = params . pop ( "module_" )
    else :
        raise ValueError ( "no module specified" )
if "bases" in params :
    params [ "bases" ] = get_impls ( params [ "bases" ] )
space = ( self . _impl . model . currentspace ) = self . _impl . new_space_from_module ( module , recursive = recursive , ** params )
return get_interfaces ( space )


signature:
def new_space_from_module ( self , module , recursive = False , ** params ) :
    """Create a child space from an module .
 Alias to : py : meth : ` import _ module ` .
 Args :
 module : a module object or name of the module object .
 recursive : Not yet implemented .
 * * params : arguments to pass to ` ` new _ space ` `
 Returns :
 The new child space created from the module ."""

implementation:
if "bases" in params :
    params [ "bases" ] = get_impls ( params [ "bases" ] )
space = ( self . _impl . model . currentspace ) = self . _impl . new_space_from_module ( module , recursive = recursive , ** params )
return get_interfaces ( space )


signature:
def new_space_from_excel ( self , book , range_ , sheet = None , name = None , names_row = None , param_cols = None , space_param_order = None , cells_param_order = None , transpose = False , names_col = None , param_rows = None , ) :
    """Create a child space from an Excel range .
 To use this method , ` ` openpyxl ` ` package must be installed .
 Args :
 book ( str ) : Path to an Excel file .
 range _ ( str ) : Range expression , such as " A1 " , " $ G4 : $ K10 " ,
 or named range " NamedRange1 " .
 sheet ( str ) : Sheet name ( case ignored ) .
 name ( str , optional ) : Name of the space . Defaults to ` ` SpaceN ` ` ,
 where ` ` N ` ` is a number determined automatically .
 names _ row ( optional ) : an index number indicating
 what row contains the names of cells and parameters .
 Defaults to the top row ( 0 ) .
 param _ cols ( optional ) : a sequence of index numbers
 indicating parameter columns .
 Defaults to only the leftmost column ( [ 0 ] ) .
 names _ col ( optional ) : an index number , starting from 0,
 indicating what column contains additional parameters .
 param _ rows ( optional ) : a sequence of index numbers , starting from
 0 , indicating rows of additional parameters , in case cells are
 defined in two dimensions .
 transpose ( optional ) : Defaults to ` ` False ` ` .
 If set to ` ` True ` ` , " row ( s ) " and " col ( s ) " in the parameter
 names are interpreted inversely , i . e .
 all indexes passed to " row ( s ) " parameters are interpreted
 as column indexes ,
 and all indexes passed to " col ( s ) " parameters as row indexes .
 space _ param _ order : a sequence to specify space parameters and
 their orders . The elements of the sequence denote the indexes
 of ` ` param _ cols ` ` elements , and optionally the index of
 ` ` param _ rows ` ` elements shifted by the length of
 ` ` param _ cols ` ` . The elements of this parameter and
 ` ` cell _ param _ order ` ` must not overlap .
 cell _ param _ order ( optional ) : a sequence to reorder the parameters .
 The elements of the sequence denote the indexes of
 ` ` param _ cols ` ` elements , and optionally the index of
 ` ` param _ rows ` ` elements shifted by the length of
 ` ` param _ cols ` ` . The elements of this parameter and
 ` ` cell _ space _ order ` ` must not overlap .
 Returns :
 The new child space created from the Excel range ."""

implementation:
space = self . _impl . new_space_from_excel ( book , range_ , sheet , name , names_row , param_cols , space_param_order , cells_param_order , transpose , names_col , param_rows , )
return get_interfaces ( space )


signature:
def restore_state ( self , system ) :
    """Called after unpickling to restore some attributes manually ."""

implementation:
for space in self . _spaces . values ( ) :
    space . restore_state ( system )


signature:
def new_space ( self , name = None , bases = None , formula = None , * , refs = None , source = None , is_derived = False , prefix = "" ) :
    """Create a new child space .
 Args :
 name ( str ) : Name of the space . If omitted , the space is
 created automatically .
 bases : If specified , the new space becomes a derived space of
 the ` base ` space .
 formula : Function whose parameters used to set space parameters .
 refs : a mapping of refs to be added .
 arguments : ordered dict of space parameter names to their values .
 source : A source module from which cell definitions are read .
 prefix : Prefix to the autogenerated name when name is None ."""

implementation:
from modelx . core . space import StaticSpaceImpl
if name is None :
    name = self . spacenamer . get_next ( self . namespace , prefix )
if name in self . namespace :
    raise ValueError ( "Name '%s' already exists." % name )
if not prefix and not is_valid_name ( name ) :
    raise ValueError ( "Invalid name '%s'." % name )
space = self . _new_space ( name = name , formula = formula , refs = refs , source = source , is_derived = is_derived , )
self . _set_space ( space )
self . model . spacegraph . add_space ( space )
# Set up direct base spaces and mro
if bases is not None :
    if isinstance ( bases , StaticSpaceImpl ) :
        bases = [ bases ]
    space . add_bases ( bases )
return space


signature:
def get_node ( obj , args , kwargs ) :
    """Create a node from arguments and return it"""

implementation:
if args is None and kwargs is None :
    return ( obj , )
if kwargs is None :
    kwargs = { }
return obj , _bind_args ( obj , args , kwargs )


signature:
def node_get_args ( node ) :
    """Return an ordered mapping from params to args"""

implementation:
obj = node [ OBJ ]
key = node [ KEY ]
boundargs = obj . formula . signature . bind ( * key )
boundargs . apply_defaults ( )
return boundargs . arguments


signature:
def tuplize_key ( obj , key , remove_extra = False ) :
    """Args"""

implementation:
paramlen = len ( obj . formula . parameters )
if isinstance ( key , str ) :
    key = ( key , )
elif not isinstance ( key , Sequence ) :
    key = ( key , )
if not remove_extra :
    return key
else :
    arglen = len ( key )
    if arglen :
        return key [ : min ( arglen , paramlen ) ]
    else :
        return key


signature:
def defcells ( space = None , name = None , * funcs ) :
    """Decorator / function to create cells from Python functions .
 Convenience decorator / function to create new cells directly from function
 definitions or function objects substituting for calling
 : py : meth : ` new _ cells < modelx . core . space . StaticSpace . new _ cells > `
 method of the parent space .
 There are 3 ways to use ` ` defcells ` ` to define cells from functions .
 * * 1 . As a decorator without arguments * *
 To create a cells from a function definition in the current space of the
 current model with the same name as the function ' s : :
 @ defcells
 def foo ( x ) :
 return x
 * * 2 . As a decorator with arguments * *
 To create a cells from a function definition in a given space and / or with
 a given name : :
 @ defcells ( space = space , name = name )
 def foo ( x ) :
 return x
 * * 3 . As a function * *
 To create a multiple cells from a multiple function definitions : :
 def foo ( x ) :
 return x
 def bar ( y ) :
 return foo ( y )
 foo , bar = defcells ( foo , bar )
 Args :
 space ( optional ) : For the 2nd usage , a space to create the cells in .
 Defaults to the current space of the current model .
 name ( optional ) : For the 2nd usage , a name of the created cells .
 Defaults to the function name .
 * funcs : For the 3rd usage , function objects . ( ` ` space ` ` and ` ` name ` `
 also take function objects for the 3rd usage . )
 Returns :
 For the 1st and 2nd usage , the newly created single cells is returned .
 For the 3rd usage , a list of newly created cells are returned ."""

implementation:
if isinstance ( space , _FunctionType ) and name is None : # called as a function decorator
    func = space
    return _system . currentspace . new_cells ( formula = func ) . interface
elif ( isinstance ( space , _Space ) or space is None ) and ( isinstance ( name , str ) or name is None ) : # return decorator itself
    if space is None :
        space = _system . currentspace . interface
    return _CellsMaker ( space = space . _impl , name = name )
elif all ( isinstance ( func , _FunctionType ) for func in ( space , name ) + funcs ) :
    return [ defcells ( func ) for func in ( space , name ) + funcs ]
else :
    raise TypeError ( "invalid defcells arguments" )


signature:
def get_object ( name : str ) :
    """Get a modelx object from its full name ."""

implementation:
# TODO : Duplicate of system . get _ object
elms = name . split ( "." )
parent = get_models ( ) [ elms . pop ( 0 ) ]
while len ( elms ) > 0 :
    obj = elms . pop ( 0 )
    parent = getattr ( parent , obj )
return parent


signature:
def _get_node ( name : str , args : str ) :
    """Get node from object name and arg string
 Not Used . Left for future reference purpose ."""

implementation:
obj = get_object ( name )
args = ast . literal_eval ( args )
if not isinstance ( args , tuple ) :
    args = ( args , )
return obj . node ( * args )


signature:
def cur_model ( model = None ) :
    """Get and / or set the current model .
 If ` ` model ` ` is given , set the current model to ` ` model ` ` and return it .
 ` ` model ` ` can be the name of a model object , or a model object itself .
 If ` ` model ` ` is not given , the current model is returned ."""

implementation:
if model is None :
    if _system . currentmodel is not None :
        return _system . currentmodel . interface
    else :
        return None
else :
    if isinstance ( model , _Model ) :
        _system . currentmodel = model . _impl
    else :
        _system . currentmodel = _system . models [ model ]
    return _system . currentmodel . interface


signature:
def cur_space ( space = None ) :
    """Get and / or set the current space of the current model .
 If ` ` name ` ` is given , the current space of the current model is
 set to ` ` name ` ` and return it .
 If ` ` name ` ` is not given , the current space of the current model
 is returned ."""

implementation:
if space is None :
    if _system . currentmodel is not None :
        if _system . currentmodel . currentspace is not None :
            return _system . currentmodel . currentspace . interface
        else :
            return None
    else :
        return None
else :
    if isinstance ( space , _Space ) :
        cur_model ( space . model )
        _system . currentmodel . currentspace = space . _impl
    else :
        _system . currentmodel . currentspace = _system . currentmodel . spaces [ space ]
    return cur_space ( )


signature:
def custom_showwarning ( message , category , filename = "" , lineno = - 1 , file = None , line = None ) :
    """Hook to override default showwarning .
 https : / / stackoverflow . com / questions / 2187269 / python - print - only - the - message - on - warnings"""

implementation:
if file is None :
    file = sys . stderr
    if file is None : # sys . stderr is None when run with pythonw . exe :
    # warnings get lost
        return
text = "%s: %s\n" % ( category . __name__ , message )
try :
    file . write ( text )
except OSError : # the file ( probably stderr ) is invalid - this warning gets lost .
    pass


signature:
def custom_showtraceback ( self , exc_tuple = None , filename = None , tb_offset = None , exception_only = False , running_compiled_code = False , ) :
    """Custom showtraceback for monkey - patching IPython ' s InteractiveShell
 https : / / stackoverflow . com / questions / 1261668 / cannot - override - sys - excepthook"""

implementation: self . default_showtraceback ( exc_tuple , filename , tb_offset , exception_only = True , running_compiled_code = running_compiled_code , )


signature:
def excepthook ( self , except_type , exception , traceback ) :
    """Not Used : Custom exception hook to replace sys . excepthook
 This is for CPython ' s default shell . IPython does not use sys . exepthook .
 https : / / stackoverflow . com / questions / 27674602 / hide - traceback - unless - a - debug - flag - is - set"""

implementation:
if except_type is DeepReferenceError :
    print ( exception . msg )
else :
    self . default_excepthook ( except_type , exception , traceback )


signature:
def tracemessage ( self , maxlen = 6 ) :
    """if maxlen > 0 , the message is shortened to maxlen traces ."""

implementation:
result = ""
for i , value in enumerate ( self ) :
    result += "{0}: {1}\n" . format ( i , get_node_repr ( value ) )
result = result . strip ( "\n" )
lines = result . split ( "\n" )
if maxlen and len ( lines ) > maxlen :
    i = int ( maxlen / 2 )
    lines = lines [ : i ] + [ "..." ] + lines [ - ( maxlen - i ) : ]
    result = "\n" . join ( lines )
return result


signature:
def setup_ipython ( self ) :
    """Monkey patch shell ' s error handler .
 This method is to monkey - patch the showtraceback method of
 IPython ' s InteractiveShell to
 _ _ IPYTHON _ _ is not detected when starting an IPython kernel ,
 so this method is called from start _ kernel in spyder - modelx ."""

implementation:
if self . is_ipysetup :
    return
from ipykernel . kernelapp import IPKernelApp
self . shell = IPKernelApp . instance ( ) . shell
# None in PyCharm console
if not self . shell and is_ipython ( ) :
    self . shell = get_ipython ( )
if self . shell :
    shell_class = type ( self . shell )
    shell_class . default_showtraceback = shell_class . showtraceback
    shell_class . showtraceback = custom_showtraceback
    self . is_ipysetup = True
else :
    raise RuntimeError ( "IPython shell not found." )


signature:
def restore_ipython ( self ) :
    """Restore default IPython showtraceback"""

implementation:
if not self . is_ipysetup :
    return
shell_class = type ( self . shell )
shell_class . showtraceback = shell_class . default_showtraceback
del shell_class . default_showtraceback
self . is_ipysetup = False


signature:
def restore_python ( self ) :
    """Restore Python settings to the original states"""

implementation:
orig = self . orig_settings
sys . setrecursionlimit ( orig [ "sys.recursionlimit" ] )
if "sys.tracebacklimit" in orig :
    sys . tracebacklimit = orig [ "sys.tracebacklimit" ]
else :
    if hasattr ( sys , "tracebacklimit" ) :
        del sys . tracebacklimit
if "showwarning" in orig :
    warnings . showwarning = orig [ "showwarning" ]
orig . clear ( )
threading . stack_size ( )


signature:
def get_object ( self , name ) :
    """Retrieve an object by its absolute name ."""

implementation:
parts = name . split ( "." )
model_name = parts . pop ( 0 )
return self . models [ model_name ] . get_object ( "." . join ( parts ) )


signature:
def get_modeltree ( model = None ) :
    """Alias to : func : ` get _ tree ` ."""

implementation:
if model is None :
    model = mx . cur_model ( )
treemodel = ModelTreeModel ( model . _baseattrs )
view = QTreeView ( )
view . setModel ( treemodel )
view . setWindowTitle ( "Model %s" % model . name )
view . setAlternatingRowColors ( True )
return view


signature:
def show_tree ( model = None ) :
    """Display the model tree window .
 Args :
 model : : class : ` Model < modelx . core . model . Model > ` object .
 Defaults to the current model .
 Warnings :
 For this function to work with Spyder , * Graphics backend * option
 of Spyder must be set to * inline * ."""

implementation:
if model is None :
    model = mx . cur_model ( )
view = get_modeltree ( model )
app = QApplication . instance ( )
if not app :
    raise RuntimeError ( "QApplication does not exist." )
view . show ( )
app . exec_ ( )


signature:
def get_interfaces ( impls ) :
    """Get interfaces from their implementations ."""

implementation:
if impls is None :
    return None
elif isinstance ( impls , OrderMixin ) :
    result = OrderedDict ( )
    for name in impls . order :
        result [ name ] = impls [ name ] . interface
    return result
elif isinstance ( impls , Mapping ) :
    return { name : impls [ name ] . interface for name in impls }
elif isinstance ( impls , Sequence ) :
    return [ impl . interface for impl in impls ]
else :
    return impls . interface


signature:
def get_impls ( interfaces ) :
    """Get impls from their interfaces ."""

implementation:
if interfaces is None :
    return None
elif isinstance ( interfaces , Mapping ) :
    return { name : interfaces [ name ] . _impl for name in interfaces }
elif isinstance ( interfaces , Sequence ) :
    return [ interfaces . _impl for interfaces in interfaces ]
else :
    return interfaces . _impl


signature:
def update_lazyevals ( self ) :
    """Update all LazyEvals in self
 self . lzy _ evals must be set to LazyEval object ( s ) enough to
 update all owned LazyEval objects ."""

implementation:
if self . lazy_evals is None :
    return
elif isinstance ( self . lazy_evals , LazyEval ) :
    self . lazy_evals . get_updated ( )
else :
    for lz in self . lazy_evals :
        lz . get_updated ( )


signature:
def evalrepr ( self ) :
    """Evaluable repr"""

implementation:
if self . is_model ( ) :
    return self . get_fullname ( )
else :
    return self . parent . evalrepr + "." + self . name


signature:
def _baseattrs ( self ) :
    """A dict of members expressed in literals"""

implementation:
result = { "type" : type ( self ) . __name__ , "id" : id ( self ) , "name" : self . name , "fullname" : self . fullname , "repr" : self . _get_repr ( ) , }
return result


signature:
def _to_attrdict ( self , attrs = None ) :
    """Get extra attributes"""

implementation:
result = self . _baseattrs
for attr in attrs :
    if hasattr ( self , attr ) :
        result [ attr ] = getattr ( self , attr ) . _to_attrdict ( attrs )
return result


implementation:
result = { "type" : type ( self ) . __name__ }
try :
    result [ "items" ] = { name : item . _baseattrs for name , item in self . items ( ) if name [ 0 ] != "_" }
except :
    raise RuntimeError ( "%s literadict raised an error" % self )
return result


signature:
def _update_data ( self ) :
    """Update altfunc"""

implementation:
func = self . owner . formula . func
codeobj = func . __code__
name = func . __name__
# self . cells . name # func . _ _ name _ _
namespace_impl = self . owner . _namespace_impl . get_updated ( )
namespace = namespace_impl . interfaces
selfnode = get_node ( self . owner , None , None )
for name in self . owner . formula . srcnames :
    if name in namespace_impl and isinstance ( namespace_impl [ name ] , ReferenceImpl ) :
        refnode = get_node ( namespace_impl [ name ] , None , None )
        self . owner . model . lexdep . add_path ( [ selfnode , refnode ] )
closure = func . __closure__
# None normally .
if closure is not None : # pytest fails without this .
    closure = create_closure ( self . owner . interface )
self . altfunc = FunctionType ( codeobj , namespace , name = name , closure = closure )


signature:
def convert_args ( args , kwargs ) :
    """If args and kwargs contains Cells , Convert them to their values ."""

implementation:
found = False
for arg in args :
    if isinstance ( arg , Cells ) :
        found = True
        break
if found :
    args = tuple ( arg . value if isinstance ( arg , Cells ) else arg for arg in args )
if kwargs is not None :
    for key , arg in kwargs . items ( ) :
        if isinstance ( arg , Cells ) :
            kwargs [ key ] = arg . value
return args , kwargs


signature:
def shareable_parameters ( cells ) :
    """Return parameter names if the parameters are shareable among cells .
 Parameters are shareable among multiple cells when all the cells
 have the parameters in the same order if they ever have any .
 For example , if cells are foo ( ) , bar ( x ) , baz ( x , y ) , then
 ( ' x ' , ' y ' ) are shareable parameters amounts them , as ' x ' and ' y '
 appear in the same order in the parameter list if they ever appear .
 Args :
 cells : An iterator yielding cells .
 Returns :
 None if parameters are not share ,
 tuple of shareable parameter names ,
 ( ) if cells are all scalars ."""

implementation:
result = [ ]
for c in cells . values ( ) :
    params = c . formula . parameters
    for i in range ( min ( len ( result ) , len ( params ) ) ) :
        if params [ i ] != result [ i ] :
            return None
    for i in range ( len ( result ) , len ( params ) ) :
        result . append ( params [ i ] )
return result


signature:
def copy ( self , space = None , name = None ) :
    """Make a copy of itself and return it ."""

implementation: return Cells ( space = space , name = name , formula = self . formula )


signature:
def node ( self , * args , ** kwargs ) :
    """Return a : class : ` CellNode ` object for the given arguments ."""

implementation: return CellNode ( get_node ( self . _impl , * convert_args ( args , kwargs ) ) )


implementation:
result = super ( ) . _baseattrs
result [ "params" ] = ", " . join ( self . parameters )
return result


signature:
def value ( self ) :
    """Return the value of the cells ."""

implementation:
if self . has_value :
    return self . _impl [ OBJ ] . get_value ( self . _impl [ KEY ] )
else :
    raise ValueError ( "Value not found" )


implementation:
result = { "type" : type ( self ) . __name__ , "obj" : self . cells . _baseattrs , "args" : self . args , "value" : self . value if self . has_value else None , "predslen" : len ( self . preds ) , "succslen" : len ( self . succs ) , "repr_parent" : self . cells . _impl . repr_parent ( ) , "repr" : self . cells . _get_repr ( ) , }
return result


signature:
def reorder_list ( source , targetorder ) :
    """Reorder a list to match target by moving a sequence at a time .
 Written for QtAbstractItemModel . moveRows ."""

implementation:
i = 0
while i < len ( source ) :
    if source [ i ] == targetorder [ i ] :
        i += 1
        continue
    else :
        i0 = i
        j0 = source . index ( targetorder [ i0 ] )
        j = j0 + 1
        while j < len ( source ) :
            if source [ j ] == targetorder [ j - j0 + i0 ] :
                j += 1
                continue
            else :
                break
        move_elements ( source , i0 , j0 , j - j0 )
        i += j - j0


signature:
def move_elements ( source , index_to , index_from , length ) :
    """Move a sub sequence in a list"""

implementation:
sublist = [ source . pop ( index_from ) for _ in range ( length ) ]
for _ in range ( length ) :
    source . insert ( index_to , sublist . pop ( ) )


signature:
def _get_col_index ( name ) :
    """Convert column name to index ."""

implementation:
index = string . ascii_uppercase . index
col = 0
for c in name . upper ( ) :
    col = col * 26 + index ( c ) + 1
return col


signature:
def _get_range ( book , range_ , sheet ) :
    """Return a range as nested dict of openpyxl cells ."""

implementation:
filename = None
if isinstance ( book , str ) :
    filename = book
    book = opxl . load_workbook ( book , data_only = True )
elif isinstance ( book , opxl . Workbook ) :
    pass
else :
    raise TypeError
if _is_range_address ( range_ ) :
    sheet_names = [ name . upper ( ) for name in book . sheetnames ]
    index = sheet_names . index ( sheet . upper ( ) )
    data = book . worksheets [ index ] [ range_ ]
else :
    data = _get_namedrange ( book , range_ , sheet )
    if data is None :
        raise ValueError ( "Named range '%s' not found in %s" % ( range_ , filename or book ) )
return data


signature:
def read_range ( filepath , range_expr , sheet = None , dict_generator = None ) :
    """Read values from an Excel range into a dictionary .
 ` range _ expr ` ie either a range address string , such as " A1 " , " $ C $ 3 : $ E $ 5 " ,
 or a defined name string for a range , such as " NamedRange1 " .
 If a range address is provided , ` sheet ` argument must also be provided .
 If a named range is provided and ` sheet ` is not , book level defined name
 is searched . If ` sheet ` is also provided , sheet level defined name for the
 specified ` sheet ` is searched .
 If range _ expr points to a single cell , its value is returned .
 ` dictgenerator ` is a generator function that yields keys and values of
 the returned dictionary . the excel range , as a nested tuple of openpyxl ' s
 Cell objects , is passed to the generator function as its single argument .
 If not specified , default generator is used , which maps tuples of row and
 column indexes , both starting with 0 , to their values .
 Args :
 filepath ( str ) : Path to an Excel file .
 range _ epxr ( str ) : Range expression , such as " A1 " , " $ G4 : $ K10 " ,
 or named range " NamedRange1"
 sheet ( str ) : Sheet name ( case ignored ) .
 None if book level defined range name is passed as ` range _ epxr ` .
 dict _ generator : A generator function taking a nested tuple of cells
 as a single parameter .
 Returns :
 Nested list containing range values ."""

implementation:
def default_generator ( cells ) :
    for row_ind , row in enumerate ( cells ) :
        for col_ind , cell in enumerate ( row ) :
            yield ( row_ind , col_ind ) , cell . value
book = opxl . load_workbook ( filepath , data_only = True )
if _is_range_address ( range_expr ) :
    sheet_names = [ name . upper ( ) for name in book . sheetnames ]
    index = sheet_names . index ( sheet . upper ( ) )
    cells = book . worksheets [ index ] [ range_expr ]
else :
    cells = _get_namedrange ( book , range_expr , sheet )
# In case of a single cell , return its value .
if isinstance ( cells , opxl . cell . Cell ) :
    return cells . value
if dict_generator is None :
    dict_generator = default_generator
gen = dict_generator ( cells )
return { keyval [ 0 ] : keyval [ 1 ] for keyval in gen }


signature:
def get_mro ( self , space ) :
    """Calculate the Method Resolution Order of bases using the C3 algorithm .
 Code modified from
 http : / / code . activestate . com / recipes / 577748 - calculate - the - mro - of - a - class /
 Args :
 bases : sequence of direct base spaces .
 Returns :
 mro as a list of bases including node itself"""

implementation:
seqs = [ self . get_mro ( base ) for base in self . get_bases ( space ) ] + [ list ( self . get_bases ( space ) ) ]
res = [ ]
while True :
    non_empty = list ( filter ( None , seqs ) )
    if not non_empty : # Nothing left to process , we ' re done .
        res . insert ( 0 , space )
        return res
    for seq in non_empty : # Find merge candidates among seq heads .
        candidate = seq [ 0 ]
        not_head = [ s for s in non_empty if candidate in s [ 1 : ] ]
        if not_head : # Reject the candidate .
            candidate = None
        else :
            break
    if not candidate :
        raise TypeError ( "inconsistent hierarchy, no C3 MRO is possible" )
    res . append ( candidate )
    for seq in non_empty : # Remove candidate .
        if seq [ 0 ] == candidate :
            del seq [ 0 ]


signature:
def _alter_code ( code , ** attrs ) :
    """Create a new code object by altering some of ` ` code ` ` attributes
 Args :
 code : code objcect
 attrs : a mapping of names of code object attrs to their values"""

implementation:
PyCode_New = ctypes . pythonapi . PyCode_New
PyCode_New . argtypes = ( ctypes . c_int , ctypes . c_int , ctypes . c_int , ctypes . c_int , ctypes . c_int , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . py_object , ctypes . c_int , ctypes . py_object )
PyCode_New . restype = ctypes . py_object
args = [ [ code . co_argcount , 'co_argcount' ] , [ code . co_kwonlyargcount , 'co_kwonlyargcount' ] , [ code . co_nlocals , 'co_nlocals' ] , [ code . co_stacksize , 'co_stacksize' ] , [ code . co_flags , 'co_flags' ] , [ code . co_code , 'co_code' ] , [ code . co_consts , 'co_consts' ] , [ code . co_names , 'co_names' ] , [ code . co_varnames , 'co_varnames' ] , [ code . co_freevars , 'co_freevars' ] , [ code . co_cellvars , 'co_cellvars' ] , [ code . co_filename , 'co_filename' ] , [ code . co_name , 'co_name' ] , [ code . co_firstlineno , 'co_firstlineno' ] , [ code . co_lnotab , 'co_lnotab' ] ]
for arg in args :
    if arg [ 1 ] in attrs :
        arg [ 0 ] = attrs [ arg [ 1 ] ]
return PyCode_New ( args [ 0 ] [ 0 ] , # code . co _ argcount ,
args [ 1 ] [ 0 ] , # code . co _ kwonlyargcount ,
args [ 2 ] [ 0 ] , # code . co _ nlocals ,
args [ 3 ] [ 0 ] , # code . co _ stacksize ,
args [ 4 ] [ 0 ] , # code . co _ flags ,
args [ 5 ] [ 0 ] , # code . co _ code ,
args [ 6 ] [ 0 ] , # code . co _ consts ,
args [ 7 ] [ 0 ] , # code . co _ names ,
args [ 8 ] [ 0 ] , # code . co _ varnames ,
args [ 9 ] [ 0 ] , # code . co _ freevars ,
args [ 10 ] [ 0 ] , # code . co _ cellvars ,
args [ 11 ] [ 0 ] , # code . co _ filename ,
args [ 12 ] [ 0 ] , # code . co _ name ,
args [ 13 ] [ 0 ] , # code . co _ firstlineno ,
args [ 14 ] [ 0 ] )


signature:
def alter_freevars ( func , globals_ = None , ** vars ) :
    """Replace local variables with free variables
 Warnings :
 This function does not work ."""

implementation:
if globals_ is None :
    globals_ = func . __globals__
frees = tuple ( vars . keys ( ) )
oldlocs = func . __code__ . co_names
newlocs = tuple ( name for name in oldlocs if name not in frees )
code = _alter_code ( func . __code__ , co_freevars = frees , co_names = newlocs , co_flags = func . __code__ . co_flags | inspect . CO_NESTED )
closure = _create_closure ( * vars . values ( ) )
return FunctionType ( code , globals_ , closure = closure )


signature:
def fix_lamdaline ( source ) :
    """Remove the last redundant token from lambda expression
 lambda x : return x )
 Return string without irrelevant tokens
 returned from inspect . getsource on lamda expr returns"""

implementation:
# Using undocumented generate _ tokens due to a tokenize . tokenize bug
# See https : / / bugs . python . org / issue23297
strio = io . StringIO ( source )
gen = tokenize . generate_tokens ( strio . readline )
tkns = [ ]
try :
    for t in gen :
        tkns . append ( t )
except tokenize . TokenError :
    pass
# Find the position of ' lambda '
lambda_pos = [ ( t . type , t . string ) for t in tkns ] . index ( ( tokenize . NAME , "lambda" ) )
# Ignore tokes before ' lambda '
tkns = tkns [ lambda_pos : ]
# Find the position of th las OP
lastop_pos = ( len ( tkns ) - 1 - [ t . type for t in tkns [ : : - 1 ] ] . index ( tokenize . OP ) )
lastop = tkns [ lastop_pos ]
# Remove OP from the line
fiedlineno = lastop . start [ 0 ]
fixedline = lastop . line [ : lastop . start [ 1 ] ] + lastop . line [ lastop . end [ 1 ] : ]
tkns = tkns [ : lastop_pos ]
fixedlines = ""
last_lineno = 0
for t in tkns :
    if last_lineno == t . start [ 0 ] :
        continue
    elif t . start [ 0 ] == fiedlineno :
        fixedlines += fixedline
        last_lineno = t . start [ 0 ]
    else :
        fixedlines += t . line
        last_lineno = t . start [ 0 ]
return fixedlines


signature:
def find_funcdef ( source ) :
    """Find the first FuncDef ast object in source"""

implementation:
try :
    module_node = compile ( source , "<string>" , mode = "exec" , flags = ast . PyCF_ONLY_AST )
except SyntaxError :
    return find_funcdef ( fix_lamdaline ( source ) )
for node in ast . walk ( module_node ) :
    if isinstance ( node , ast . FunctionDef ) or isinstance ( node , ast . Lambda ) :
        return node
raise ValueError ( "function definition not found" )


signature:
def extract_params ( source ) :
    """Extract parameters from a function definition"""

implementation:
funcdef = find_funcdef ( source )
params = [ ]
for node in ast . walk ( funcdef . args ) :
    if isinstance ( node , ast . arg ) :
        if node . arg not in params :
            params . append ( node . arg )
return params


signature:
def extract_names ( source ) :
    """Extract names from a function definition
 Looks for a function definition in the source .
 Only the first function definition is examined .
 Returns :
 a list names ( identifiers ) used in the body of the function
 excluding function parameters ."""

implementation:
if source is None :
    return None
source = dedent ( source )
funcdef = find_funcdef ( source )
params = extract_params ( source )
names = [ ]
if isinstance ( funcdef , ast . FunctionDef ) :
    stmts = funcdef . body
elif isinstance ( funcdef , ast . Lambda ) :
    stmts = [ funcdef . body ]
else :
    raise ValueError ( "must not happen" )
for stmt in stmts :
    for node in ast . walk ( stmt ) :
        if isinstance ( node , ast . Name ) :
            if node . id not in names and node . id not in params :
                names . append ( node . id )
return names


signature:
def is_funcdef ( src ) :
    """True if src is a function definition"""

implementation:
module_node = ast . parse ( dedent ( src ) )
if len ( module_node . body ) == 1 and isinstance ( module_node . body [ 0 ] , ast . FunctionDef ) :
    return True
else :
    return False