signature:
def tile ( ) :
    """Tiles open figures ."""

implementation:
figs = plt . get_fignums ( )
# Keep track of x , y , size for figures
x = 0
y = 0
# maxy = 0
toppad = 21
size = np . array ( [ 0 , 0 ] )
if ( len ( figs ) != 0 ) :
    fig = plt . figure ( figs [ 0 ] )
    screen = fig . canvas . window . get_screen ( )
    screenx = screen . get_monitor_geometry ( screen . get_primary_monitor ( ) )
    screenx = screenx [ 2 ]
    fig = plt . figure ( figs [ 0 ] )
    fig . canvas . manager . window . move ( x , y )
    maxy = np . array ( fig . canvas . manager . window . get_position ( ) ) [ 1 ]
    size = np . array ( fig . canvas . manager . window . get_size ( ) )
    y = maxy
    x += size [ 0 ] + 1
    for fig in figs [ 1 : ] :
        fig = plt . figure ( fig )
        size = np . array ( fig . canvas . manager . window . get_size ( ) )
        if ( x + size [ 0 ] > screenx ) :
            x = 0
            y = maxy
            maxy = y + size [ 1 ] + toppad
        else :
            maxy = max ( maxy , y + size [ 1 ] + toppad )
        fig . canvas . manager . window . move ( x , y )
        x += size [ 0 ] + 1


signature:
def linspaceborders ( array ) :
    """Generate a new array with numbers interpolated between the numbers of the input array . Extrapolates elements to the left and right sides to get the exterior border as well .
 Parameters
 array : : class : ` numpy . ndarray `
 The original array .
 Returns
 array : : class : ` numpy . ndarray `
 The interpolated / extrapolated array ."""

implementation:
# Get and set left side
dela = array [ 1 ] - array [ 0 ]
new_arr = _np . array ( [ array [ 0 ] - dela / 2 ] )
# Add a point to the right side so the for loop works
delb = array [ - 1 ] - array [ - 2 ]
array = _np . append ( array , array [ - 1 ] + delb )
for i , val in enumerate ( array ) :
    try :
        avg = ( array [ i ] + array [ i + 1 ] ) / 2
        new_arr = _np . append ( new_arr , avg )
    except :
        pass
# start = array [ 0 ] - dela / 2
# end = array [ - 1 ] + dela / 2
# return _ linspacestep ( start , end , dela )
return new_arr


signature:
def nb0 ( self ) :
    """On - axis beam density : math : ` n _ { b , 0 } ` ."""

implementation: return self . N_e / ( 4 * _np . sqrt ( 3 ) * _np . pi * self . sig_x * self . sig_y * self . sig_xi )


signature:
def k ( self ) :
    """Driving force term : : math : ` r ' ' = - k \\ left ( \\ frac { 1 - e ^ { - r ^ 2/2{ \\ sigma _ r } ^ 2 } } { r } \\ right ) `"""

implementation:
try :
    return self . _k
except AttributeError :
    self . _k = _np . sqrt ( _np . pi / 8 ) * e ** 2 * self . nb0 * self . sig_y / ( e0 * self . m * c ** 2 )
    return self . _k


signature:
def k_small ( self ) :
    """Small - angle driving force term : : math : ` r ' ' = - k _ { small } r ` .
 Note : : math : ` k _ { small } = \\ frac { k } { 2{ \\ sigma _ r ^ 2 } } `"""

implementation: return self . k * _np . sqrt ( 2 / _np . pi ) / self . sig_y


signature:
def update_time ( sender , ** kwargs ) :
    """When a Comment is added , updates the Update to set " last _ updated " time"""

implementation:
comment = kwargs [ 'instance' ]
if comment . content_type . app_label == "happenings" and comment . content_type . name == "Update" :
    from . models import Update
    item = Update . objects . get ( id = comment . object_pk )
    item . save ( )


signature:
def new_game ( self , mode = None ) :
    """new _ game ( ) creates a new game . Docs TBC .
 : return : JSON String containing the game object ."""

implementation:
# Create a placeholder Game object
self . _g = GameObject ( )
# Validate game mode
_mode = mode or "normal"
logging . debug ( "new_game: requesting mode {}" . format ( _mode ) )
mode_info = self . _g . get_game_type ( gametype = _mode )
logging . debug ( "mode_info: {} (Type: {})" . format ( mode_info , type ( mode_info ) ) )
if not mode_info :
    self . _g = None
    raise ValueError ( 'The mode passed ({}) is not supported.' . format ( _mode ) )
logging . debug ( "Creating a DigitWord (type {})" . format ( mode_info . digitType ) )
dw = DigitWord ( wordtype = mode_info . digitType )
dw . random ( mode_info . digits )
logging . debug ( "Randomized DigitWord. Value is {}." . format ( dw . word ) )
_game = { "key" : str ( uuid . uuid4 ( ) ) , "status" : "playing" , "ttl" : int ( time ( ) ) + 3600 , "answer" : dw . word , "mode" : _mode , "guesses_remaining" : mode_info . guesses_allowed , "guesses_made" : 0 }
logging . debug ( "Game being created: {}" . format ( _game ) )
self . _g . from_json ( jsonstr = json . dumps ( _game ) )
return self . _g . to_json ( )


signature:
def load_game ( self , jsonstr ) :
    """load _ game ( ) takes a JSON string representing a game object and calls the underlying
 game object ( _ g ) to load the JSON . The underlying object will handle schema validation
 and transformation .
 : param jsonstr : A valid JSON string representing a GameObject ( see above )
 : return : None"""

implementation:
logging . debug ( "load_game called." )
logging . debug ( "Creating empty GameObject." )
self . _g = GameObject ( )
logging . debug ( "Calling from_json with {}." . format ( jsonstr ) )
self . _g . from_json ( jsonstr = jsonstr )


signature:
def save_game ( self ) :
    """save _ game ( ) asks the underlying game object ( _ g ) to dump the contents of
 itself as JSON and then returns the JSON to
 : return : A JSON representation of the game object"""

implementation:
logging . debug ( "save_game called." )
logging . debug ( "Validating game object" )
self . _validate_game_object ( op = "save_game" )
logging . debug ( "Dumping JSON from GameObject" )
return self . _g . to_json ( )


signature:
def guess ( self , * args ) :
    """guess ( ) allows a guess to be made . Before the guess is made , the method
 checks to see if the game has been won , lost , or there are no tries
 remaining . It then creates a return object stating the number of bulls
 ( direct matches ) , cows ( indirect matches ) , an analysis of the guess ( a
 list of analysis objects ) , and a status .
 : param args : any number of integers ( or string representations of integers )
 to the number of Digits in the answer ; i . e . in normal mode , there would be
 a DigitWord to guess of 4 digits , so guess would expect guess ( 1 , 2 , 3 , 4)
 and a shorter ( guess ( 1 , 2 ) ) or longer ( guess ( 1 , 2 , 3 , 4 , 5 ) ) sequence will
 raise an exception .
 : return : a JSON object containing the analysis of the guess :
 " cows " : { " type " : " integer " } ,
 " bulls " : { " type " : " integer " } ,
 " analysis " : { " type " : " array of DigitWordAnalysis " } ,
 " status " : { " type " : " string " }"""

implementation:
logging . debug ( "guess called." )
logging . debug ( "Validating game object" )
self . _validate_game_object ( op = "guess" )
logging . debug ( "Building return object" )
_return_results = { "cows" : None , "bulls" : None , "analysis" : [ ] , "status" : "" }
logging . debug ( "Check if game already won, lost, or too many tries." )
if self . _g . status . lower ( ) == "won" :
    _return_results [ "message" ] = self . _start_again ( "You already won!" )
elif self . _g . status . lower ( ) == "lost" :
    _return_results [ "message" ] = self . _start_again ( "You have made too many guesses_allowed, you lost!" )
elif self . _g . guesses_remaining < 1 :
    _return_results [ "message" ] = self . _start_again ( "You have run out of tries, sorry!" )
elif self . _g . ttl < time ( ) :
    _return_results [ "message" ] = self . _start_again ( "Sorry, you ran out of time to complete the puzzle!" )
else :
    logging . debug ( "Creating a DigitWord for the guess." )
    _wordtype = DigitWord . HEXDIGIT if self . _g . mode . lower ( ) == 'hex' else DigitWord . DIGIT
    guess = DigitWord ( * args , wordtype = _wordtype )
    logging . debug ( "Validating guess." )
    self . _g . guesses_remaining -= 1
    self . _g . guesses_made += 1
    logging . debug ( "Initializing return object." )
    _return_results [ "analysis" ] = [ ]
    _return_results [ "cows" ] = 0
    _return_results [ "bulls" ] = 0
    logging . debug ( "Asking the underlying GameObject to compare itself to the guess." )
    for i in self . _g . answer . compare ( guess ) :
        logging . debug ( "Iteration of guesses_allowed. Processing guess {}" . format ( i . index ) )
        if i . match is True :
            logging . debug ( "Bull found. +1" )
            _return_results [ "bulls" ] += 1
        elif i . in_word is True :
            logging . debug ( "Cow found. +1" )
            _return_results [ "cows" ] += 1
        logging . debug ( "Add analysis to return object" )
        _return_results [ "analysis" ] . append ( i . get_object ( ) )
    logging . debug ( "Checking if game won or lost." )
    if _return_results [ "bulls" ] == len ( self . _g . answer . word ) :
        logging . debug ( "Game was won." )
        self . _g . status = "won"
        self . _g . guesses_remaining = 0
        _return_results [ "message" ] = "Well done! You won the game with your " "answers {}" . format ( self . _get_text_answer ( ) )
    elif self . _g . guesses_remaining < 1 :
        logging . debug ( "Game was lost." )
        self . _g . status = "lost"
        _return_results [ "message" ] = "Sorry, you lost! The correct answer was " "{}" . format ( self . _get_text_answer ( ) )
    _return_results [ "status" ] = self . _g . status
logging . debug ( "Returning results." )
return _return_results


signature:
def _start_again ( self , message = None ) :
    """Simple method to form a start again message and give the answer in readable form ."""

implementation:
logging . debug ( "Start again message delivered: {}" . format ( message ) )
the_answer = self . _get_text_answer ( )
return "{0} The correct answer was {1}. Please start a new game." . format ( message , the_answer )


signature:
def _validate_game_object ( self , op = "unknown" ) :
    """A helper method to provide validation of the game object ( _ g ) . If the
 game object does not exist or if ( for any reason ) the object is not a GameObject ,
 then an exception will be raised .
 : param op : A string describing the operation ( e . g . guess , save , etc . ) taking place
 : return : Nothing"""

implementation:
if self . _g is None :
    raise ValueError ( "Game must be instantiated properly before using - call new_game() " "or load_game(jsonstr='{...}')" )
if not isinstance ( self . _g , GameObject ) :
    raise TypeError ( "Unexpected error during {0}! GameObject (_g) is not a GameObject!" . format ( op ) )


signature:
def extra_context ( request ) :
    """Adds useful global items to the context for use in templates .
 * * request * : the request object
 * * HOST * : host name of server
 * * IN _ ADMIN * : True if you are in the django admin area"""

implementation:
host = os . environ . get ( 'DJANGO_LIVE_TEST_SERVER_ADDRESS' , None ) or request . get_host ( )
d = { 'request' : request , 'HOST' : host , 'IN_ADMIN' : request . path . startswith ( '/admin/' ) , }
return d


signature:
def fft ( values , freq = None , timestamps = None , fill_missing = False ) :
    """Adds options to : func : ` scipy . fftpack . rfft ` :
 * * freq * is the frequency the samples were taken at
 * * timestamps * is the time the samples were taken , to help with filling in missing data if * fill _ missing * is true"""

implementation:
# Get frequency
if freq is None :
    from . . import qt
    freq = qt . getDouble ( title = 'Fourier Analysis' , text = 'Frequency samples taken at:' , min = 0 , decimals = 2 , value = 1.0 )
    freq = freq . input
if fill_missing :
    ( t_x , x_filled ) = fill_missing_timestamps ( timestamps , values )
else :
    x_filled = values
