signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def arctic_paginate ( parser , token ) :
"""Renders a Page object with pagination bar .
Example : :
{ % arctic _ paginate page _ obj paginator = page _ obj . paginator range = 10 % }
Named Parameters : :
range - The size of the pagination bar ( ie , if set to 10 then , at most ,
10 page numbers will displ... | bits = token . split_contents ( )
if len ( bits ) < 2 :
raise TemplateSyntaxError ( "'%s' takes at least one argument" " (Page object reference)" % bits [ 0 ] )
page = parser . compile_filter ( bits [ 1 ] )
kwargs = { }
bits = bits [ 2 : ]
kwarg_re = re . compile ( r"(\w+)=(.+)" )
if len ( bits ) :
for bit in b... |
def get_pid ( self , name ) :
"""Get PID file name for a named notebook .""" | pid_file = os . path . join ( self . get_work_folder ( name ) , "notebook.pid" )
return pid_file |
def get_filtered_devices ( self , model_name , device_types = "upnp:rootdevice" , timeout = 2 ) :
"""returns a dict of devices that contain the given model name""" | # get list of all UPNP devices in the network
upnp_devices = self . discover_upnp_devices ( st = device_types )
# go through all UPNP devices and filter wanted devices
filtered_devices = collections . defaultdict ( dict )
for dev in upnp_devices . values ( ) :
try : # download XML file with information about the de... |
def _resolve_module_placeholders ( modules , module_name , visit_path , resolved ) :
"""Resolve all placeholder children under a module .
: param modules : A mapping of module names to their data dictionary .
Placeholders are resolved in place .
: type modules : dict ( str , dict )
: param module _ name : T... | if module_name in resolved :
return
visit_path [ module_name ] = True
module , children = modules [ module_name ]
for child in list ( children . values ( ) ) :
if child [ "type" ] != "placeholder" :
continue
if child [ "original_path" ] in modules :
module [ "children" ] . remove ( child )
... |
def index ( self , connection , partition , columns ) :
"""Create an index on the columns .
Args :
connection ( apsw . Connection ) : connection to sqlite database who stores mpr table or view .
partition ( orm . Partition ) :
columns ( list of str ) :""" | import hashlib
query_tmpl = '''
CREATE INDEX IF NOT EXISTS {index_name} ON {table_name} ({columns});
'''
if not isinstance ( columns , ( list , tuple ) ) :
columns = [ columns ]
col_list = ',' . join ( '"{}"' . format ( col ) for col in columns )
col_hash = hashlib . md5 ( col_list ) . hexdigest... |
def _format_class_nodes ( self , task_class ) :
"""Create a ` ` desc ` ` node summarizing the class docstring .""" | # Patterned after PyObject . handle _ signature in Sphinx .
# https : / / github . com / sphinx - doc / sphinx / blob / 3e57ea0a5253ac198c1bff16c40abe71951bb586 / sphinx / domains / python . py # L246
modulename = task_class . __module__
classname = task_class . __name__
fullname = '.' . join ( ( modulename , classname... |
def route ( self , arg , destination = None , waypoints = None , raw = False , ** kwargs ) :
"""Query a route .
route ( locations ) : points can be
- a sequence of locations
- a Shapely LineString
route ( origin , destination , waypoints = None )
- origin and destination are a single destination
- waypo... | points = _parse_points ( arg , destination , waypoints )
if len ( points ) < 2 :
raise ValueError ( 'You must specify at least 2 points' )
self . rate_limit_wait ( )
data = self . raw_query ( points , ** kwargs )
self . _last_query = time . time ( )
if raw :
return data
return self . format_output ( data ) |
def generate_authenticator_response ( password , nt_response , peer_challenge , authenticator_challenge , username ) :
"""GenerateAuthenticatorResponse""" | Magic1 = "\x4D\x61\x67\x69\x63\x20\x73\x65\x72\x76\x65\x72\x20\x74\x6F\x20\x63\x6C\x69\x65\x6E\x74\x20\x73\x69\x67\x6E\x69\x6E\x67\x20\x63\x6F\x6E\x73\x74\x61\x6E\x74"
Magic2 = "\x50\x61\x64\x20\x74\x6F\x20\x6D\x61\x6B\x65\x20\x69\x74\x20\x64\x6F\x20\x6D\x6F\x72\x65\x20\x74\x68\x61\x6E\x20\x6F\x6E\x65\x20\x69\x74\x65\x... |
def find_all_matches ( finder , ireq , pre = False ) : # type : ( PackageFinder , InstallRequirement , bool ) - > List [ InstallationCandidate ]
"""Find all matching dependencies using the supplied finder and the
given ireq .
: param finder : A package finder for discovering matching candidates .
: type finde... | candidates = clean_requires_python ( finder . find_all_candidates ( ireq . name ) )
versions = { candidate . version for candidate in candidates }
allowed_versions = _get_filtered_versions ( ireq , versions , pre )
if not pre and not allowed_versions :
allowed_versions = _get_filtered_versions ( ireq , versions , T... |
def validate_owner_repo_package ( ctx , param , value ) :
"""Ensure that owner / repo / package is formatted correctly .""" | # pylint : disable = unused - argument
form = "OWNER/REPO/PACKAGE"
return validate_slashes ( param , value , minimum = 3 , maximum = 3 , form = form ) |
def get_typeof ( self , name ) :
"""Get the GType of a GObject property .
This function returns 0 if the property does not exist .""" | # logger . debug ( ' VipsObject . get _ typeof : self = % s , name = % s ' ,
# str ( self ) , name )
pspec = self . _get_pspec ( name )
if pspec is None : # need to clear any error , this is horrible
Error ( '' )
return 0
return pspec . value_type |
def get_data_path ( cls ) :
"""Read data path from the following sources in order of priority :
1 . Environment variable
If not found raises an exception
: return : str - datapath""" | marvin_path = os . environ . get ( cls . _key )
if not marvin_path :
raise InvalidConfigException ( 'Data path not set!' )
is_path_created = check_path ( marvin_path , create = True )
if not is_path_created :
raise InvalidConfigException ( 'Data path does not exist!' )
return marvin_path |
def emit_containers ( self , containers , verbose = True ) :
"""Emits the applications and sorts containers by name
: param containers : List of the container definitions
: type containers : list of dict
: param verbose : Print out newlines and indented JSON
: type verbose : bool
: returns : The text outp... | containers = sorted ( containers , key = lambda c : c . get ( 'id' ) )
if len ( containers ) == 1 and isinstance ( containers , list ) :
containers = containers [ 0 ]
if verbose :
return json . dumps ( containers , indent = 4 , sort_keys = True )
else :
return json . dumps ( containers ) |
def generate_unique_slug ( field , instance , slug , manager ) :
"""Generates unique slug by adding a number to given value until no model
instance can be found with such slug . If ` ` unique _ with ` ` ( a tuple of field
names ) was specified for the field , all these fields are included together
in the quer... | original_slug = slug = crop_slug ( field , slug )
default_lookups = tuple ( get_uniqueness_lookups ( field , instance , field . unique_with ) )
index = 1
if not manager :
manager = field . model . _default_manager
# keep changing the slug until it is unique
while True : # find instances with same slug
lookups =... |
def init_mpraw ( mpv , npv ) :
"""Set a global variable as a multiprocessing RawArray in shared
memory with a numpy array wrapper and initialise its value .
Parameters
mpv : string
Name of global variable to set
npv : ndarray
Numpy array to use as initialiser for global variable value""" | globals ( ) [ mpv ] = mpraw_as_np ( npv . shape , npv . dtype )
globals ( ) [ mpv ] [ : ] = npv |
def _update_with_like_args ( ctx , _ , value ) :
"""Update arguments with options taken from a currently running VS .""" | if value is None :
return
env = ctx . ensure_object ( environment . Environment )
vsi = SoftLayer . VSManager ( env . client )
vs_id = helpers . resolve_id ( vsi . resolve_ids , value , 'VS' )
like_details = vsi . get_instance ( vs_id )
like_args = { 'hostname' : like_details [ 'hostname' ] , 'domain' : like_detail... |
def check_indexes ( self ) :
"""Check if the indexes exists""" | for collection_name in INDEXES :
existing_indexes = self . indexes ( collection_name )
indexes = INDEXES [ collection_name ]
for index in indexes :
index_name = index . document . get ( 'name' )
if not index_name in existing_indexes :
logger . warning ( "Index {0} missing. Run co... |
def set ( self , name , value , domain , ** kwargs ) :
"""Add new cookie or replace existing cookie with same parameters .
: param name : name of cookie
: param value : value of cookie
: param kwargs : extra attributes of cookie""" | if domain == 'localhost' :
domain = ''
self . cookiejar . set_cookie ( create_cookie ( name , value , domain , ** kwargs ) ) |
def display_queries ( request , stats , queries ) :
"""Generate a HttpResponse of SQL queries for a profiling run .
_ stats _ should contain a pstats . Stats of a hotshot session .
_ queries _ should contain a list of SQL queries .""" | sort = request . REQUEST . get ( 'sort_by' , 'time' )
sort_buttons = RadioButtons ( 'sort_by' , sort , ( ( 'order' , 'by order' ) , ( 'time' , 'time' ) , ( 'queries' , 'query count' ) ) )
output = render_queries ( queries , sort )
output . reset ( )
output = [ html . escape ( unicode ( line ) ) for line in output . rea... |
def run ( self , start_point = None , stop_before = None , stop_after = None ) :
"""Run the pipeline , optionally specifying start and / or stop points .
: param str start _ point : Name of stage at which to begin execution .
: param str stop _ before : Name of stage at which to cease execution ;
exclusive , ... | # Start the run with a clean slate of Stage status / label tracking .
self . _reset ( )
# TODO : validate starting point against checkpoint flags for
# TODO ( cont . ) : earlier stages if the pipeline defines its stages as a
# TODO ( cont . ) : sequence ( i . e . , probably prohibit start point with
# TODO ( cont ) : n... |
def find_first_stop_codon ( nucleotide_sequence ) :
"""Given a sequence of codons ( expected to have length multiple of three ) ,
return index of first stop codon , or - 1 if none is in the sequence .""" | n_mutant_codons = len ( nucleotide_sequence ) // 3
for i in range ( n_mutant_codons ) :
codon = nucleotide_sequence [ 3 * i : 3 * i + 3 ]
if codon in STOP_CODONS :
return i
return - 1 |
def _main ( ) :
"""A simple demo to be used from command line .""" | import sys
def log ( message ) :
print ( message )
def print_usage ( ) :
log ( 'usage: %s <application key> <application secret> send <number> <message> <from_number>' % sys . argv [ 0 ] )
log ( ' %s <application key> <application secret> status <message_id>' % sys . argv [ 0 ] )
if len ( sys . argv )... |
def dumb_css_parser ( data ) :
"""returns a hash of css selectors , each of which contains a hash of css attributes""" | # remove @ import sentences
data += ';'
importIndex = data . find ( '@import' )
while importIndex != - 1 :
data = data [ 0 : importIndex ] + data [ data . find ( ';' , importIndex ) + 1 : ]
importIndex = data . find ( '@import' )
# parse the css . reverted from dictionary compehension in order to support older ... |
def remove_folder ( self , tree , prefix ) :
"""Used to remove any empty folders
If this folder is empty then it is removed . If the parent is empty as a
result , then the parent is also removed , and so on .""" | while True :
child = tree
tree = tree . parent
if not child . folders and not child . files :
del self . cache [ tuple ( prefix ) ]
if tree :
del tree . folders [ prefix . pop ( ) ]
if not tree or tree . folders or tree . files :
break |
def _check_for_pending ( self , * args , ** kwargs ) :
"""Checks if a notification is pending .""" | if self . _notification_pending and not self . _processing :
self . _processing = True
args , kwargs = self . _data
self . _notify ( * args , ** kwargs )
self . _notification_pending = False
self . _processing = False |
def grouper ( iterable , n ) :
"""Slice up ` iterable ` into iterables of ` n ` items .
: param iterable : Iterable to splice .
: param n : Number of items per slice .
: returns : iterable of iterables""" | it = iter ( iterable )
while True :
chunk = itertools . islice ( it , n )
try :
first = next ( chunk )
except StopIteration :
return
yield itertools . chain ( [ first ] , chunk ) |
def htmlDocContentDumpFormatOutput ( self , cur , encoding , format ) :
"""Dump an HTML document .""" | if cur is None :
cur__o = None
else :
cur__o = cur . _o
libxml2mod . htmlDocContentDumpFormatOutput ( self . _o , cur__o , encoding , format ) |
def to_indra_statements ( graph ) :
"""Export this graph as a list of INDRA statements using the : py : class : ` indra . sources . pybel . PybelProcessor ` .
: param pybel . BELGraph graph : A BEL graph
: rtype : list [ indra . statements . Statement ]""" | from indra . sources . bel import process_pybel_graph
pbp = process_pybel_graph ( graph )
return pbp . statements |
def log_init ( level ) :
"""Set up a logger that catches all channels and logs it to stdout .
This is used to set up logging when testing .""" | log = logging . getLogger ( )
hdlr = logging . StreamHandler ( )
formatter = logging . Formatter ( '%(asctime)s %(name)s %(levelname)s %(message)s' )
hdlr . setFormatter ( formatter )
log . addHandler ( hdlr )
log . setLevel ( level ) |
def do_request ( self , request , proxies , timeout , ** _ ) :
"""Dispatch the actual request and return the result .""" | print ( '{0} {1}' . format ( request . method , request . url ) )
response = self . http . send ( request , proxies = proxies , timeout = timeout , allow_redirects = False )
response . raw = None
# Make pickleable
return response |
def start ( self ) :
"""Start the background thread and begin consuming the thread .""" | with self . _operational_lock :
ready = threading . Event ( )
thread = threading . Thread ( name = _BIDIRECTIONAL_CONSUMER_NAME , target = self . _thread_main , args = ( ready , ) )
thread . daemon = True
thread . start ( )
# Other parts of the code rely on ` thread . is _ alive ` which
# isn ' ... |
def _get_datacenter_name ( ) :
'''Returns the datacenter name configured on the proxy
Supported proxies : esxcluster , esxdatacenter''' | proxy_type = __salt__ [ 'vsphere.get_proxy_type' ] ( )
details = None
if proxy_type == 'esxcluster' :
details = __salt__ [ 'esxcluster.get_details' ] ( )
elif proxy_type == 'esxdatacenter' :
details = __salt__ [ 'esxdatacenter.get_details' ] ( )
if not details :
raise salt . exceptions . CommandExecutionErr... |
def check_web_config ( config_fname ) :
'''Try to load the Django settings .
If this does not work , than settings file does not exist .
Returns :
Loaded configuration , or None .''' | print ( "Looking for config file at {0} ..." . format ( config_fname ) )
config = RawConfigParser ( )
try :
config . readfp ( open ( config_fname ) )
return config
except IOError :
print ( "ERROR: Seems like the config file does not exist. Please call 'opensubmit-web configcreate' first, or specify a locati... |
def zlexcount ( self , name , min , max ) :
"""Return the number of items in the sorted set between the
lexicographical range ` ` min ` ` and ` ` max ` ` .
: param name : str the name of the redis key
: param min : int or ' - inf '
: param max : int or ' + inf '
: return : Future ( )""" | with self . pipe as pipe :
return pipe . zlexcount ( self . redis_key ( name ) , min , max ) |
def pairwise ( iterable ) :
"""Pair each element with its neighbors .
Arguments
iterable : iterable
Returns
The generator produces a tuple containing a pairing of each element with
its neighbor .""" | iterable = iter ( iterable )
left = next ( iterable )
for right in iterable :
yield left , right
left = right |
def setHoverForeground ( self , column , brush ) :
"""Returns the brush to use when coloring when the user hovers over
the item for the given column .
: param column | < int >
brush | < QtGui . QBrush >""" | self . _hoverForeground [ column ] = QtGui . QBrush ( brush ) |
def flush ( table = 'filter' , chain = '' , family = 'ipv4' ) :
'''Flush the chain in the specified table , flush all chains in the specified
table if not specified chain .
CLI Example :
. . code - block : : bash
salt ' * ' iptables . flush filter INPUT
IPv6:
salt ' * ' iptables . flush filter INPUT fam... | wait = '--wait' if _has_option ( '--wait' , family ) else ''
cmd = '{0} {1} -t {2} -F {3}' . format ( _iptables_cmd ( family ) , wait , table , chain )
out = __salt__ [ 'cmd.run' ] ( cmd )
return out |
def get_search_index_for ( catalog ) :
"""Returns the search index to query""" | searchable_text_index = "SearchableText"
listing_searchable_text_index = "listing_searchable_text"
if catalog == CATALOG_ANALYSIS_REQUEST_LISTING :
tool = api . get_tool ( catalog )
indexes = tool . indexes ( )
if listing_searchable_text_index in indexes :
return listing_searchable_text_index
return... |
def _copy_attachment ( self , name , data , mimetype , mfg_event ) :
"""Copies an attachment to mfg _ event .""" | attachment = mfg_event . attachment . add ( )
attachment . name = name
if isinstance ( data , unicode ) :
data = data . encode ( 'utf8' )
attachment . value_binary = data
if mimetype in test_runs_converter . MIMETYPE_MAP :
attachment . type = test_runs_converter . MIMETYPE_MAP [ mimetype ]
elif mimetype == test... |
def get_queryset ( self ) :
"""Returns a queryset of all executive offices holding an election on
a date .""" | try :
date = ElectionDay . objects . get ( date = self . kwargs [ 'date' ] )
except Exception :
raise APIException ( 'No elections on {}.' . format ( self . kwargs [ 'date' ] ) )
office_ids = [ ]
for election in date . elections . all ( ) :
office = election . race . office
if not office . body :
... |
def _patch_argument_parser ( self ) :
'''Since argparse doesn ' t support much introspection , we monkey - patch it to replace the parse _ known _ args method and
all actions with hooks that tell us which action was last taken or about to be taken , and let us have the parser
figure out which subparsers need to... | active_parsers = [ self . _parser ]
parsed_args = argparse . Namespace ( )
visited_actions = [ ]
def patch ( parser ) :
parser . __class__ = IntrospectiveArgumentParser
for action in parser . _actions : # TODO : accomplish this with super
class IntrospectAction ( action . __class__ ) :
def _... |
def get_processor_name ( ) :
"""Returns the processor name in the system""" | if platform . system ( ) == "Linux" :
with open ( "/proc/cpuinfo" , "rb" ) as cpuinfo :
all_info = cpuinfo . readlines ( )
for line in all_info :
if b'model name' in line :
return re . sub ( b'.*model name.*:' , b'' , line , 1 )
return platform . processor ( ) |
def mark ( self ) :
"""Mark the unit of work as failed in the database and update the listener
so as to skip it next time .""" | self . reliableListener . lastRun = extime . Time ( )
BatchProcessingError ( store = self . reliableListener . store , processor = self . reliableListener . processor , listener = self . reliableListener . listener , item = self . workUnit , error = self . failure . getErrorMessage ( ) ) |
def query_get_user_contact_info ( uid ) :
"""Get the user contact information
: return : tuple ( nickname , email , last _ login ) , if none found return ( )
Note : for the moment , if no nickname , will return email address up to the ' : '""" | # FIXME compatibility with postgresql
query1 = """SELECT nickname, email,
""" + datetime_format ( 'last_login' ) + """
FROM "user" WHERE id=%s"""
params1 = ( uid , )
res1 = run_sql ( query1 , params1 )
if res1 :
return res1 [ 0 ]
else :
return ( ) |
def _accept ( self , listen_socket ) :
"""Accept new incoming connection .""" | conn , addr = listen_socket . accept ( )
connection = TelnetConnection ( conn , addr , self . application , self , encoding = self . encoding )
self . connections . add ( connection )
logger . info ( 'New connection %r %r' , * addr ) |
def build_ingest_fs ( self ) :
"""Return a pyfilesystem subdirectory for the ingested source files""" | base_path = 'ingest'
if not self . build_fs . exists ( base_path ) :
self . build_fs . makedir ( base_path , recursive = True , allow_recreate = True )
return self . build_fs . opendir ( base_path ) |
def file_decrypt ( blockchain_id , hostname , sender_blockchain_id , sender_key_id , input_path , output_path , passphrase = None , config_path = CONFIG_PATH , wallet_keys = None ) :
"""Decrypt a file from a sender ' s blockchain ID .
Try our current key , and then the old keys
( but warn if there are revoked k... | config_dir = os . path . dirname ( config_path )
decrypted = False
old_key = False
old_key_index = 0
sender_old_key_index = 0
# get the sender key
sender_key_info = file_key_lookup ( sender_blockchain_id , None , None , key_id = sender_key_id , config_path = config_path , wallet_keys = wallet_keys )
if 'error' in sende... |
def setBehavior ( self , behavior , cascade = True ) :
"""Set behavior . If cascade is True , autoBehavior all descendants .""" | self . behavior = behavior
if cascade :
for obj in self . getChildren ( ) :
obj . parentBehavior = behavior
obj . autoBehavior ( True ) |
def merge_true_table ( ) :
"""Merge all true table into single excel file .""" | writer = pd . ExcelWriter ( "True Table.xlsx" )
for p in Path ( __file__ ) . parent . select_by_ext ( ".csv" ) :
df = pd . read_csv ( p . abspath , index_col = 0 )
df . to_excel ( writer , p . fname , index = True )
writer . save ( ) |
def add_ref ( self , name , ref ) :
"""Add a reference for the backend object that gives access
to the low level context . Used in vispy . app . canvas . backends .
The given name must match with that of previously added
references .""" | if self . _name is None :
self . _name = name
elif name != self . _name :
raise RuntimeError ( 'Contexts can only share between backends of ' 'the same type' )
self . _refs . append ( weakref . ref ( ref ) ) |
def parse_singular_alphabetic_character ( t , tag_name ) :
'''Parses the sole alphabetic character value with name tag _ name in tag t . Heavy - handed with the asserts .''' | pos = t . getElementsByTagName ( tag_name )
assert ( len ( pos ) == 1 )
pos = pos [ 0 ]
assert ( len ( pos . childNodes ) == 1 )
v = pos . childNodes [ 0 ] . data
assert ( len ( v ) == 1 and v >= 'A' and 'v' <= 'z' )
# no floats allowed
return v |
def get_path ( ) :
"""Shortcut for users whose theme is next to their conf . py .""" | # Theme directory is defined as our parent directory
return os . path . abspath ( os . path . dirname ( os . path . dirname ( __file__ ) ) ) |
def _regexp ( expr , item ) :
'''REGEXP function for Sqlite''' | reg = re . compile ( expr )
return reg . search ( item ) is not None |
def resolve_pointer ( self , document , pointer ) :
"""Resolve a json pointer ` ` pointer ` ` within the referenced ` ` document ` ` .
: argument document : the referent document
: argument str pointer : a json pointer URI fragment to resolve within it""" | # Do only split at single forward slashes which are not prefixed by a caret
parts = re . split ( r"(?<!\^)/" , unquote ( pointer . lstrip ( "/" ) ) ) if pointer else [ ]
for part in parts : # Restore escaped slashes and carets
replacements = { r"^/" : r"/" , r"^^" : r"^" }
part = re . sub ( "|" . join ( re . es... |
def invoke ( self , dirname , filenames = set ( ) , linter_configs = set ( ) ) :
"""Main entrypoint for all plugins .
Returns results in the format of :
{ ' filename ' : {
' line _ number ' : [
' error1 ' ,
' error2'""" | retval = defaultdict ( lambda : defaultdict ( list ) )
if len ( filenames ) :
extensions = [ e . lstrip ( '.' ) for e in self . get_file_extensions ( ) ]
filenames = [ f for f in filenames if f . split ( '.' ) [ - 1 ] in extensions ]
if not filenames : # There were a specified set of files , but none were t... |
def sync ( self ) :
"""Retrieve zones from ElkM1""" | self . elk . send ( az_encode ( ) )
self . elk . send ( zd_encode ( ) )
self . elk . send ( zp_encode ( ) )
self . elk . send ( zs_encode ( ) )
self . get_descriptions ( TextDescriptions . ZONE . value ) |
def get_inframe_gap ( seq , nucs_needed = 3 ) :
"""This funtion takes a sequnece starting with a gap or the complementary
seqeuence to the gap , and the number of nucleotides that the seqeunce
should contain in order to maintain the correct reading frame . The
sequence is gone through and the number of non - ... | nuc_count = 0
gap_indel = ""
nucs = ""
for i in range ( len ( seq ) ) : # Check if the character is not a gap
if seq [ i ] != "-" : # Check if the indel is a ' clean '
# i . e . if the insert or deletion starts at the first nucleotide in the codon and can be divided by 3
if gap_indel . count ( "-" ) == ... |
def buy ( self , player , cost ) :
"""indicate that the player was bought at the specified cost
: param Player player : player to buy
: param int cost : cost to pay
: raises InsufficientFundsError : if owner doesn ' t have the money
: raises NoValidRosterSlotError : if owner doesn ' t have a slot this playe... | if cost > self . max_bid ( ) :
raise InsufficientFundsError ( )
elif not any ( roster_slot . accepts ( player ) and roster_slot . occupant is None for roster_slot in self . roster ) :
raise NoValidRosterSlotError ( )
elif self . owns ( player ) :
raise AlreadyPurchasedError ( )
self . money -= cost
self . _... |
def remove_mediators ( tree , columns ) :
"""Removes intermediate nodes that are just mediators between their parent and child states .
: param columns : list of characters
: param tree : ete3 . Tree
: return : void , modifies the input tree""" | num_removed = 0
for n in tree . traverse ( 'postorder' ) :
if getattr ( n , METACHILD , False ) or n . is_leaf ( ) or len ( n . children ) > 1 or n . is_root ( ) or getattr ( n , NUM_TIPS_INSIDE ) > 0 :
continue
parent = n . up
child = n . children [ 0 ]
compatible = True
for column in colum... |
def traverse ( self , startVertex , ** kwargs ) :
"""Traversal ! see : https : / / docs . arangodb . com / HttpTraversal / README . html for a full list of the possible kwargs .
The function must have as argument either : direction = " outbout " / " any " / " inbound " or expander = " custom JS ( see arangodb ' s... | url = "%s/traversal" % self . database . URL
if type ( startVertex ) is DOC . Document :
startVertex_id = startVertex . _id
else :
startVertex_id = startVertex
payload = { "startVertex" : startVertex_id , "graphName" : self . name }
if "expander" in kwargs :
if "direction" in kwargs :
raise ValueErr... |
def frame ( self , action ) :
'''Places / removes frame around text
Args :
action - - Enable or disable frame . Options are ' on ' and ' off '
Returns :
None
Raises :
RuntimeError : Invalid action .''' | choices = { 'on' : '1' , 'off' : '0' }
if action in choices :
self . send ( chr ( 27 ) + 'if' + choices [ action ] )
else :
raise RuntimeError ( 'Invalid action for function frame, choices are on and off' ) |
def cooccurrence ( corpus_or_featureset , featureset_name = None , min_weight = 1 , edge_attrs = [ 'ayjid' , 'date' ] , filter = None ) :
"""A network of feature elements linked by their joint occurrence in papers .""" | if not filter :
filter = lambda f , v , c , dc : dc >= min_weight
featureset = _get_featureset ( corpus_or_featureset , featureset_name )
if type ( corpus_or_featureset ) in [ Corpus , StreamingCorpus ] :
attributes = { i : { a : corpus_or_featureset . indices_lookup [ i ] [ a ] for a in edge_attrs } for i in c... |
def _Purge ( self , event , by_tags ) :
"""Purge all events that have occurred after the given event . step .
If by _ tags is True , purge all events that occurred after the given
event . step , but only for the tags that the event has . Non - sequential
event . steps suggest that a TensorFlow restart occurre... | # # Keep data in reservoirs that has a step less than event . step
_NotExpired = lambda x : x . step < event . step
num_expired = 0
if by_tags :
for value in event . summary . value :
if value . tag in self . tensors_by_tag :
tag_reservoir = self . tensors_by_tag [ value . tag ]
num_... |
def collect_assets ( result , force = False ) :
"""collect assets from meta file
Collecting assets only when the metafile is updated . If number of assets
are decreased , assets are reset and re - collect the assets .""" | path_name = result . path_name
info_path = os . path . join ( path_name , summary . CHAINERUI_ASSETS_METAFILE_NAME )
if not os . path . isfile ( info_path ) :
return
start_idx = len ( result . assets )
file_modified_at = datetime . datetime . fromtimestamp ( os . path . getmtime ( info_path ) )
if start_idx > 0 :
... |
def entity ( self , entity_type , identifier = None ) :
"""Factory method for creating an Entity .
If an entity with the same type and identifier already exists ,
this will return a reference to that entity . If not , it will
create a new one and add it to the list of known entities for
this ACL .
: type ... | entity = _ACLEntity ( entity_type = entity_type , identifier = identifier )
if self . has_entity ( entity ) :
entity = self . get_entity ( entity )
else :
self . add_entity ( entity )
return entity |
def get_path ( item ) :
"""Gets a path from an Labelled object or from a tuple of an existing
path and a labelled object . The path strings are sanitized and
capitalized .""" | sanitizers = [ group_sanitizer , label_sanitizer ]
if isinstance ( item , tuple ) :
path , item = item
if item . label :
if len ( path ) > 1 and item . label == path [ 1 ] :
path = path [ : 2 ]
else :
path = path [ : 1 ] + ( item . label , )
else :
path = path... |
def numDomtblout ( domtblout , numHits , evalueT , bitT , sort ) :
"""parse hmm domain table output
this version is faster but does not work unless the table is sorted""" | if sort is True :
for hit in numDomtblout_sort ( domtblout , numHits , evalueT , bitT ) :
yield hit
return
header = [ '#target name' , 'target accession' , 'tlen' , 'query name' , 'query accession' , 'qlen' , 'full E-value' , 'full score' , 'full bias' , 'domain #' , '# domains' , 'domain c-Evalue' , 'd... |
def enqueue_message ( self , message , timeout ) :
"""Add the given message to this transport ' s queue .
This method also handles ACKing any WRTE messages .
Args :
message : The AdbMessage to enqueue .
timeout : The timeout to use for the operation . Specifically , WRTE
messages cause an OKAY to be sent ... | # Ack WRTE messages immediately , handle our OPEN ack if it gets enqueued .
if message . command == 'WRTE' :
self . _send_command ( 'OKAY' , timeout = timeout )
elif message . command == 'OKAY' :
self . _set_or_check_remote_id ( message . arg0 )
self . message_queue . put ( message ) |
def parse_line ( line ) :
"""Parses a line of a text embedding file .
Args :
line : ( str ) One line of the text embedding file .
Returns :
A token string and its embedding vector in floats .""" | columns = line . split ( )
token = columns . pop ( 0 )
values = [ float ( column ) for column in columns ]
return token , values |
def cftime_to_timestamp ( date , time_unit = 'us' ) :
"""Converts cftime to timestamp since epoch in milliseconds
Non - standard calendars ( e . g . Julian or no leap calendars )
are converted to standard Gregorian calendar . This can cause
extra space to be added for dates that don ' t exist in the original ... | import cftime
utime = cftime . utime ( 'microseconds since 1970-01-01 00:00:00' )
if time_unit == 'us' :
tscale = 1
else :
tscale = ( np . timedelta64 ( 1 , 'us' ) / np . timedelta64 ( 1 , time_unit ) )
return utime . date2num ( date ) * tscale |
def from_rational ( cls , value , to_base , precision = None , method = RoundingMethods . ROUND_DOWN ) :
"""Convert rational value to a base .
: param Rational value : the value to convert
: param int to _ base : base of result , must be at least 2
: param precision : number of digits in total or None
: typ... | # pylint : disable = too - many - locals
if to_base < 2 :
raise BasesValueError ( to_base , "to_base" , "must be at least 2" )
if precision is not None and precision < 0 :
raise BasesValueError ( precision , "precision" , "must be at least 0" )
if value == 0 :
non_repeating_part = [ ] if precision is None e... |
def fitted_parameters ( self ) :
"""A tuple of fitted values for the ` scipy _ data _ fitting . Fit . fitting _ parameters ` .
The values in this tuple are not scaled by the prefix ,
as they are passed back to ` scipy _ data _ fitting . Fit . function ` ,
e . g . in most standard use cases these would be the ... | if hasattr ( self , '_fitted_parameters' ) :
return self . _fitted_parameters
if not self . fitting_parameters :
return tuple ( )
if self . options [ 'fit_function' ] == 'lmfit' :
return tuple ( self . curve_fit . params [ key ] . value for key in sorted ( self . curve_fit . params ) )
else :
return tup... |
def get_args ( parser ) :
"""Converts arguments extracted from a parser to a dict ,
and will dismiss arguments which default to NOT _ SET .
: param parser : an ` ` argparse . ArgumentParser ` ` instance .
: type parser : argparse . ArgumentParser
: return : Dictionary with the configs found in the parsed CL... | args = vars ( parser . parse_args ( ) ) . items ( )
return { key : val for key , val in args if not isinstance ( val , NotSet ) } |
def has_address ( self , address ) :
"""is the given address on the don ' t send list ?""" | queryset = self . filter ( to_address__iexact = address )
return queryset . exists ( ) |
def add_configuration_file ( self , file_name ) :
'''Register a file path from which to read parameter values .
This method can be called multiple times to register multiple files for
querying . Files are expected to be ` ` ini ` ` formatted .
No assumptions should be made about the order that the registered ... | logger . info ( 'adding %s to configuration files' , file_name )
if file_name not in self . configuration_files and self . _inotify :
self . _watch_manager . add_watch ( file_name , pyinotify . IN_MODIFY )
if os . access ( file_name , os . R_OK ) :
self . configuration_files [ file_name ] = SafeConfigParser ( )... |
def Process ( cls , host_data , os_name = None , cpe = None , labels = None , exclude_checks = None , restrict_checks = None ) :
"""Runs checks over all host data .
Args :
host _ data : The data collected from a host , mapped to artifact name .
os _ name : 0 + OS names .
cpe : 0 + CPE identifiers .
labels... | # All the conditions that apply to this host .
artifacts = list ( iterkeys ( host_data ) )
check_ids = cls . FindChecks ( artifacts , os_name , cpe , labels )
conditions = list ( cls . Conditions ( artifacts , os_name , cpe , labels ) )
for check_id in check_ids : # skip if check in list of excluded checks
if exclu... |
def access_token_endpoint ( request ) :
"""Generates : py : class : ` djoauth2 . models . AccessTokens ` if provided with
sufficient authorization .
This endpoint only supports two grant types :
* ` ` authorization _ code ` ` : http : / / tools . ietf . org / html / rfc6749 # section - 4.1
* ` ` refresh _ t... | # TODO ( peter ) : somehow implement the anti - brute - force requirement specified
# by http : / / tools . ietf . org / html / rfc6749 # section - 2.3.1 :
# Since this client authentication method involves a password , the
# authorization server MUST protect any endpoint utilizing it against
# brute force attacks .
tr... |
def json_normalize ( data , record_path = None , meta = None , meta_prefix = None , record_prefix = None , errors = 'raise' , sep = '.' ) :
"""Normalize semi - structured JSON data into a flat table .
Parameters
data : dict or list of dicts
Unserialized JSON objects
record _ path : string or list of strings... | def _pull_field ( js , spec ) :
result = js
if isinstance ( spec , list ) :
for field in spec :
result = result [ field ]
else :
result = result [ spec ]
return result
if isinstance ( data , list ) and not data :
return DataFrame ( )
# A bit of a hackjob
if isinstance ( d... |
def clone ( self , data = None , shared_data = True , new_type = None , link = True , * args , ** overrides ) :
"""Clones the object , overriding data and parameters .
Args :
data : New data replacing the existing data
shared _ data ( bool , optional ) : Whether to use existing data
new _ type ( optional ) ... | if 'link_inputs' in overrides and util . config . future_deprecations :
self . param . warning ( 'link_inputs argument to the clone method is deprecated, ' 'use the more general link argument instead.' )
link = link and overrides . pop ( 'link_inputs' , True )
callback = overrides . pop ( 'callback' , self . callba... |
def paper_format_efficiency_gain_df ( eff_gain_df ) :
"""Transform efficiency gain data frames output by nestcheck into the
format shown in the dynamic nested sampling paper ( Higson et al . 2019 ) .
Parameters
eff _ gain _ df : pandas DataFrame
DataFrame of the from produced by efficiency _ gain _ df .
R... | idxs = pd . IndexSlice [ [ 'std' , 'std efficiency gain' ] , : , : ]
paper_df = copy . deepcopy ( eff_gain_df . loc [ idxs , : ] )
# Show mean number of samples and likelihood calls instead of st dev
means = ( eff_gain_df . xs ( 'mean' , level = 'calculation type' ) . xs ( 'value' , level = 'result type' ) )
for col in... |
def images ( self ) :
"""( : class : ` productmd . images . Images ` ) - - Compose images metadata""" | if self . _images is not None :
return self . _images
paths = [ "metadata/images.json" , "metadata/image-manifest.json" , ]
self . _images = self . _load_metadata ( paths , productmd . images . Images )
return self . _images |
def mount_status_encode ( self , target_system , target_component , pointing_a , pointing_b , pointing_c ) :
'''Message with some status from APM to GCS about camera or antenna mount
target _ system : System ID ( uint8 _ t )
target _ component : Component ID ( uint8 _ t )
pointing _ a : pitch ( deg * 100 ) ( ... | return MAVLink_mount_status_message ( target_system , target_component , pointing_a , pointing_b , pointing_c ) |
def update_store_credit_by_id ( cls , store_credit_id , store_credit , ** kwargs ) :
"""Update StoreCredit
Update attributes of StoreCredit
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . update _ store _ credit _... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _update_store_credit_by_id_with_http_info ( store_credit_id , store_credit , ** kwargs )
else :
( data ) = cls . _update_store_credit_by_id_with_http_info ( store_credit_id , store_credit , ** kwargs )
return data |
def from_df ( cls , df ) :
"""Creates an OrbitPopulation from a DataFrame .
: param df :
: class : ` pandas . DataFrame ` object . Must contain the following
columns : ` ` [ ' M1 ' , ' M2 ' , ' P ' , ' ecc ' , ' mean _ anomaly ' , ' obsx ' , ' obsy ' , ' obsz ' ] ` ` ,
i . e . , as what is accessed via : at... | return cls ( df [ 'M1' ] , df [ 'M2' ] , df [ 'P' ] , ecc = df [ 'ecc' ] , mean_anomaly = df [ 'mean_anomaly' ] , obsx = df [ 'obsx' ] , obsy = df [ 'obsy' ] , obsz = df [ 'obsz' ] ) |
def set_json ( self , json ) :
"""Set all attributes based on JSON response .""" | import time
if 'access_token' in json :
self . access_token = json [ 'access_token' ]
self . refresh_token = json [ 'refresh_token' ]
self . expires_in = json [ 'expires_in' ]
if 'authenticated' in json :
self . authenticated = json [ 'authenticated' ]
else :
self . authenticated = t... |
def open ( self ) :
"""Opens the file for subsequent access .""" | if self . handle is None :
self . handle = fits . open ( self . fname , mode = 'readonly' )
if self . extn :
if len ( self . extn ) == 1 :
hdu = self . handle [ self . extn [ 0 ] ]
else :
hdu = self . handle [ self . extn [ 0 ] , self . extn [ 1 ] ]
else :
hdu = self . handle [ 0 ]
if is... |
def delete ( self , ids ) :
"""Method to delete vip ' s by their id ' s
: param ids : Identifiers of vip ' s
: return : None""" | url = build_uri_with_ids ( 'api/v3/vip-request/%s/' , ids )
return super ( ApiVipRequest , self ) . delete ( url ) |
def validateDtd ( self , doc , dtd ) :
"""Try to validate the document against the dtd instance
Basically it does check all the definitions in the DtD .
Note the the internal subset ( if present ) is de - coupled
( i . e . not used ) , which could give problems if ID or IDREF
is present .""" | if doc is None :
doc__o = None
else :
doc__o = doc . _o
if dtd is None :
dtd__o = None
else :
dtd__o = dtd . _o
ret = libxml2mod . xmlValidateDtd ( self . _o , doc__o , dtd__o )
return ret |
def generate_data ( path , tokenizer , char_vcb , word_vcb , is_training = False ) :
'''Generate data''' | global root_path
qp_pairs = data . load_from_file ( path = path , is_training = is_training )
tokenized_sent = 0
# qp _ pairs = qp _ pairs [ : 1000]1
for qp_pair in qp_pairs :
tokenized_sent += 1
data . tokenize ( qp_pair , tokenizer , is_training )
for word in qp_pair [ 'question_tokens' ] :
word_v... |
def render_to_image_file ( self , image_out_path , width_pixels = None , height_pixels = None , dpi = 90 ) :
"""Render the SubjectInfo to an image file .
Args :
image _ out _ path : str
Path to where image image will be written . Valid extensions are
` ` . svg , ` ` ` ` . pdf ` ` , and ` ` . png ` ` .
wid... | self . _render_type = "file"
self . _tree . render ( file_name = image_out_path , w = width_pixels , h = height_pixels , dpi = dpi , units = "px" , tree_style = self . _get_tree_style ( ) , ) |
def start ( self ) :
"""Start the sensor .""" | if rospy . get_name ( ) == '/unnamed' :
raise ValueError ( 'PhoXi sensor must be run inside a ros node!' )
# Connect to the cameras
if not self . _connect_to_sensor ( ) :
self . _running = False
return False
# Set up subscribers for camera data
self . _color_im_sub = rospy . Subscriber ( '/phoxi_camera/text... |
def to_dms ( angle , style = 'dms' ) :
"""Convert decimal angle to degrees , minutes and possibly seconds .
Args :
angle ( float ) : Angle to convert
style ( str ) : Return fractional or whole minutes values
Returns :
tuple of int : Angle converted to degrees , minutes and possibly seconds
Raises :
Va... | sign = 1 if angle >= 0 else - 1
angle = abs ( angle ) * 3600
minutes , seconds = divmod ( angle , 60 )
degrees , minutes = divmod ( minutes , 60 )
if style == 'dms' :
return tuple ( sign * abs ( i ) for i in ( int ( degrees ) , int ( minutes ) , seconds ) )
elif style == 'dm' :
return tuple ( sign * abs ( i ) f... |
def get_article ( self , url = None , article_id = None , max_pages = 25 ) :
"""Send a GET request to the ` parser ` endpoint of the parser API to get
back the representation of an article .
The article can be identified by either a URL or an id that exists
in Readability .
Note that either the ` url ` or `... | query_params = { }
if url is not None :
query_params [ 'url' ] = url
if article_id is not None :
query_params [ 'article_id' ] = article_id
query_params [ 'max_pages' ] = max_pages
url = self . _generate_url ( 'parser' , query_params = query_params )
return self . get ( url ) |
def get_jids ( ) :
'''Return a dict mapping all job ids to job information''' | serv = _get_serv ( ret = None )
ret = { }
for s in serv . mget ( serv . keys ( 'load:*' ) ) :
if s is None :
continue
load = salt . utils . json . loads ( s )
jid = load [ 'jid' ]
ret [ jid ] = salt . utils . jid . format_jid_instance ( jid , load )
return ret |
def list_wegsegmenten_by_straat ( self , straat ) :
'''List all ` wegsegmenten ` in a : class : ` Straat `
: param straat : The : class : ` Straat ` for which the ` wegsegmenten ` are wanted .
: rtype : A : class : ` list ` of : class : ` Wegsegment `''' | try :
id = straat . id
except AttributeError :
id = straat
def creator ( ) :
res = crab_gateway_request ( self . client , 'ListWegsegmentenByStraatnaamId' , id )
try :
return [ Wegsegment ( r . IdentificatorWegsegment , r . StatusWegsegment ) for r in res . WegsegmentItem ]
except AttributeE... |
def vgcsUplinkGrant ( ) :
"""VGCS UPLINK GRANT Section 9.1.49""" | a = TpPd ( pd = 0x6 )
b = MessageType ( mesType = 0x9 )
# 00001001
c = RrCause ( )
d = RequestReference ( )
e = TimingAdvance ( )
packet = a / b / c / d / e
return packet |
def blocks_from_ops ( ops ) :
"""Group a list of : class : ` Op ` and : class : ` Label ` instances by label .
Everytime a label is found , a new : class : ` Block ` is created . The resulting
blocks are returned as a dictionary to easily access the target block of a
jump operation . The keys of this dictiona... | blocks = { }
current_block = blocks [ None ] = Block ( )
for op in ops :
if isinstance ( op , Label ) :
next_block = blocks [ op ] = Block ( op )
current_block . next = next_block
current_block = next_block
continue
current_block . ops . append ( op )
return blocks |
def clean_markdown ( text ) :
"""Parse markdown sintaxt to html .""" | result = text
if isinstance ( text , str ) :
result = '' . join ( BeautifulSoup ( markdown ( text ) , 'lxml' ) . findAll ( text = True ) )
return result |
def blast ( request , blast_form , template_init , template_result , blast_commandline , sample_fasta_path , extra_context = None ) :
"""Process blastn / tblastn ( blast + ) query or set up initial blast form .""" | if request . method == 'POST' :
form = blast_form ( request . POST )
if form . is_valid ( ) :
query_file_object_tmp = form . cleaned_data [ 'sequence_in_form' ]
evalue = float ( form . cleaned_data [ 'evalue_in_form' ] )
word_size = int ( form . cleaned_data [ 'word_size_in_form' ] )
... |
def _lock ( self ) :
'''Locks , or returns False if already locked''' | if not self . _is_locked ( ) :
with open ( self . _lck , 'w' ) as fh :
if self . _devel :
self . logger . debug ( "Locking" )
fh . write ( str ( os . getpid ( ) ) )
return True
else :
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.