num_samples = _np . size ( x_filled )
xfft = _sp . fftpack . rfft ( x_filled )
factor = freq / num_samples
num_fft = _np . size ( xfft )
f = factor * _np . linspace ( 1 , num_fft , num_fft )
xpow = _np . abs ( xfft * _np . conj ( xfft ) )
# No DC term
xpow = xpow [ 1 : ]
f = f [ 1 : ]
return ( f , xpow )


signature:
def create ( self , server ) :
    """Create the challenge on the server"""

implementation: return server . post ( 'challenge_admin' , self . as_payload ( ) , replacements = { 'slug' : self . slug } )


signature:
def update ( self , server ) :
    """Update existing challenge on the server"""

implementation: return server . put ( 'challenge_admin' , self . as_payload ( ) , replacements = { 'slug' : self . slug } )


signature:
def exists ( self , server ) :
    """Check if a challenge exists on the server"""

implementation:
try :
    server . get ( 'challenge' , replacements = { 'slug' : self . slug } )
except Exception :
    return False
return True


signature:
def from_server ( cls , server , slug ) :
    """Retrieve a challenge from the MapRoulette server
 : type server"""

implementation:
challenge = server . get ( 'challenge' , replacements = { 'slug' : slug } )
return cls ( ** challenge )


signature:
def django_logging_dict ( log_dir , handlers = [ 'file' ] , filename = 'debug.log' ) :
    """Extends : func : ` logthing . utils . default _ logging _ dict ` with django
 specific values ."""

implementation:
d = default_logging_dict ( log_dir , handlers , filename )
d [ 'handlers' ] . update ( { 'mail_admins' : { 'level' : 'ERROR' , 'class' : 'django.utils.log.AdminEmailHandler' , } } )
d [ 'loggers' ] . update ( { 'django.db.backends' : { # stop SQL debug from going to main logger
'handlers' : [ 'file' , 'mail_admins' ] , 'level' : 'ERROR' , 'propagate' : False , } , 'django.request' : { 'handlers' : [ 'file' , 'mail_admins' ] , 'level' : 'ERROR' , 'propagate' : False , } , } )
return d


signature:
def get_position ( self , position_id ) :
    """Returns position data .
 http : / / dev . wheniwork . com / # get - existing - position"""

implementation:
url = "/2/positions/%s" % position_id
return self . position_from_json ( self . _get_resource ( url ) [ "position" ] )


signature:
def get_positions ( self ) :
    """Returns a list of positions .
 http : / / dev . wheniwork . com / # listing - positions"""

implementation:
url = "/2/positions"
data = self . _get_resource ( url )
positions = [ ]
for entry in data [ 'positions' ] :
    positions . append ( self . position_from_json ( entry ) )
return positions


signature:
def create_position ( self , params = { } ) :
    """Creates a position
 http : / / dev . wheniwork . com / # create - update - position"""

implementation:
url = "/2/positions/"
body = params
data = self . _post_resource ( url , body )
return self . position_from_json ( data [ "position" ] )


signature:
def print2elog ( author = '' , title = '' , text = '' , link = None , file = None , now = None ) :
    """Prints to the elog .
 Parameters
 author : str , optional
 Author of the elog .
 title : str , optional
 Title of the elog .
 link : str , optional
 Path to a thumbnail .
 file : str , optional
 Path to a file .
 now : : class : ` datetime . datetime `
 Time of the elog ."""

implementation:
# Get current time
if now is None :
    now = _dt . datetime . now ( )
fulltime = now . strftime ( '%Y-%m-%dT%H:%M:%S-00' )
# Copy files
if not ( ( link is None ) ^ ( file is None ) ) :
    link_copied = _copy_file ( link , fulltime )
    file_copied = _copy_file ( file , fulltime )
else :
    raise ValueError ( 'Need both file and its thumbnail!' )
# Jinja templating
loader = _jj . PackageLoader ( 'pytools.facettools' , 'resources/templates' )
env = _jj . Environment ( loader = loader , trim_blocks = True )
template = env . get_template ( 'facetelog.xml' )
stream = template . stream ( author = author , title = title , text = text , link = link_copied , file = file_copied , now = now )
# Write xml
with _tempfile . TemporaryDirectory ( ) as dirname :
    filename = '{}.xml' . format ( fulltime )
    filepath = _os . path . join ( dirname , filename )
    with open ( filepath , 'w+' ) as fid : # stream . disable _ buffering ( )
        stream . dump ( fid )
    finalpath = _os . path . join ( basedir , filename )
    # _ shutil . copyfile ( filepath , ' new . xml ' )
    _shutil . copyfile ( filepath , finalpath )


signature:
def fopen ( name , mode = 'r' , buffering = - 1 ) :
    """Similar to Python ' s built - in ` open ( ) ` function ."""

implementation:
f = _fopen ( name , mode , buffering )
return _FileObjectThreadWithContext ( f , mode , buffering )


signature:
def sloccount ( ) :
    '''Print " Source Lines of Code " and export to file .
 Export is hudson _ plugin _ compatible : sloccount . sc
 requirements :
 - sloccount _ should be installed .
 - tee and pipes are used
 options . paved . pycheck . sloccount . param
 . . _ sloccount : http : / / www . dwheeler . com / sloccount /
 . . _ hudson : http : / / hudson - ci . org /
 . . _ plugin : http : / / wiki . hudson - ci . org / display / HUDSON / SLOCCount + Plugin'''

implementation:
# filter out subpackages
setup = options . get ( 'setup' )
packages = options . get ( 'packages' ) if setup else None
if packages :
    dirs = [ x for x in packages if '.' not in x ]
else :
    dirs = [ '.' ]
# sloccount has strange behaviour with directories ,
# can cause exception in hudson sloccount plugin .
# Better to call it with file list
ls = [ ]
for d in dirs :
    ls += list ( path ( d ) . walkfiles ( ) )
# ls = list ( set ( ls ) )
files = ' ' . join ( ls )
param = options . paved . pycheck . sloccount . param
sh ( 'sloccount {param} {files} | tee sloccount.sc' . format ( param = param , files = files ) )


signature:
def pyflakes ( ) :
    '''passive check of python programs by pyflakes .
 requirements :
 - pyflakes _ should be installed . ` ` easy _ install pyflakes ` `
 options . paved . pycheck . pyflakes . param
 . . _ pyflakes : http : / / pypi . python . org / pypi / pyflakes'''

implementation:
# filter out subpackages
packages = [ x for x in options . setup . packages if '.' not in x ]
sh ( 'pyflakes {param} {files}' . format ( param = options . paved . pycheck . pyflakes . param , files = ' ' . join ( packages ) ) )


signature:
def gaussian ( x , mu , sigma ) :
    """Gaussian function of the form : math : ` \\ frac { 1 } { \\ sqrt { 2 \\ pi } \\ sigma } e ^ { - \\ frac { ( x - \\ mu ) ^ 2 } { 2 \\ sigma ^ 2 } } ` .
 . . versionadded : : 1.5
 Parameters
 x : float
 Function variable : math : ` x ` .
 mu : float
 Mean of the Gaussian function .
 sigma : float
 Standard deviation of the Gaussian function ."""

implementation: return _np . exp ( - ( x - mu ) ** 2 / ( 2 * sigma ** 2 ) ) / ( _np . sqrt ( 2 * _np . pi ) * sigma )


signature:
def http_exception_error_handler ( exception ) :
    """Handle HTTP exception
 : param werkzeug . exceptions . HTTPException exception : Raised exception
 A response is returned , as formatted by the : py : func : ` response ` function ."""

implementation:
assert issubclass ( type ( exception ) , HTTPException ) , type ( exception )
assert hasattr ( exception , "code" )
assert hasattr ( exception , "description" )
return response ( exception . code , exception . description )


signature:
def is_colour ( value ) :
    """Returns True if the value given is a valid CSS colour , i . e . matches one
 of the regular expressions in the module or is in the list of
 predetefined values by the browser ."""

implementation:
global PREDEFINED , HEX_MATCH , RGB_MATCH , RGBA_MATCH , HSL_MATCH , HSLA_MATCH
value = value . strip ( )
# hex match
if HEX_MATCH . match ( value ) or RGB_MATCH . match ( value ) or RGBA_MATCH . match ( value ) or HSL_MATCH . match ( value ) or HSLA_MATCH . match ( value ) or value in PREDEFINED :
    return True
return False


signature:
def format_time ( seconds ) :
    """Formats time as the string " HH : MM : SS " ."""

implementation:
timedelta = datetime . timedelta ( seconds = int ( seconds ) )
mm , ss = divmod ( timedelta . seconds , 60 )
if mm < 60 :
    return "%02d:%02d" % ( mm , ss )
hh , mm = divmod ( mm , 60 )
if hh < 24 :
    return "%02d:%02d:%02d" % ( hh , mm , ss )
dd , hh = divmod ( mm , 24 )
return "%d days %02d:%02d:%02d" % ( dd , hh , mm , ss )


signature:
def frictional_resistance_coef ( length , speed , ** kwargs ) :
    """Flat plate frictional resistance of the ship according to ITTC formula .
 ref : https : / / ittc . info / media / 2021/75-02-02-02 . pdf
 : param length : metres length of the vehicle
 : param speed : m / s speed of the vehicle
 : param kwargs : optional could take in temperature to take account change of water property
 : return : Frictional resistance coefficient of the vehicle"""

implementation:
Cf = 0.075 / ( np . log10 ( reynolds_number ( length , speed , ** kwargs ) ) - 2 ) ** 2
return Cf


signature:
def reynolds_number ( length , speed , temperature = 25 ) :
    """Reynold number utility function that return Reynold number for vehicle at specific length and speed .
 Optionally , it can also take account of temperature effect of sea water .
 Kinematic viscosity from : http : / / web . mit . edu / seawater / 2017 _ MIT _ Seawater _ Property _ Tables _ r2 . pdf
 : param length : metres length of the vehicle
 : param speed : m / s speed of the vehicle
 : param temperature : degree C
 : return : Reynolds number of the vehicle ( dimensionless )"""

implementation:
kinematic_viscosity = interpolate . interp1d ( [ 0 , 10 , 20 , 25 , 30 , 40 ] , np . array ( [ 18.54 , 13.60 , 10.50 , 9.37 , 8.42 , 6.95 ] ) / 10 ** 7 )
# Data from http : / / web . mit . edu / seawater / 2017 _ MIT _ Seawater _ Property _ Tables _ r2 . pdf
Re = length * speed / kinematic_viscosity ( temperature )
return Re


signature:
def froude_number ( speed , length ) :
    """Froude number utility function that return Froude number for vehicle at specific length and speed .
 : param speed : m / s speed of the vehicle
 : param length : metres length of the vehicle
 : return : Froude number of the vehicle ( dimensionless )"""

implementation:
g = 9.80665
# conventional standard value m / s ^ 2
Fr = speed / np . sqrt ( g * length )
return Fr


signature:
def residual_resistance_coef ( slenderness , prismatic_coef , froude_number ) :
    """Residual resistance coefficient estimation from slenderness function , prismatic coefficient and Froude number .
 : param slenderness : Slenderness coefficient dimensionless : math : ` L / ( ∇ ^ { 1/3 } ) ` where L is length of ship , ∇ is displacement
 : param prismatic _ coef : Prismatic coefficient dimensionless : math : ` ∇ / ( L \ cdot A _ m ) ` where L is length of ship , ∇ is displacement Am is midsection area of the ship
 : param froude _ number : Froude number of the ship dimensionless
 : return : Residual resistance of the ship"""

implementation:
Cr = cr ( slenderness , prismatic_coef , froude_number )
if math . isnan ( Cr ) :
    Cr = cr_nearest ( slenderness , prismatic_coef , froude_number )
# if Froude number is out of interpolation range , nearest extrapolation is used
return Cr


signature:
def dimension ( self , length , draught , beam , speed , slenderness_coefficient , prismatic_coefficient ) :
    """Assign values for the main dimension of a ship .
 : param length : metres length of the vehicle
 : param draught : metres draught of the vehicle
 : param beam : metres beam of the vehicle
 : param speed : m / s speed of the vehicle
 : param slenderness _ coefficient : Slenderness coefficient dimensionless : math : ` L / ( ∇ ^ { 1/3 } ) ` where L is length of ship ,
 ∇ is displacement
 : param prismatic _ coefficient : Prismatic coefficient dimensionless : math : ` ∇ / ( L \ cdot A _ m ) ` where L is length of ship ,
 ∇ is displacement Am is midsection area of the ship"""

implementation:
self . length = length
self . draught = draught
self . beam = beam
self . speed = speed
self . slenderness_coefficient = slenderness_coefficient
self . prismatic_coefficient = prismatic_coefficient
self . displacement = ( self . length / self . slenderness_coefficient ) ** 3
self . surface_area = 1.025 * ( 1.7 * self . length * self . draught + self . displacement / self . draught )


signature:
def resistance ( self ) :
    """Return resistance of the vehicle .
 : return : newton the resistance of the ship"""

implementation:
self . total_resistance_coef = frictional_resistance_coef ( self . length , self . speed ) + residual_resistance_coef ( self . slenderness_coefficient , self . prismatic_coefficient , froude_number ( self . speed , self . length ) )
RT = 1 / 2 * self . total_resistance_coef * 1025 * self . surface_area * self . speed ** 2
return RT


signature:
def maximum_deck_area ( self , water_plane_coef = 0.88 ) :
    """Return the maximum deck area of the ship
 : param water _ plane _ coef : optional water plane coefficient
 : return : Area of the deck"""

implementation:
AD = self . beam * self . length * water_plane_coef
return AD


signature:
def prop_power ( self , propulsion_eff = 0.7 , sea_margin = 0.2 ) :
    """Total propulsion power of the ship .
 : param propulsion _ eff : Shaft efficiency of the ship
 : param sea _ margin : Sea margin take account of interaction between ship and the sea , e . g . wave
 : return : Watts shaft propulsion power of the ship"""

implementation:
PP = ( 1 + sea_margin ) * self . resistance ( ) * self . speed / propulsion_eff
return PP


signature:
def axesfontsize ( ax , fontsize ) :
    """Change the font size for the title , x and y labels , and x and y tick labels for axis * ax * to * fontsize * ."""

implementation:
items = ( [ ax . title , ax . xaxis . label , ax . yaxis . label ] + ax . get_xticklabels ( ) + ax . get_yticklabels ( ) )
for item in items :
    item . set_fontsize ( fontsize )


signature:
def less_labels ( ax , x_fraction = 0.5 , y_fraction = 0.5 ) :
    """Scale the number of tick labels in x and y by * x _ fraction * and * y _ fraction * respectively ."""

implementation:
nbins = _np . size ( ax . get_xticklabels ( ) )
ax . locator_params ( nbins = _np . floor ( nbins * x_fraction ) , axis = 'x' )
nbins = _np . size ( ax . get_yticklabels ( ) )
ax . locator_params ( nbins = _np . floor ( nbins * y_fraction ) , axis = 'y' )


signature:
def configure ( self , url = None , token = None , test = False ) :
    """Configure the api to use given url and token or to get them from the
 Config ."""

implementation:
if url is None :
    url = Config . get_value ( "url" )
if token is None :
    token = Config . get_value ( "token" )
self . server_url = url
self . auth_header = { "Authorization" : "Basic {0}" . format ( token ) }
self . configured = True
if test :
    self . test_connection ( )
Config . set ( "url" , url )
Config . set ( "token" , token )


signature:
def send_zip ( self , exercise , file , params ) :
    """Send zipfile to TMC for given exercise"""

implementation:
resp = self . post ( exercise . return_url , params = params , files = { "submission[file]" : ( 'submission.zip' , file ) } , data = { "commit" : "Submit" } )
return self . _to_json ( resp )


signature:
def _make_url ( self , slug ) :
    """Ensures that the request url is valid .
 Sometimes we have URLs that the server gives that are preformatted ,
 sometimes we need to form our own ."""

implementation:
if slug . startswith ( "http" ) :
    return slug
return "{0}{1}" . format ( self . server_url , slug )


signature:
def _do_request ( self , method , slug , ** kwargs ) :
    """Does HTTP request sending / response validation .
 Prevents RequestExceptions from propagating"""

implementation:
# ensure we are configured
if not self . configured :
    self . configure ( )
url = self . _make_url ( slug )
# ' defaults ' are values associated with every request .
# following will make values in kwargs override them .
defaults = { "headers" : self . auth_header , "params" : self . params }
for item in defaults . keys ( ) : # override default ' s value with kwargs ' s one if existing .
    kwargs [ item ] = dict ( defaults [ item ] , ** ( kwargs . get ( item , { } ) ) )
# request ( ) can raise connectivity related exceptions .
# raise _ for _ status raises an exception ONLY if the response
# status _ code is " not - OK " i . e 4XX , 5XX . .
# All of these inherit from RequestException
# which is " translated " into an APIError .
try :
    resp = request ( method , url , ** kwargs )
    resp . raise_for_status ( )
except RequestException as e :
    reason = "HTTP {0} request to {1} failed: {2}"
    raise APIError ( reason . format ( method , url , repr ( e ) ) )
return resp


signature:
def _to_json ( self , resp ) :
    """Extract json from a response .
 Assumes response is valid otherwise .
 Internal use only ."""

implementation:
try :
    json = resp . json ( )
except ValueError as e :
    reason = "TMC Server did not send valid JSON: {0}"
    raise APIError ( reason . format ( repr ( e ) ) )
return json


signature:
def _normalize_instancemethod ( instance_method ) :
    """wraps ( instancemethod ) returns a function , not an instancemethod so its repr ( ) is all messed up ;
 we want the original repr to show up in the logs , therefore we do this trick"""

implementation:
if not hasattr ( instance_method , 'im_self' ) :
    return instance_method
def _func ( * args , ** kwargs ) :
    return instance_method ( * args , ** kwargs )
_func . __name__ = repr ( instance_method )
return _func


signature:
def safe_joinall ( greenlets , timeout = None , raise_error = False ) :
    """Wrapper for gevent . joinall if the greenlet that waits for the joins is killed , it kills all the greenlets it
 joins for ."""

implementation:
greenlets = list ( greenlets )
try :
    gevent . joinall ( greenlets , timeout = timeout , raise_error = raise_error )
except gevent . GreenletExit :
    [ greenlet . kill ( ) for greenlet in greenlets if not greenlet . ready ( ) ]
    raise
return greenlets


signature:
def imshow_batch ( images , cbar = True , show = True , pdf = None , figsize = ( 16 , 12 ) , rows = 2 , columns = 2 , cmap = None , ** kwargs ) :
    """Plots an array of * images * to a single window of size * figsize * with * rows * and * columns * .
 * * cmap * : Specifies color map
 * * cbar * : Add color bars
 * * show * : If false , dismisses each window after it is created and optionally saved
 * * pdf * : Save to a pdf of filename * pdf *
 * * \ * \ * kwargs * passed to : class : ` matplotlib . axis . imshow `"""

implementation:
# Set up grid
images = _np . array ( images )
gs = _gridspec . GridSpec ( rows , columns )
num_imgs = images . shape [ 0 ]
max_ind = num_imgs - 1
# Split into pages
per_page = rows * columns
num_pages = _np . int ( _np . ceil ( num_imgs / per_page ) )
fig_array = _np . empty ( shape = num_pages , dtype = object )
if num_pages > 1 :
    logger . info ( 'Multiple pages necessary' )
if pdf is not None :
    f = _PdfPages ( pdf )
for p in range ( num_pages ) : # Make figure
    fig_array [ p ] = _plt . figure ( figsize = figsize )
    # Get number of rows on page
    pg_max_ind = _np . min ( [ ( p + 1 ) * per_page - 1 , max_ind ] )
    num_rows = _np . int ( _np . ceil ( ( pg_max_ind + 1 - p * per_page ) / columns ) )
    for i in range ( num_rows ) : # Get images for column
        i_min_ind = p * per_page + i * columns
        col_max_ind = _np . min ( [ i_min_ind + columns - 1 , max_ind ] )
        for j , image in enumerate ( images [ i_min_ind : col_max_ind + 1 ] ) :
            ax = fig_array [ p ] . add_subplot ( gs [ i , j ] )
            try :
                if _np . issubdtype ( image . dtype , _np . integer ) :
                    image = _np . array ( image , dtype = float )
            except :
                pass
            plot = ax . imshow ( image , ** kwargs )
            if cmap is not None :
                plot . set_cmap ( cmap )
            if cbar :
                fig_array [ p ] . colorbar ( plot )
    fig_array [ p ] . tight_layout ( )
    if pdf is not None :
        f . savefig ( fig_array [ p ] )
    if not show :
        _plt . close ( fig_array [ p ] )
if pdf is not None :
    f . close ( )
return fig_array


signature:
def error ( code : int , * args , ** kwargs ) -> HedgehogCommandError :
    """Creates an error from the given code , and args and kwargs .
 : param code : The acknowledgement code
 : param args : Exception args
 : param kwargs : Exception kwargs
 : return : the error for the given acknowledgement code"""

implementation:
# TODO add proper error code
if code == FAILED_COMMAND and len ( args ) >= 1 and args [ 0 ] == "Emergency Shutdown activated" :
    return EmergencyShutdown ( * args , ** kwargs )
return _errors [ code ] ( * args , ** kwargs )


signature:
def to_message ( self ) :
    """Creates an error Acknowledgement message .
 The message ' s code and message are taken from this exception .
 : return : the message representing this exception"""

implementation:
from . messages import ack
return ack . Acknowledgement ( self . code , self . args [ 0 ] if len ( self . args ) > 0 else '' )


signature:
def clean ( options , info ) :
    """Clean up extra files littering the source tree .
 options . paved . clean . dirs : directories to search recursively
 options . paved . clean . patterns : patterns to search for and remove"""

implementation:
info ( "Cleaning patterns %s" , options . paved . clean . patterns )
for wd in options . paved . clean . dirs :
    info ( "Cleaning in %s" , wd )
    for p in options . paved . clean . patterns :
        for f in wd . walkfiles ( p ) :
            f . remove ( )


signature:
def printoptions ( ) :
    '''print paver options .
 Prettified by json .
 ` long _ description ` is removed'''

implementation:
x = json . dumps ( environment . options , indent = 4 , sort_keys = True , skipkeys = True , cls = MyEncoder )
print ( x )


signature:
def parse ( self , data : RawMessage ) -> Message :
    """Parses a binary protobuf message into a Message object ."""

implementation:
try :
    return self . receiver . parse ( data )
except KeyError as err :
    raise UnknownCommandError from err
except DecodeError as err :
    raise UnknownCommandError ( f"{err}" ) from err


signature:
def setup_axes ( rows = 1 , cols = 1 , figsize = ( 8 , 6 ) , expand = True , tight_layout = None , ** kwargs ) :
    """Sets up a figure of size * figsize * with a number of rows ( * rows * ) and columns ( * cols * ) . \ * \ * kwargs passed through to : meth : ` matplotlib . figure . Figure . add _ subplot ` .
 . . versionadded : : 1.2
 Parameters
 rows : int
 Number of rows to create .
 cols : int
 Number of columns to create .
 figsize : tuple
 Size of figure to create .
 expand : bool
 Make the entire figure with size ` figsize ` .
 Returns
 fig : : class : ` matplotlib . figure . Figure `
 The figure .
 axes : : class : ` numpy . ndarray `
 An array of all of the axes . ( Unless there ' s only one axis , in which case it returns an object instance : class : ` matplotlib . axis . Axis ` . )"""

implementation:
if expand :
    figsize = ( figsize [ 0 ] * cols , figsize [ 1 ] * rows )
figargs = { }
if isinstance ( tight_layout , dict ) :
    figargs [ "tight_layout" ] = tight_layout
elif tight_layout == "pdf" :
    figargs [ "tight_layout" ] = { "rect" : ( 0 , 0 , 1 , 0.95 ) }
dpi = kwargs . pop ( 'dpi' , None )
fig , gs = _setup_figure ( rows = rows , cols = cols , figsize = figsize , dpi = dpi , ** figargs )
axes = _np . empty ( shape = ( rows , cols ) , dtype = object )
for i in range ( rows ) :
    for j in range ( cols ) :
        axes [ i , j ] = fig . add_subplot ( gs [ i , j ] , ** kwargs )
if axes . shape == ( 1 , 1 ) :
    return fig , axes [ 0 , 0 ]
else :
    return fig , axes


signature:
def factory ( cls , data_class , ** kwargs ) :
    """Creates a ` ` DCCGraph ` ` , a root : class : ` Node ` : and the node ' s
 associated data class instance . This factory is used to get around
 the chicken - and - egg problem of the ` ` DCCGraph ` ` and ` ` Nodes ` ` within
 it having pointers to each other .
 : param data _ class :
 django model class that extends : class : ` BaseNodeData ` and is used
 to associate information with the nodes in this graph
 : param kwargs :
 arguments to pass to constructor of the data class instance that
 is to be created for the root node
 : returns :
 instance of the newly created ` ` DCCGraph ` `"""

implementation:
if not issubclass ( data_class , BaseNodeData ) :
    raise AttributeError ( 'data_class must be a BaseNodeData extender' )
content_type = ContentType . objects . get_for_model ( data_class )
graph = DCCGraph . objects . create ( data_content_type = content_type )
node = Node . objects . create ( graph = graph )
data_class . objects . create ( node = node , ** kwargs )
graph . root = node
graph . save ( )
return graph


signature:
def factory_from_graph ( cls , data_class , root_args , children ) :
    """Creates a ` ` DCCGraph ` ` and corresponding nodes . The root _ args parm
 is a dictionary specifying the parameters for creating a : class : ` Node `
 and its corresponding : class : ` BaseNodeData ` subclass from the
 data _ class specified . The children parm is an iterable containing
 pairs of dictionaries and iterables , where the dictionaries specify
 the parameters for a : class : ` BaseNodeData ` subclass and the iterable
 the list of children .
 Example : :
 DCCGraph . factory _ from _ graph ( Label ,
 { ' name ' : ' A ' } , [
 ( { ' name ' : ' B ' , [ ] ) ,
 ( { ' name ' : ' C ' , [ ] )
 creates the graph : :
 / B C
 : param data _ class :
 django model class that extends : class : ` BaseNodeData ` and is used
 to associate information with the Nodes in this graph
 : param root _ args :
 dictionary of arguments to pass to constructor of the data class
 instance that is to be created for the root node
 : param children :
 iterable with a list of dictionary and iterable pairs
 : returns :
 instance of the newly created ` ` DCCGraph ` `"""

implementation:
graph = cls . factory ( data_class , ** root_args )
for child in children :
    cls . _depth_create ( graph . root , child [ 0 ] , child [ 1 ] )
return graph


signature:
def find_nodes ( self , ** kwargs ) :
    """Searches the data nodes that are associated with this graph using
 the key word arguments as a filter and returns a
 : class : ` django . db . models . query . QuerySet ` ` of the attached
 : class : ` Node ` objects .
 : param kwargs :
 filter arguments applied to searching the : class : ` BaseNodeData `
 subclass associated with this graph .
 : returns :
 ` ` QuerySet ` ` of : class : ` Node ` objects"""

implementation:
filter_args = { }
classname = self . data_content_type . model_class ( ) . __name__ . lower ( )
for key , value in kwargs . items ( ) :
    filter_args [ '%s__%s' % ( classname , key ) ] = value
return Node . objects . filter ( ** filter_args )


signature:
def add_child ( self , ** kwargs ) :
    """Creates a new ` ` Node ` ` based on the extending class and adds it as
 a child to this ` ` Node ` ` .
 : param kwargs :
 arguments for constructing the data object associated with this
 ` ` Node ` `
 : returns :
 extender of the ` ` Node ` ` class"""

implementation:
data_class = self . graph . data_content_type . model_class ( )
node = Node . objects . create ( graph = self . graph )
data_class . objects . create ( node = node , ** kwargs )
node . parents . add ( self )
self . children . add ( node )
return node


signature:
def connect_child ( self , node ) :
    """Adds the given node as a child to this one . No new nodes are
 created , only connections are made .
 : param node :
 a ` ` Node ` ` object to connect"""

implementation:
if node . graph != self . graph :
    raise AttributeError ( 'cannot connect nodes from different graphs' )
node . parents . add ( self )
self . children . add ( node )


signature:
def ancestors ( self ) :
    """Returns a list of the ancestors of this node ."""

implementation:
ancestors = set ( [ ] )
self . _depth_ascend ( self , ancestors )
try :
    ancestors . remove ( self )
except KeyError : # we weren ' t ancestor of ourself , that ' s ok
    pass
return list ( ancestors )


signature:
def ancestors_root ( self ) :
    """Returns a list of the ancestors of this node but does not pass the
 root node , even if the root has parents due to cycles ."""

implementation:
if self . is_root ( ) :
    return [ ]
ancestors = set ( [ ] )
self . _depth_ascend ( self , ancestors , True )
try :
    ancestors . remove ( self )
except KeyError : # we weren ' t ancestor of ourself , that ' s ok
    pass
return list ( ancestors )


signature:
def descendents ( self ) :
    """Returns a list of descendents of this node ."""

implementation:
visited = set ( [ ] )
self . _depth_descend ( self , visited )
try :
    visited . remove ( self )
except KeyError : # we weren ' t descendent of ourself , that ' s ok
    pass
return list ( visited )


signature:
def descendents_root ( self ) :
    """Returns a list of descendents of this node , if the root node is in
 the list ( due to a cycle ) it will be included but will not pass
 through it ."""

implementation:
visited = set ( [ ] )
self . _depth_descend ( self , visited , True )
try :
    visited . remove ( self )
except KeyError : # we weren ' t descendent of ourself , that ' s ok
    pass
return list ( visited )


signature:
def can_remove ( self ) :
    """Returns True if it is legal to remove this node and still leave the
 graph as a single connected entity , not splitting it into a forest .
 Only nodes with no children or those who cause a cycle can be deleted ."""

implementation:
if self . children . count ( ) == 0 :
    return True
ancestors = set ( self . ancestors_root ( ) )
children = set ( self . children . all ( ) )
return children . issubset ( ancestors )


signature:
def remove ( self ) :
    """Removes the node from the graph . Note this does not remove the
 associated data object . See : func : ` Node . can _ remove ` for limitations
 on what can be deleted .
 : returns :
 : class : ` BaseNodeData ` subclass associated with the deleted Node
 : raises AttributeError :
 if called on a ` ` Node ` ` that cannot be deleted"""

implementation:
if not self . can_remove ( ) :
    raise AttributeError ( 'this node cannot be deleted' )
data = self . data
self . parents . remove ( self )
self . delete ( )
return data


signature:
def prune ( self ) :
    """Removes the node and all descendents without looping back past the
 root . Note this does not remove the associated data objects .
 : returns :
 list of : class : ` BaseDataNode ` subclassers associated with the
 removed ` ` Node ` ` objects ."""

implementation:
targets = self . descendents_root ( )
try :
    targets . remove ( self . graph . root )
except ValueError : # root wasn ' t in the target list , no problem
    pass
results = [ n . data for n in targets ]
results . append ( self . data )
for node in targets :
    node . delete ( )
for parent in self . parents . all ( ) :
    parent . children . remove ( self )
self . delete ( )
return results


signature:
def prune_list ( self ) :
    """Returns a list of nodes that would be removed if prune were called
 on this element ."""

implementation:
targets = self . descendents_root ( )
try :
    targets . remove ( self . graph . root )
except ValueError : # root wasn ' t in the target list , no problem
    pass
targets . append ( self )
return targets


signature:
def _child_allowed ( self , child_rule ) :
    """Called to verify that the given rule can become a child of the
 current node .
 : raises AttributeError :
 if the child is not allowed"""

implementation:
num_kids = self . node . children . count ( )
num_kids_allowed = len ( self . rule . children )
if not self . rule . multiple_paths :
    num_kids_allowed = 1
if num_kids >= num_kids_allowed :
    raise AttributeError ( 'Rule %s only allows %s children' % ( self . rule_name , self . num_kids_allowed ) )
# verify not a duplicate
for node in self . node . children . all ( ) :
    if node . data . rule_label == child_rule . class_label :
        raise AttributeError ( 'Child rule already exists' )
# check if the given rule is allowed as a child
if child_rule not in self . rule . children :
    raise AttributeError ( 'Rule %s is not a valid child of Rule %s' % ( child_rule . __name__ , self . rule_name ) )


signature:
def add_child_rule ( self , child_rule ) :
    """Add a child path in the : class : ` Flow ` graph using the given
 : class : ` Rule ` subclass . This will create a new child : class : ` Node ` in
 the associated : class : ` Flow ` object ' s state graph with a new
 : class : ` FlowNodeData ` instance attached .
 The : class : ` Rule ` must be allowed at this stage of the flow according
 to the hierarchy of rules .
 : param child _ rule :
 : class : ` Rule ` class to add to the flow as a child of : class : ` Node `
 that this object owns
 : returns :
 ` ` FlowNodeData ` ` that was added"""

implementation:
self . _child_allowed ( child_rule )
child_node = self . node . add_child ( rule_label = child_rule . class_label )
return child_node . data


signature:
def connect_child ( self , child_node ) :
    """Adds a connection to an existing rule in the : class ` Flow ` graph .
 The given : class ` Rule ` subclass must be allowed to be connected at
 this stage of the flow according to the hierarchy of rules .
 : param child _ node :
 ` ` FlowNodeData ` ` to attach as a child"""

implementation:
self . _child_allowed ( child_node . rule )
self . node . connect_child ( child_node . node )


signature:
def in_use ( self ) :
    """Returns True if there is a : class : ` State ` object that uses this
 ` ` Flow ` `"""

implementation:
state = State . objects . filter ( flow = self ) . first ( )
return bool ( state )


signature:
def start ( self , flow ) :
    """Factory method for a running state based on a flow . Creates and
 returns a ` ` State ` ` object and calls the associated
 : func : ` Rule . on _ enter ` method .
 : param flow :
 : class : ` Flow ` which defines this state machine
 : returns :
 newly created instance"""

implementation:
state = State . objects . create ( flow = flow , current_node = flow . state_graph . root )
flow . state_graph . root . data . rule . on_enter ( state )
return state


signature:
def next_state ( self , rule = None ) :
    """Proceeds to the next step in the flow . Calls the associated
 : func : ` Rule . on _ leave ` method for the for the current rule and the
 : func : ` Rule . on _ enter ` for the rule being entered . If the current step
 in the flow is multipath then a valid : class : ` Rule ` subclass must be
 passed into this call .
 If there is only one possible path in the flow and a : class : ` Rule ` is
 given it will be ignored .
 : param rule :
 if the current : class : ` Rule ` in the : class : ` Flow ` is multipath
 then the next : class : ` Rule ` in the flow must be provided ."""

implementation:
num_kids = self . current_node . children . count ( )
next_node = None
if num_kids == 0 :
    raise AttributeError ( 'No next state in this Flow id=%s' % ( self . flow . id ) )
elif num_kids == 1 :
    next_node = self . current_node . children . first ( )
else :
    if not rule :
        raise AttributeError ( ( 'Current Rule %s is multipath but no ' 'choice was passed in' ) % self . current_node . data . rule_name )
    for node in self . current_node . children . all ( ) :
        if node . data . rule_label == rule . class_label :
            next_node = node
            break
    if not next_node :
        raise AttributeError ( ( 'Current Rule %s is multipath and the ' 'Rule choice passed in was not in the Flow' ) % ( self . current_node . data . rule_name ) )
self . current_node . data . rule . on_leave ( self )
next_node . data . rule . on_enter ( self )
self . current_node = next_node
self . save ( )


signature:
def get_location ( self , location_id ) :
    """Returns location data .
 http : / / dev . wheniwork . com / # get - existing - location"""

implementation:
url = "/2/locations/%s" % location_id
return self . location_from_json ( self . _get_resource ( url ) [ "location" ] )


signature:
def get_locations ( self ) :
    """Returns a list of locations .
 http : / / dev . wheniwork . com / # listing - locations"""

implementation:
url = "/2/locations"
data = self . _get_resource ( url )
locations = [ ]
for entry in data [ 'locations' ] :
    locations . append ( self . location_from_json ( entry ) )
return locations


signature:
def X ( self ) :
    """The : math : ` X ` weighted properly by the errors from * y _ error *"""

implementation:
if self . _X is None :
    X = _copy . deepcopy ( self . X_unweighted )
    # print ' X shape is { } ' . format ( X . shape )
    for i , el in enumerate ( X ) :
        X [ i , : ] = el / self . y_error [ i ]
    # print ' New X shape is { } ' . format ( X . shape )
    self . _X = X
return self . _X


signature:
def y ( self ) :
    """The : math : ` X ` weighted properly by the errors from * y _ error *"""

implementation:
if self . _y is None :
    self . _y = self . y_unweighted / self . y_error
return self . _y


signature:
def y_fit ( self ) :
    """Using the result of the linear least squares , the result of : math : ` X _ { ij } \\ beta _ i `"""

implementation:
if self . _y_fit is None :
    self . _y_fit = _np . dot ( self . X_unweighted , self . beta )
return self . _y_fit


signature:
def beta ( self ) :
    """The result : math : ` \\ beta ` of the linear least squares"""

implementation:
if self . _beta is None : # This is the linear least squares matrix formalism
    self . _beta = _np . dot ( _np . linalg . pinv ( self . X ) , self . y )
return self . _beta


signature:
def covar ( self ) :
    """The covariance matrix for the result : math : ` \\ beta `"""

implementation:
if self . _covar is None :
    self . _covar = _np . linalg . inv ( _np . dot ( _np . transpose ( self . X ) , self . X ) )
return self . _covar


signature:
def chisq_red ( self ) :
    """The reduced chi - square of the linear least squares"""

implementation:
if self . _chisq_red is None :
    self . _chisq_red = chisquare ( self . y_unweighted . transpose ( ) , _np . dot ( self . X_unweighted , self . beta ) , self . y_error , ddof = 3 , verbose = False )
return self . _chisq_red


signature:
def create ( self , server ) :
    """Create the task on the server"""

implementation:
if len ( self . geometries ) == 0 :
    raise Exception ( 'no geometries' )
return server . post ( 'task_admin' , self . as_payload ( ) , replacements = { 'slug' : self . __challenge__ . slug , 'identifier' : self . identifier } )


signature:
def update ( self , server ) :
    """Update existing task on the server"""

implementation: return server . put ( 'task_admin' , self . as_payload ( ) , replacements = { 'slug' : self . __challenge__ . slug , 'identifier' : self . identifier } )


signature:
def from_server ( cls , server , slug , identifier ) :
    """Retrieve a task from the server"""

implementation:
task = server . get ( 'task' , replacements = { 'slug' : slug , 'identifier' : identifier } )
return cls ( ** task )


signature:
def formatter ( color , s ) :
    """Formats a string with color"""

implementation:
if no_coloring :
    return s
return "{begin}{s}{reset}" . format ( begin = color , s = s , reset = Colors . RESET )


signature:
def reload ( self , * fields , ** kwargs ) :
    """Reloads all attributes from the database .
 : param fields : ( optional ) args list of fields to reload
 : param max _ depth : ( optional ) depth of dereferencing to follow
 . . versionadded : : 0.1.2
 . . versionchanged : : 0.6 Now chainable
 . . versionchanged : : 0.9 Can provide specific fields to reload"""

implementation:
max_depth = 1
if fields and isinstance ( fields [ 0 ] , int ) :
    max_depth = fields [ 0 ]
    fields = fields [ 1 : ]
elif "max_depth" in kwargs :
    max_depth = kwargs [ "max_depth" ]
if not self . pk :
    raise self . DoesNotExist ( "Document does not exist" )
obj = self . _qs . read_preference ( ReadPreference . PRIMARY ) . filter ( ** self . _object_key ) . only ( * fields ) . limit ( 1 ) . select_related ( max_depth = max_depth )
if obj :
    obj = obj [ 0 ]
else :
    raise self . DoesNotExist ( "Document does not exist" )
for field in self . _fields_ordered :
    if not fields or field in fields :
        try :
            setattr ( self , field , self . _reload ( field , obj [ field ] ) )
        except KeyError : # If field is removed from the database while the object
        # is in memory , a reload would cause a KeyError
        # i . e . obj . update ( unset _ _ field = 1 ) followed by obj . reload ( )
            delattr ( self , field )
# BUG FIX BY US HERE :
if not fields :
    self . _changed_fields = obj . _changed_fields
else :
    for field in fields :
        field = self . _db_field_map . get ( field , field )
        if field in self . _changed_fields :
            self . _changed_fields . remove ( field )
self . _created = False
return self


signature:
def pdf2png ( file_in , file_out ) :
    """Uses ` ImageMagick < http : / / www . imagemagick . org / > ` _ to convert an input * file _ in * pdf to a * file _ out * png . ( Untested with other formats . )
 Parameters
 file _ in : str
 The path to the pdf file to be converted .
 file _ out : str
 The path to the png file to be written ."""

implementation:
command = 'convert -display 37.5 {} -resize 600 -append {}' . format ( file_in , file_out )
_subprocess . call ( _shlex . split ( command ) )


signature:
def get_user ( self , user_id ) :
    """Returns user profile data .
 http : / / dev . wheniwork . com / # get - existing - user"""

implementation:
url = "/2/users/%s" % user_id
return self . user_from_json ( self . _get_resource ( url ) [ "user" ] )


signature:
def get_users ( self , params = { } ) :
    """Returns a list of users .
 http : / / dev . wheniwork . com / # listing - users"""

implementation:
param_list = [ ( k , params [ k ] ) for k in sorted ( params ) ]
url = "/2/users/?%s" % urlencode ( param_list )
data = self . _get_resource ( url )
users = [ ]
for entry in data [ "users" ] :
    users . append ( self . user_from_json ( entry ) )
return users


signature:
def _setVirtualEnv ( ) :
    """Attempt to set the virtualenv activate command , if it hasn ' t been specified ."""

implementation:
try :
    activate = options . virtualenv . activate_cmd
except AttributeError :
    activate = None
if activate is None :
    virtualenv = path ( os . environ . get ( 'VIRTUAL_ENV' , '' ) )
    if not virtualenv :
        virtualenv = options . paved . cwd
    else :
        virtualenv = path ( virtualenv )
    activate = virtualenv / 'bin' / 'activate'
    if activate . exists ( ) :
        info ( 'Using default virtualenv at %s' % activate )
        options . setdotted ( 'virtualenv.activate_cmd' , 'source %s' % activate )


signature:
def shv ( command , capture = False , ignore_error = False , cwd = None ) :
    """Run the given command inside the virtual environment , if available :"""

implementation:
_setVirtualEnv ( )
try :
    command = "%s; %s" % ( options . virtualenv . activate_cmd , command )
except AttributeError :
    pass
return bash ( command , capture = capture , ignore_error = ignore_error , cwd = cwd )


signature:
def update ( dst , src ) :
    """Recursively update the destination dict - like object with the source dict - like object .
 Useful for merging options and Bunches together !
 Based on :
 http : / / code . activestate . com / recipes / 499335 - recursively - update - a - dictionary - without - hitting - py / # c1"""

implementation:
stack = [ ( dst , src ) ]
def isdict ( o ) :
    return hasattr ( o , 'keys' )
while stack :
    current_dst , current_src = stack . pop ( )
    for key in current_src :
        if key not in current_dst :
            current_dst [ key ] = current_src [ key ]
        else :
            if isdict ( current_src [ key ] ) and isdict ( current_dst [ key ] ) :
                stack . append ( ( current_dst [ key ] , current_src [ key ] ) )
            else :
                current_dst [ key ] = current_src [ key ]
return dst


signature:
def pip_install ( * args ) :
    """Send the given arguments to ` pip install ` ."""

implementation:
download_cache = ( '--download-cache=%s ' % options . paved . pip . download_cache ) if options . paved . pip . download_cache else ''
shv ( 'pip install %s%s' % ( download_cache , ' ' . join ( args ) ) )


signature:
def _get_resource ( self , url , data_key = None ) :
    """When I Work GET method . Return representation of the requested
 resource ."""

implementation:
headers = { "Accept" : "application/json" }
if self . token :
    headers [ "W-Token" ] = "%s" % self . token
response = WhenIWork_DAO ( ) . getURL ( url , headers )
if response . status != 200 :
    raise DataFailureException ( url , response . status , response . data )
return json . loads ( response . data )


signature:
def _put_resource ( self , url , body ) :
    """When I Work PUT method ."""

implementation:
headers = { "Content-Type" : "application/json" , "Accept" : "application/json" }
if self . token :
    headers [ "W-Token" ] = "%s" % self . token
response = WhenIWork_DAO ( ) . putURL ( url , headers , json . dumps ( body ) )
if not ( response . status == 200 or response . status == 201 or response . status == 204 ) :
    raise DataFailureException ( url , response . status , response . data )
return json . loads ( response . data )


signature:
def _post_resource ( self , url , body ) :
    """When I Work POST method ."""

implementation:
headers = { "Content-Type" : "application/json" , "Accept" : "application/json" }
if self . token :
    headers [ "W-Token" ] = "%s" % self . token
response = WhenIWork_DAO ( ) . postURL ( url , headers , json . dumps ( body ) )
if not ( response . status == 200 or response . status == 204 ) :
    raise DataFailureException ( url , response . status , response . data )
return json . loads ( response . data )


signature:
def _delete_resource ( self , url ) :
    """When I Work DELETE method ."""

implementation:
headers = { "Content-Type" : "application/json" , "Accept" : "application/json" }
if self . token :
    headers [ "W-Token" ] = "%s" % self . token
response = WhenIWork_DAO ( ) . deleteURL ( url , headers )
if not ( response . status == 200 or response . status == 201 or response . status == 204 ) :
    raise DataFailureException ( url , response . status , response . data )
return json . loads ( response . data )


signature:
def get_shifts ( self , params = { } ) :
    """List shifts
 http : / / dev . wheniwork . com / # listing - shifts"""

implementation:
param_list = [ ( k , params [ k ] ) for k in sorted ( params ) ]
url = "/2/shifts/?%s" % urlencode ( param_list )
data = self . _get_resource ( url )
shifts = [ ]
locations = { }
sites = { }
positions = { }
users = { }
for entry in data . get ( "locations" , [ ] ) :
    location = Locations . location_from_json ( entry )
    locations [ location . location_id ] = location
for entry in data . get ( "sites" , [ ] ) :
    site = Sites . site_from_json ( entry )
    sites [ site . site_id ] = site
for entry in data . get ( "positions" , [ ] ) :
    position = Positions . position_from_json ( entry )
    positions [ position . position_id ] = position
for entry in data . get ( "users" , [ ] ) :
    user = Users . user_from_json ( entry )
    users [ user . user_id ] = user
for entry in data [ "shifts" ] :
    shift = self . shift_from_json ( entry )
    shifts . append ( shift )
for shift in shifts :
    shift . location = locations . get ( shift . location_id , None )
    shift . site = sites . get ( shift . site_id , None )
    shift . position = positions . get ( shift . position_id , None )
    shift . user = users . get ( shift . user_id , None )
return shifts


signature:
def create_shift ( self , params = { } ) :
    """Creates a shift
 http : / / dev . wheniwork . com / # create / update - shift"""

implementation:
url = "/2/shifts/"
body = params
data = self . _post_resource ( url , body )
shift = self . shift_from_json ( data [ "shift" ] )
return shift


signature:
def delete_shifts ( self , shifts ) :
    """Delete existing shifts .
 http : / / dev . wheniwork . com / # delete - shift"""

implementation:
url = "/2/shifts/?%s" % urlencode ( { 'ids' : "," . join ( str ( s ) for s in shifts ) } )
data = self . _delete_resource ( url )
return data


signature:
def delete_past_events ( self ) :
    """Removes old events . This is provided largely as a convenience for maintenance
 purposes ( daily _ cleanup ) . if an Event has passed by more than X days
 as defined by Lapsed and has no related special events it will be deleted
 to free up the event name and remove clutter .
 For best results , set this up to run regularly as a cron job ."""

implementation:
lapsed = datetime . datetime . now ( ) - datetime . timedelta ( days = 90 )
for event in self . filter ( start_date__lte = lapsed , featured = 0 , recap = '' ) :
    event . delete ( )


signature:
def recently_ended ( self ) :
    """Determines if event ended recently ( within 5 days ) .
 Useful for attending list ."""

implementation:
if self . ended ( ) :
    end_date = self . end_date if self . end_date else self . start_date
    if end_date >= offset . date ( ) :
        return True


signature:
def all_comments ( self ) :
    """Returns combined list of event and update comments ."""

implementation:
ctype = ContentType . objects . get ( app_label__exact = "happenings" , model__exact = 'event' )
update_ctype = ContentType . objects . get ( app_label__exact = "happenings" , model__exact = 'update' )
update_ids = self . update_set . values_list ( 'id' , flat = True )
return Comment . objects . filter ( Q ( content_type = ctype . id , object_pk = self . id ) | Q ( content_type = update_ctype . id , object_pk__in = update_ids ) )


signature:
def get_all_images ( self ) :
    """Returns chained list of event and update images ."""

implementation:
self_imgs = self . image_set . all ( )
update_ids = self . update_set . values_list ( 'id' , flat = True )
u_images = UpdateImage . objects . filter ( update__id__in = update_ids )
return list ( chain ( self_imgs , u_images ) )


signature:
def get_all_images_count ( self ) :
    """Gets count of all images from both event and updates ."""

implementation:
self_imgs = self . image_set . count ( )
update_ids = self . update_set . values_list ( 'id' , flat = True )
u_images = UpdateImage . objects . filter ( update__id__in = update_ids ) . count ( )
count = self_imgs + u_images
return count


signature:
def get_top_assets ( self ) :
    """Gets images and videos to populate top assets .
 Map is built separately ."""

implementation:
images = self . get_all_images ( ) [ 0 : 14 ]
video = [ ]
if supports_video :
    video = self . eventvideo_set . all ( ) [ 0 : 10 ]
return list ( chain ( images , video ) ) [ 0 : 15 ]


signature:
def plot_featured ( * args , ** kwargs ) :
    """Wrapper for matplotlib . pyplot . plot ( ) / errorbar ( ) .
 Takes options :
 * ' error ' : if true , use : func : ` matplotlib . pyplot . errorbar ` instead of : func : ` matplotlib . pyplot . plot ` . * \ * args * and * \ * \ * kwargs * passed through here .
 * ' fig ' : figure to use .
 * ' figlabel ' : figure label .
 * ' legend ' : legend location .
 * ' toplabel ' : top label of plot .
 * ' xlabel ' : x - label of plot .
 * ' ylabel ' : y - label of plot ."""

implementation:
# Strip off options specific to plot _ featured
toplabel = kwargs . pop ( 'toplabel' , None )
xlabel = kwargs . pop ( 'xlabel' , None )
ylabel = kwargs . pop ( 'ylabel' , None )
legend = kwargs . pop ( 'legend' , None )
error = kwargs . pop ( 'error' , None )
# save = kwargs . pop ( ' save ' , False )
figlabel = kwargs . pop ( 'figlabel' , None )
fig = kwargs . pop ( 'fig' , None )
if figlabel is not None :
    fig = _figure ( figlabel )
elif fig is None :
    try :
        fig = _plt . gcf ( )
    except :
        fig = _plt . fig ( )
# Pass everything else to plot
if error is None :
    _plt . plot ( * args , ** kwargs )
else :
    _plt . errorbar ( * args , ** kwargs )
# Format plot as desired
_addlabel ( toplabel , xlabel , ylabel , fig = fig )
if legend is not None :
    _plt . legend ( legend )
return fig


signature:
def decorate ( msg = "" , waitmsg = "Please wait" ) :
    """Decorated methods progress will be displayed to the user as a spinner .
 Mostly for slower functions that do some network IO ."""

implementation:
def decorator ( func ) :
    @ functools . wraps ( func )
    def wrapper ( * args , ** kwargs ) :
        spin = Spinner ( msg = msg , waitmsg = waitmsg )
        spin . start ( )
        a = None
        try :
            a = func ( * args , ** kwargs )
        except Exception as e :
            spin . msg = "Something went wrong: "
            spin . stop_spinning ( )
            spin . join ( )
            raise e
        spin . stop_spinning ( )
        spin . join ( )
        return a
    return wrapper
return decorator


signature:
def launch ( title , items , selected = None ) :
    """Launches a new menu . Wraps curses nicely so exceptions won ' t screw with
 the terminal too much ."""

implementation:
resp = { "code" : - 1 , "done" : False }
curses . wrapper ( Menu , title , items , selected , resp )
return resp


signature:
def q ( self , x , q0 ) :
    """Numerically solved trajectory function for initial conditons : math : ` q ( 0 ) = q _ 0 ` and : math : ` q ' ( 0 ) = 0 ` ."""

implementation:
y1_0 = q0
y0_0 = 0
y0 = [ y0_0 , y1_0 ]
y = _sp . integrate . odeint ( self . _func , y0 , x , Dfun = self . _gradient , rtol = self . rtol , atol = self . atol )
return y [ : , 1 ]


signature:
def save ( self , * args , ** kwargs ) :
    """Overridden method that handles that re - ranking of objects and the
 integrity of the ` ` rank ` ` field .
 : param rerank :
 Added parameter , if True will rerank other objects based on the
 change in this save . Defaults to True ."""

implementation:
rerank = kwargs . pop ( 'rerank' , True )
if rerank :
    if not self . id :
        self . _process_new_rank_obj ( )
    elif self . rank == self . _rank_at_load : # nothing changed
        pass
    else :
        self . _process_moved_rank_obj ( )
super ( RankedModel , self ) . save ( * args , ** kwargs )


signature:
def repack ( self ) :
    """Removes any blank ranks in the order ."""

implementation:
items = self . grouped_filter ( ) . order_by ( 'rank' ) . select_for_update ( )
for count , item in enumerate ( items ) :
    item . rank = count + 1
    item . save ( rerank = False )


signature:
def refetch_for_update ( obj ) :
    """Queries the database for the same object that is passed in , refetching
 its contents and runs ` ` select _ for _ update ( ) ` ` to lock the corresponding
 row until the next commit .
 : param obj :
 Object to refetch
 : returns :
 Refreshed version of the object"""

implementation: return obj . __class__ . objects . select_for_update ( ) . get ( id = obj . id )


signature:
def get_field_names ( obj , ignore_auto = True , ignore_relations = True , exclude = [ ] ) :
    """Returns the field names of a Django model object .
 : param obj : the Django model class or object instance to get the fields
 from
 : param ignore _ auto : ignore any fields of type AutoField . Defaults to True
 : param ignore _ relations : ignore any fields that involve relations such as
 the ForeignKey or ManyToManyField
 : param exclude : exclude anything in this list from the results
 : returns : generator of found field names"""

implementation:
from django . db . models import ( AutoField , ForeignKey , ManyToManyField , ManyToOneRel , OneToOneField , OneToOneRel )
for field in obj . _meta . get_fields ( ) :
    if ignore_auto and isinstance ( field , AutoField ) :
        continue
    if ignore_relations and ( isinstance ( field , ForeignKey ) or isinstance ( field , ManyToManyField ) or isinstance ( field , ManyToOneRel ) or isinstance ( field , OneToOneRel ) or isinstance ( field , OneToOneField ) ) : # optimization is killing coverage measure , have to put no - op that
    # does something
        a = 1 ;
        a
        continue
    if field . name in exclude :
        continue
    yield field . name


signature:
def get_obj_attr ( obj , attr ) :
    """Works like getattr ( ) but supports django ' s double underscore object
 dereference notation .
 Example usage :
 . . code - block : : python
 > > > get _ obj _ attr ( book , ' writer _ _ age ' )
 42
 > > > get _ obj _ attr ( book , ' publisher _ _ address ' )
 < Address object at 105a79ac8 >
 : param obj :
 Object to start the derference from
 : param attr :
 String name of attribute to return
 : returns :
 Derferenced object
 : raises :
 AttributeError in the attribute in question does not exist"""

implementation:
# handle ' _ _ ' referencing like in QuerySets
fields = attr . split ( '__' )
field_obj = getattr ( obj , fields [ 0 ] )
for field in fields [ 1 : ] : # keep going down the reference tree
    field_obj = getattr ( field_obj , field )
return field_obj


signature:
def as_list ( self ) :
    """Returns a list of strings describing the full paths and patterns
 along with the name of the urls . Example :
 . . code - block : : python
 > > > u = URLTree ( )
 > > > u . as _ list ( )
 ' admin / ' ,
 ' admin / $ , name = index ' ,
 ' admin / login / $ , name = login ' ,"""

implementation:
result = [ ]
for child in self . children :
    self . _depth_traversal ( child , result )
return result


signature:
def register ( app ) :
    """Register all HTTP error code error handlers
 Currently , errors are handled by the JSON error handler ."""

implementation:
# Pick a handler based on the requested format . Currently we assume the
# caller wants JSON .
error_handler = json . http_exception_error_handler
@ app . errorhandler ( 400 )
def handle_bad_request ( exception ) :
    return error_handler ( exception )
@ app . errorhandler ( 404 )
def handle_not_found ( exception ) :
    return error_handler ( exception )
@ app . errorhandler ( 405 )
def handle_method_not_allowed ( exception ) :
    return error_handler ( exception )
@ app . errorhandler ( 422 )
def handle_unprocessable_entity ( exception ) :
    return error_handler ( exception )
@ app . errorhandler ( 500 )
def handle_internal_server_error ( exception ) :
    return error_handler ( exception )


signature:
def plot ( * args , ax = None , ** kwargs ) :
    """Plots but automatically resizes x axis .
 . . versionadded : : 1.4
 Parameters
 args
 Passed on to : meth : ` matplotlib . axis . Axis . plot ` .
 ax : : class : ` matplotlib . axis . Axis ` , optional
 The axis to plot to .
 kwargs
 Passed on to : meth : ` matplotlib . axis . Axis . plot ` ."""

implementation:
if ax is None :
    fig , ax = _setup_axes ( )
pl = ax . plot ( * args , ** kwargs )
if _np . shape ( args ) [ 0 ] > 1 :
    if type ( args [ 1 ] ) is not str :
        min_x = min ( args [ 0 ] )
        max_x = max ( args [ 0 ] )
        ax . set_xlim ( ( min_x , max_x ) )
return pl


signature:
def linspacestep ( start , stop , step = 1 ) :
    """Create a vector of values over an interval with a specified step size .
 Parameters
 start : float
 The beginning of the interval .
 stop : float
 The end of the interval .
 step : float
 The step size .
 Returns
 vector : : class : ` numpy . ndarray `
 The vector of values ."""

implementation:
# Find an integer number of steps
numsteps = _np . int ( ( stop - start ) / step )
# Do a linspace over the new range
# that has the correct endpoint
return _np . linspace ( start , start + step * numsteps , numsteps + 1 )


signature:
def mylogger ( name = None , filename = None , indent_offset = 7 , level = _logging . DEBUG , stream_level = _logging . WARN , file_level = _logging . INFO ) :
    """Sets up logging to * filename * . debug . log , * filename * . log , and the terminal . * indent _ offset * attempts to line up the lowest indent level to 0 . Custom levels :
 * * level * : Parent logging level .
 * * stream _ level * : Logging level for console stream .
 * * file _ level * : Logging level for general file log ."""

implementation:
if name is not None :
    logger = _logging . getLogger ( name )
else :
    logger = _logging . getLogger ( )
logger . setLevel ( level )
fmtr = IndentFormatter ( indent_offset = indent_offset )
fmtr_msgonly = IndentFormatter ( '%(funcName)s:%(lineno)d: %(message)s' )
ch = _logging . StreamHandler ( )
ch . setLevel ( stream_level )
ch . setFormatter ( fmtr_msgonly )
logger . addHandler ( ch )
if filename is not None :
    debugh = _logging . FileHandler ( filename = '{}_debug.log' . format ( filename ) , mode = 'w' )
    debugh . setLevel ( _logging . DEBUG )
    debugh . setFormatter ( fmtr_msgonly )
    logger . addHandler ( debugh )
    fh = _logging . FileHandler ( filename = '{}.log' . format ( filename ) , mode = 'w' )
    fh . setLevel ( file_level )
    fh . setFormatter ( fmtr )
    logger . addHandler ( fh )
return logger


signature:
def selected_course ( func ) :
    """Passes the selected course as the first argument to func ."""

implementation:
@ wraps ( func )
def inner ( * args , ** kwargs ) :
    course = Course . get_selected ( )
    return func ( course , * args , ** kwargs )
return inner


signature:
def selected_exercise ( func ) :
    """Passes the selected exercise as the first argument to func ."""

implementation:
@ wraps ( func )
def inner ( * args , ** kwargs ) :
    exercise = Exercise . get_selected ( )
    return func ( exercise , * args , ** kwargs )
return inner


signature:
def false_exit ( func ) :
    """If func returns False the program exits immediately ."""

implementation:
@ wraps ( func )
def inner ( * args , ** kwargs ) :
    ret = func ( * args , ** kwargs )
    if ret is False :
        if "TMC_TESTING" in os . environ :
            raise TMCExit ( )
        else :
            sys . exit ( - 1 )
    return ret
return inner


signature:
def configure ( server = None , username = None , password = None , tid = None , auto = False ) :
    """Configure tmc . py to use your account ."""

implementation:
if not server and not username and not password and not tid :
    if Config . has ( ) :
        if not yn_prompt ( "Override old configuration" , False ) :
            return False
reset_db ( )
if not server :
    while True :
        server = input ( "Server url [https://tmc.mooc.fi/mooc/]: " ) . strip ( )
        if len ( server ) == 0 :
            server = "https://tmc.mooc.fi/mooc/"
        if not server . endswith ( '/' ) :
            server += '/'
        if not ( server . startswith ( "http://" ) or server . startswith ( "https://" ) ) :
            ret = custom_prompt ( "Server should start with http:// or https://\n" + "R: Retry, H: Assume http://, S: Assume https://" , [ "r" , "h" , "s" ] , "r" )
            if ret == "r" :
                continue
            # Strip previous schema
            if "://" in server :
                server = server . split ( "://" ) [ 1 ]
            if ret == "h" :
                server = "http://" + server
            elif ret == "s" :
                server = "https://" + server
        break
    print ( "Using URL: '{0}'" . format ( server ) )
while True :
    if not username :
        username = input ( "Username: " )
    if not password :
        password = getpass ( "Password: " )
    # wow , such security
    token = b64encode ( bytes ( "{0}:{1}" . format ( username , password ) , encoding = 'utf-8' ) ) . decode ( "utf-8" )
    try :
        api . configure ( url = server , token = token , test = True )
    except APIError as e :
        print ( e )
        if auto is False and yn_prompt ( "Retry authentication" ) :
            username = password = None
            continue
        return False
    break
if tid :
    select ( course = True , tid = tid , auto = auto )
else :
    select ( course = True )


signature:
def download ( course , tid = None , dl_all = False , force = False , upgradejava = False , update = False ) :
    """Download the exercises from the server ."""

implementation:
def dl ( id ) :
    download_exercise ( Exercise . get ( Exercise . tid == id ) , force = force , update_java = upgradejava , update = update )
if dl_all :
    for exercise in list ( course . exercises ) :
        dl ( exercise . tid )
elif tid is not None :
    dl ( int ( tid ) )
else :
    for exercise in list ( course . exercises ) :
        if not exercise . is_completed :
            dl ( exercise . tid )
        else :
            exercise . update_downloaded ( )


signature:
def skip ( course , num = 1 ) :
    """Go to the next exercise ."""

implementation:
sel = None
try :
    sel = Exercise . get_selected ( )
    if sel . course . tid != course . tid :
        sel = None
except NoExerciseSelected :
    pass
if sel is None :
    sel = course . exercises . first ( )
else :
    try :
        sel = Exercise . get ( Exercise . id == sel . id + num )
    except peewee . DoesNotExist :
        print ( "There are no more exercises in this course." )
        return False
sel . set_select ( )
list_all ( single = sel )


signature:
def run ( exercise , command ) :
    """Spawns a process with ` command path - of - exercise `"""

implementation: Popen ( [ 'nohup' , command , exercise . path ( ) ] , stdout = DEVNULL , stderr = DEVNULL )


signature:
def select ( course = False , tid = None , auto = False ) :
    """Select a course or an exercise ."""

implementation:
if course :
    update ( course = True )
    course = None
    try :
        course = Course . get_selected ( )
    except NoCourseSelected :
        pass
    ret = { }
    if not tid :
        ret = Menu . launch ( "Select a course" , Course . select ( ) . execute ( ) , course )
    else :
        ret [ "item" ] = Course . get ( Course . tid == tid )
    if "item" in ret :
        ret [ "item" ] . set_select ( )
        update ( )
        if ret [ "item" ] . path == "" :
            select_a_path ( auto = auto )
        # Selects the first exercise in this course
        skip ( )
        return
    else :
        print ( "You can select the course with `tmc select --course`" )
        return
else :
    selected = None
    try :
        selected = Exercise . get_selected ( )
    except NoExerciseSelected :
        pass
    ret = { }
    if not tid :
        ret = Menu . launch ( "Select an exercise" , Course . get_selected ( ) . exercises , selected )
    else :
        ret [ "item" ] = Exercise . byid ( tid )
    if "item" in ret :
        ret [ "item" ] . set_select ( )
        print ( "Selected {}" . format ( ret [ "item" ] ) )


signature:
def submit ( course , tid = None , pastebin = False , review = False ) :
    """Submit the selected exercise to the server ."""

implementation:
if tid is not None :
    return submit_exercise ( Exercise . byid ( tid ) , pastebin = pastebin , request_review = review )
else :
    sel = Exercise . get_selected ( )
    if not sel :
        raise NoExerciseSelected ( )
    return submit_exercise ( sel , pastebin = pastebin , request_review = review )


signature:
def paste ( tid = None , review = False ) :
    """Sends the selected exercise to the TMC pastebin ."""

implementation: submit ( pastebin = True , tid = tid , review = False )


signature:
def list_all ( course , single = None ) :
    """Lists all of the exercises in the current course ."""

implementation:
def bs ( val ) :
    return "●" if val else " "
def bc ( val ) :
    return as_success ( "✔" ) if val else as_error ( "✘" )
def format_line ( exercise ) :
    return "{0} │ {1} │ {2} │ {3} │ {4}" . format ( exercise . tid , bs ( exercise . is_selected ) , bc ( exercise . is_downloaded ) , bc ( exercise . is_completed ) , exercise . menuname ( ) )
print ( "ID{0}│ S │ D │ C │ Name" . format ( ( len ( str ( course . exercises [ 0 ] . tid ) ) - 1 ) * " " ) )
if single :
    print ( format_line ( single ) )
    return
for exercise in course . exercises : # ToDo : use a pager
    print ( format_line ( exercise ) )


signature:
def update ( course = False ) :
    """Update the data of courses and or exercises from server ."""

implementation:
if course :
    with Spinner . context ( msg = "Updated course metadata." , waitmsg = "Updating course metadata." ) :
        for course in api . get_courses ( ) :
            old = None
            try :
                old = Course . get ( Course . tid == course [ "id" ] )
            except peewee . DoesNotExist :
                old = None
            if old :
                old . details_url = course [ "details_url" ]
                old . save ( )
                continue
            Course . create ( tid = course [ "id" ] , name = course [ "name" ] , details_url = course [ "details_url" ] )
else :
    selected = Course . get_selected ( )
    # with Spinner . context ( msg = " Updated exercise metadata . " ,
    # waitmsg = " Updating exercise metadata . " ) :
    print ( "Updating exercise data." )
    for exercise in api . get_exercises ( selected ) :
        old = None
        try :
            old = Exercise . byid ( exercise [ "id" ] )
        except peewee . DoesNotExist :
            old = None
        if old is not None :
            old . name = exercise [ "name" ]
            old . course = selected . id
            old . is_attempted = exercise [ "attempted" ]
            old . is_completed = exercise [ "completed" ]
            old . deadline = exercise . get ( "deadline" )
            old . is_downloaded = os . path . isdir ( old . path ( ) )
            old . return_url = exercise [ "return_url" ]
            old . zip_url = exercise [ "zip_url" ]
            old . submissions_url = exercise [ "exercise_submissions_url" ]
            old . save ( )
            download_exercise ( old , update = True )
        else :
            ex = Exercise . create ( tid = exercise [ "id" ] , name = exercise [ "name" ] , course = selected . id , is_attempted = exercise [ "attempted" ] , is_completed = exercise [ "completed" ] , deadline = exercise . get ( "deadline" ) , return_url = exercise [ "return_url" ] , zip_url = exercise [ "zip_url" ] , submissions_url = exercise [ ( "exercise_" "submissions_" "url" ) ] )
            ex . is_downloaded = os . path . isdir ( ex . path ( ) )
            ex . save ( )


signature:
def determine_type ( x ) :
    """Determine the type of x"""

implementation:
types = ( int , float , str )
_type = filter ( lambda a : is_type ( a , x ) , types ) [ 0 ]
return _type ( x )


signature:
def dmap ( fn , record ) :
    """map for a directory"""

implementation:
values = ( fn ( v ) for k , v in record . items ( ) )
return dict ( itertools . izip ( record , values ) )


signature:
def apply_types ( use_types , guess_type , line ) :
    """Apply the types on the elements of the line"""

implementation:
new_line = { }
for k , v in line . items ( ) :
    if use_types . has_key ( k ) :
        new_line [ k ] = force_type ( use_types [ k ] , v )
    elif guess_type :
        new_line [ k ] = determine_type ( v )
    else :
        new_line [ k ] = v
return new_line


signature:
def read_csv ( filename , delimiter = "," , skip = 0 , guess_type = True , has_header = True , use_types = { } ) :
    """Read a CSV file
 Usage
 > > > data = read _ csv ( filename , delimiter = delimiter , skip = skip ,
 guess _ type = guess _ type , has _ header = True , use _ types = { } )
 # Use specific types
 > > > types = { " sepal . length " : int , " petal . width " : float }
 > > > data = read _ csv ( filename , guess _ type = guess _ type , use _ types = types )
 keywords
 : has _ header :
 Determine whether the file has a header or not"""

implementation:
with open ( filename , 'r' ) as f : # Skip the n first lines
    if has_header :
        header = f . readline ( ) . strip ( ) . split ( delimiter )
    else :
        header = None
    for i in range ( skip ) :
        f . readline ( )
    for line in csv . DictReader ( f , delimiter = delimiter , fieldnames = header ) :
        if use_types :
            yield apply_types ( use_types , guess_type , line )
        elif guess_type :
            yield dmap ( determine_type , line )
        else :
            yield line


signature:
def write_csv ( filename , header , data = None , rows = None , mode = "w" ) :
    """Write the data to the specified filename
 Usage
 > > > write _ csv ( filename , header , data , mode = mode )
 Parameters
 filename : str
 The name of the file
 header : list of strings
 The names of the columns ( or fields ) :
 ( fieldname1 , fieldname2 , . . . )
 data : list of dictionaries ( optional )
 { fieldname1 : a1 , fieldname2 : a2 } ,
 { fieldname1 : b1 , fieldname2 : b2 } ,
 rows : list of lists ( optional )
 ( a1 , a2 ) ,
 ( b1 , b2 ) ,
 mode : str ( optional )
 " w " : write the data to the file by overwriting it
 " a " : write the data to the file by appending them
 Returns
 None . A CSV file is written ."""

implementation:
if data == rows == None :
    msg = "You must specify either data or rows"
    raise ValueError ( msg )
elif data != None and rows != None :
    msg = "You must specify either data or rows. Not both"
    raise ValueError ( msg )
data_header = dict ( ( x , x ) for x in header )
with open ( filename , mode ) as f :
    if data :
        writer = csv . DictWriter ( f , fieldnames = header )
        if mode == "w" :
            writer . writerow ( data_header )
        writer . writerows ( data )
    elif rows :
        writer = csv . writer ( f )
        if mode == "w" :
            writer . writerow ( header )
        writer . writerows ( rows )
print "Saved %s." % filename


signature:
def format_to_csv ( filename , skiprows = 0 , delimiter = "" ) :
    """Convert a file to a . csv file"""

implementation:
if not delimiter :
    delimiter = "\t"
input_file = open ( filename , "r" )
if skiprows :
    [ input_file . readline ( ) for _ in range ( skiprows ) ]
new_filename = os . path . splitext ( filename ) [ 0 ] + ".csv"
output_file = open ( new_filename , "w" )
header = input_file . readline ( ) . split ( )
reader = csv . DictReader ( input_file , fieldnames = header , delimiter = delimiter )
writer = csv . DictWriter ( output_file , fieldnames = header , delimiter = "," )
# Write header
writer . writerow ( dict ( ( x , x ) for x in header ) )
# Write rows
for line in reader :
    if None in line :
        del line [ None ]
    writer . writerow ( line )
input_file . close ( )
output_file . close ( )
print "Saved %s." % new_filename


signature:
def savefig ( filename , path = "figs" , fig = None , ext = 'eps' , verbose = False , ** kwargs ) :
    """Save the figure * fig * ( optional , if not specified , latest figure in focus ) to * filename * in the path * path * with extension * ext * .
 * \ * \ * kwargs * is passed to : meth : ` matplotlib . figure . Figure . savefig ` ."""

implementation:
filename = os . path . join ( path , filename )
final_filename = '{}.{}' . format ( filename , ext ) . replace ( " " , "" ) . replace ( "\n" , "" )
final_filename = os . path . abspath ( final_filename )
final_path = os . path . dirname ( final_filename )
if not os . path . exists ( final_path ) :
    os . makedirs ( final_path )
if verbose :
    print ( 'Saving file: {}' . format ( final_filename ) )
if fig is not None :
    fig . savefig ( final_filename , bbox_inches = 'tight' , ** kwargs )
else :
    plt . savefig ( final_filename , bbox_inches = 'tight' , ** kwargs )


signature:
def admin_obj_link ( obj , display = '' ) :
    """Returns a link to the django admin change list with a filter set to
 only the object given .
 : param obj :
 Object to create the admin change list display link for
 : param display :
 Text to display in the link . Defaults to string call of the object
 : returns :
 Text containing HTML for a link"""

implementation:
# get the url for the change list for this object
url = reverse ( 'admin:%s_%s_changelist' % ( obj . _meta . app_label , obj . _meta . model_name ) )
url += '?id__exact=%s' % obj . id
text = str ( obj )
if display :
    text = display
return format_html ( '{}' , url , text )


signature:
def admin_obj_attr ( obj , attr ) :
    """A safe version of : func : ` ` utils . get _ obj _ attr ` ` that returns and empty
 string in the case of an exception or an empty object"""

implementation:
try :
    field_obj = get_obj_attr ( obj , attr )
    if not field_obj :
        return ''
except AttributeError :
    return ''
return field_obj


signature:
def _obj_display ( obj , display = '' ) :
    """Returns string representation of an object , either the default or based
 on the display template passed in ."""

implementation:
result = ''
if not display :
    result = str ( obj )
else :
    template = Template ( display )
    context = Context ( { 'obj' : obj } )
    result = template . render ( context )
return result


signature:
def make_admin_obj_mixin ( name ) :
    """This method dynamically creates a mixin to be used with your
 : class : ` ModelAdmin ` classes . The mixin provides utility methods that can
 be referenced in side of the admin object ' s ` ` list _ display ` ` and other
 similar attributes .
 : param name :
 Each usage of the mixin must be given a unique name for the mixin class
 being created
 : returns :
 Dynamically created mixin class
 The created class supports the following methods :
 . . code - block : : python
 add _ obj _ ref ( funcname , attr , [ title , display ] )
 Django admin ` ` list _ display ` ` does not support the double underscore
 semantics of object references . This method adds a function to the mixin
 that returns the ` ` str ( obj ) ` ` value from object relations .
 : param funcname :
 Name of the function to be added to the mixin . In the admin class
 object that includes the mixin , this name is used in the
 ` ` list _ display ` ` tuple .
 : param attr :
 Name of the attribute to dereference from the corresponding object ,
 i . e . what will be dereferenced . This name supports double underscore
 object link referencing for ` ` models . ForeignKey ` ` members .
 : param title :
 Title for the column of the django admin table . If not given it
 defaults to a capitalized version of ` ` attr ` `
 : param display :
 What to display as the text in the column . If not given it defaults
 to the string representation of the object for the row : ` ` str ( obj ) ` ` .
 This parameter supports django templating , the context for which
 contains a dictionary key named " obj " with the value being the object
 for the row .
 . . code - block : : python
 add _ obj _ link ( funcname , attr , [ title , display ] )
 This method adds a function to the mixin that returns a link to a django
 admin change list page for the member attribute of the object being
 displayed .
 : param funcname :
 Name of the function to be added to the mixin . In the admin class
 object that includes the mixin , this name is used in the
 ` ` list _ display ` ` tuple .
 : param attr :
 Name of the attribute to dereference from the corresponding object ,
 i . e . what will be lined to . This name supports double underscore
 object link referencing for ` ` models . ForeignKey ` ` members .
 : param title :
 Title for the column of the django admin table . If not given it
 defaults to a capitalized version of ` ` attr ` `
 : param display :
 What to display as the text for the link being shown . If not given it
 defaults to the string representation of the object for the row :
 ` ` str ( obj ) ` ` . This parameter supports django templating , the context
 for which contains a dictionary key named " obj " with the value being
 the object for the row .
 Example usage :
 . . code - block : : python
 # - - - - models . py file - - - -
 class Author ( models . Model ) :
 name = models . CharField ( max _ length = 100)
 class Book ( models . Model ) :
 title = models . CharField ( max _ length = 100)
 author = models . ForeignKey ( Author , on _ delete = models . CASCADE )
 . . code - block : : python
 # - - - - admin . py file - - - -
 @ admin . register ( Author )
 class Author ( admin . ModelAdmin ) :
 list _ display = ( ' name ' , )
 mixin = make _ admin _ obj _ mixin ( ' BookMixin ' )
 mixin . add _ obj _ link ( ' show _ author ' , ' Author ' , ' Our Authors ' ,
 ' { { obj . name } } ( id = { { obj . id } } ) ' )
 @ admin . register ( Book )
 class BookAdmin ( admin . ModelAdmin , mixin ) :
 list _ display = ( ' name ' , ' show _ author ' )
 A sample django admin page for " Book " would have the table :
 | Name | Our Authors |
 | Hitchhikers Guide To The Galaxy | * Douglas Adams ( id = 1 ) * |
 | War and Peace | * Tolstoy ( id = 2 ) * |
 | Dirk Gently | * Douglas Adams ( id = 1 ) * |
 Each of the * items * in the " Our Authors " column would be a link to the
 django admin change list for the " Author " object with a filter set to show
 just the object that was clicked . For example , if you clicked " Douglas
 Adams ( id = 1 ) " you would be taken to the Author change list page filtered
 just for Douglas Adams books .
 The ` ` add _ obj _ ref ` ` method is similar to the above , but instead of showing
 links , it just shows text and so can be used for view - only attributes of
 dereferenced objects ."""

implementation:
@ classmethod
def add_obj_link ( cls , funcname , attr , title = '' , display = '' ) :
    if not title :
        title = attr . capitalize ( )
    # python scoping is a bit weird with default values , if it isn ' t
    # referenced the inner function won ' t see it , so assign it for use
    _display = display
    def _link ( self , obj ) :
        field_obj = admin_obj_attr ( obj , attr )
        if not field_obj :
            return ''
        text = _obj_display ( field_obj , _display )
        return admin_obj_link ( field_obj , text )
    _link . short_description = title
    _link . allow_tags = True
    _link . admin_order_field = attr
    setattr ( cls , funcname , _link )
@ classmethod
def add_obj_ref ( cls , funcname , attr , title = '' , display = '' ) :
    if not title :
        title = attr . capitalize ( )
    # python scoping is a bit weird with default values , if it isn ' t
    # referenced the inner function won ' t see it , so assign it for use
    _display = display
    def _ref ( self , obj ) :
        field_obj = admin_obj_attr ( obj , attr )
        if not field_obj :
            return ''
        return _obj_display ( field_obj , _display )
    _ref . short_description = title
    _ref . allow_tags = True
    _ref . admin_order_field = attr
    setattr ( cls , funcname , _ref )
klass = type ( name , ( ) , { } )
klass . add_obj_link = add_obj_link
klass . add_obj_ref = add_obj_ref
return klass


signature:
def fancy_modeladmin ( * args ) :
    """Returns a new copy of a : class : ` FancyModelAdmin ` class ( a class , not
 an instance ! ) . This can then be inherited from when declaring a model
 admin class . The : class : ` FancyModelAdmin ` class has additional methods
 for managing the ` ` list _ display ` ` attribute .
 : param ` ` * args ` ` : [ optional ] any arguments given will be added to the
 ` ` list _ display ` ` property using regular django ` ` list _ display ` `
 functionality .
 This function is meant as a replacement for : func : ` make _ admin _ obj _ mixin ` ,
 it does everything the old one does with fewer bookkeeping needs for the
 user as well as adding functionality .
 Example usage :
 . . code - block : : python
 # - - - - models . py file - - - -
 class Author ( models . Model ) :
 name = models . CharField ( max _ length = 100)
 class Book ( models . Model ) :
 title = models . CharField ( max _ length = 100)
 author = models . ForeignKey ( Author , on _ delete = models . CASCADE )
 . . code - block : : python
 # - - - - admin . py file - - - -
 @ admin . register ( Author )
 class Author ( admin . ModelAdmin ) :
 list _ display = ( ' name ' , )
 base = fany _ list _ display _ modeladmin ( )
 base . add _ displays ( ' id ' , ' name ' )
 base . add _ obj _ link ( ' author ' , ' Our Authors ' ,
 ' { { obj . name } } ( id = { { obj . id } } ) ' )
 @ admin . register ( Book )
 class BookAdmin ( base ) :
 list _ display = ( ' name ' , ' show _ author ' )
 A sample django admin page for " Book " would have the table :
 | ID | Name | Our Authors |
 | 1 | Hitchhikers Guide To The Galaxy | * Douglas Adams ( id = 1 ) * |
 | 2 | War and Peace | * Tolstoy ( id = 2 ) * |
 | 3 | Dirk Gently | * Douglas Adams ( id = 1 ) * |
 See : class : ` FancyModelAdmin ` for a full list of functionality
 provided by the returned base class ."""

implementation:
global klass_count
klass_count += 1
name = 'DynamicAdminClass%d' % klass_count
# clone the admin class
klass = type ( name , ( FancyModelAdmin , ) , { } )
klass . list_display = [ ]
if len ( args ) > 0 :
    klass . add_displays ( * args )
return klass


signature:
def add_display ( cls , attr , title = '' ) :
    """Adds a ` ` list _ display ` ` property without any extra wrappers ,
 similar to : func : ` add _ displays ` , but can also change the title .
 : param attr :
 Name of the attribute to add to the display
 : param title :
 Title for the column of the django admin table . If not given it
 defaults to a capitalized version of ` ` attr ` `"""

implementation:
global klass_count
klass_count += 1
fn_name = 'dyn_fn_%d' % klass_count
cls . list_display . append ( fn_name )
if not title :
    title = attr . capitalize ( )
def _ref ( self , obj ) : # use the django mechanism for field value lookup
    _ , _ , value = lookup_field ( attr , obj , cls )
    return value
_ref . short_description = title
_ref . allow_tags = True
_ref . admin_order_field = attr
setattr ( cls , fn_name , _ref )