signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def before_update ( self , context , current , resource ) :
"""If the resource has changed we try to generate a budget data
package , but if it hasn ' t then we don ' t do anything""" | # Return if the budget data package fields have not been filled in
if not self . are_budget_data_package_fields_filled_in ( resource ) :
return
if resource . get ( 'upload' , '' ) == '' : # If it isn ' t an upload we check if it ' s the same url
if current [ 'url' ] == resource [ 'url' ] : # Return if it ' s th... |
def make_full_url ( request , url ) :
"""Get a relative URL and returns the absolute version .
Eg : “ / foo / bar ? q = is - open ” = = > “ http : / / example . com / foo / bar ? q = is - open ”""" | urlparts = request . urlparts
return '{scheme}://{site}/{url}' . format ( scheme = urlparts . scheme , site = get_site_name ( request ) , url = url . lstrip ( '/' ) , ) |
def build_cookbook ( build_config , templatepack_path , cookbooks_home , force = False ) :
"""Build a cookbook from a fastfood . json file .
Can build on an existing cookbook , otherwise this will
create a new cookbook for you based on your templatepack .""" | with open ( build_config ) as cfg :
cfg = json . load ( cfg )
cookbook_name = cfg [ 'name' ]
template_pack = pack . TemplatePack ( templatepack_path )
written_files = [ ]
cookbook = create_new_cookbook ( cookbook_name , cookbooks_home )
for stencil_definition in cfg [ 'stencils' ] :
selected_stencil_set_name = ... |
def set_current_stim_parameter ( self , param , val ) :
"""Sets a parameter on the current stimulus
: param param : name of the parameter of the stimulus to set
: type param : str
: param val : new value to set the parameter to""" | component = self . _stimulus . component ( 0 , 1 )
component . set ( param , val ) |
def hash_trees ( self ) :
"hash ladderized tree topologies" | observed = { }
for idx , tree in enumerate ( self . treelist ) :
nwk = tree . write ( tree_format = 9 )
hashed = md5 ( nwk . encode ( "utf-8" ) ) . hexdigest ( )
if hashed not in observed :
observed [ hashed ] = idx
self . treedict [ idx ] = 1
else :
idx = observed [ hashed ]
... |
def owner ( self ) :
"""Username of document creator""" | if self . _owner :
return self . _owner
elif not self . abstract :
return self . read_meta ( ) . _owner
raise EmptyDocumentException ( ) |
def _commit ( self , session , errorMessage ) :
"""Custom commit function for file objects""" | try :
session . commit ( )
except IntegrityError : # Raise special error if the commit fails due to empty files
log . error ( 'Commit to database failed. %s' % errorMessage )
except : # Raise other errors as normal
raise |
def intersection ( self , other ) :
"""Replaces the ScienceSegments contained in this instance of ScienceData
with the intersection of those in the instance other . Returns the number
of segments in the intersection .
@ param other : ScienceData to use to generate the intersection""" | # we only deal with the case of two lists here
length1 = len ( self )
length2 = len ( other )
# initialize list of output segments
ostart = - 1
outlist = [ ]
iseg2 = - 1
start2 = - 1
stop2 = - 1
for seg1 in self :
start1 = seg1 . start ( )
stop1 = seg1 . end ( )
id = seg1 . id ( )
# loop over segments f... |
def ProcessResponses ( self , responses , thread_pool ) :
"""For WellKnownFlows we receive these messages directly .""" | for response in responses :
thread_pool . AddTask ( target = self . _SafeProcessMessage , args = ( response , ) , name = self . __class__ . __name__ ) |
def fix ( self ) :
"""Fix the parameters with the coordinates ( either ra , dec or l , b depending on how the class
has been instanced )""" | if self . _coord_type == 'equatorial' :
self . ra . fix = True
self . dec . fix = True
else :
self . l . fix = True
self . b . fix = True |
def response_headers ( ) :
"""Returns a set of response headers from the query string .
tags :
- Response inspection
parameters :
- in : query
name : freeform
explode : true
allowEmptyValue : true
schema :
type : object
additionalProperties :
type : string
style : form
produces :
- appli... | # Pending swaggerUI update
# https : / / github . com / swagger - api / swagger - ui / issues / 3850
headers = MultiDict ( request . args . items ( multi = True ) )
response = jsonify ( list ( headers . lists ( ) ) )
while True :
original_data = response . data
d = { }
for key in response . headers . keys (... |
def update ( self , id , label = None , status = None , master = None ) :
"""Update an Identity
: param label : The label to give this new identity
: param status : The status of this identity . Default : ' active '
: param master : Represents whether this identity is a master .
Default : False
: return :... | params = { }
if label :
params [ 'label' ] = label
if status :
params [ 'status' ] = status
if master :
params [ 'master' ] = master
return self . request . put ( str ( id ) , params ) |
def cast ( obj ) :
"""Many tools love to subclass built - in types in order to implement useful
functionality , such as annotating the safety of a Unicode string , or adding
additional methods to a dict . However , cPickle loves to preserve those
subtypes during serialization , resulting in CallError during :... | if isinstance ( obj , dict ) :
return dict ( ( cast ( k ) , cast ( v ) ) for k , v in iteritems ( obj ) )
if isinstance ( obj , ( list , tuple ) ) :
return [ cast ( v ) for v in obj ]
if isinstance ( obj , PASSTHROUGH ) :
return obj
if isinstance ( obj , mitogen . core . UnicodeType ) :
return mitogen .... |
async def call_async ( self , method , ** parameters ) :
"""Makes an async call to the API .
: param method : The method name .
: param params : Additional parameters to send ( for example , search = dict ( id = ' b123 ' ) )
: return : The JSON result ( decoded into a dict ) from the server . abs
: raise My... | if method is None :
raise Exception ( 'A method name must be specified' )
params = api . process_parameters ( parameters )
if self . credentials and not self . credentials . session_id :
self . authenticate ( )
if 'credentials' not in params and self . credentials . session_id :
params [ 'credentials' ] = s... |
def comment_list ( self , group_by , limit = None , page = None , body_matches = None , post_id = None , post_tags_match = None , creator_name = None , creator_id = None , is_deleted = None ) :
"""Return a list of comments .
Parameters :
limit ( int ) : How many posts you want to retrieve .
page ( int ) : The... | params = { 'group_by' : group_by , 'limit' : limit , 'page' : page , 'search[body_matches]' : body_matches , 'search[post_id]' : post_id , 'search[post_tags_match]' : post_tags_match , 'search[creator_name]' : creator_name , 'search[creator_id]' : creator_id , 'search[is_deleted]' : is_deleted }
return self . _get ( 'c... |
def hook_changed ( self , hook_name , widget , new_data ) :
"""Handle a hook upate .""" | if hook_name == 'song' :
self . song_changed ( widget , new_data )
elif hook_name == 'state' :
self . state_changed ( widget , new_data )
elif hook_name == 'elapsed_and_total' :
elapsed , total = new_data
self . time_changed ( widget , elapsed , total ) |
def _first_expander ( fringe , iteration , viewer ) :
'''Expander that expands only the first node on the fringe .''' | current = fringe [ 0 ]
neighbors = current . expand ( local_search = True )
if viewer :
viewer . event ( 'expanded' , [ current ] , [ neighbors ] )
fringe . extend ( neighbors ) |
def change_tz ( cal , new_timezone , default , utc_only = False , utc_tz = icalendar . utc ) :
"""Change the timezone of the specified component .
Args :
cal ( Component ) : the component to change
new _ timezone ( tzinfo ) : the timezone to change to
default ( tzinfo ) : a timezone to assume if the dtstart... | for vevent in getattr ( cal , 'vevent_list' , [ ] ) :
start = getattr ( vevent , 'dtstart' , None )
end = getattr ( vevent , 'dtend' , None )
for node in ( start , end ) :
if node :
dt = node . value
if ( isinstance ( dt , datetime ) and ( not utc_only or dt . tzinfo == utc_t... |
def capture_sys_output ( ) :
"""Capture standard output and error .""" | capture_out , capture_err = StringIO ( ) , StringIO ( )
current_out , current_err = sys . stdout , sys . stderr
try :
sys . stdout , sys . stderr = capture_out , capture_err
yield capture_out , capture_err
finally :
sys . stdout , sys . stderr = current_out , current_err |
def list ( self ) :
"""List the tables in the database""" | connection = self . _backend . _get_connection ( )
return list ( self . _backend . list ( connection ) ) |
def get_config_value ( self , overrides , skip_environment = False ) :
"""Get the configuration value from all overrides .
Iterates over all overrides given to see if a value can be pulled
out from them . It will convert each of these values to ensure they
are the correct type .
Args :
overrides : A list ... | label , override , key = self . _search_overrides ( overrides , skip_environment )
if override is None and self . default is None and self . required :
raise YapconfItemNotFound ( 'Could not find config value for {0}' . format ( self . fq_name ) , self )
if override is None :
self . logger . debug ( 'Config val... |
def removeRows ( self , row , count , parent = QModelIndex ( ) ) :
"""Reimplements the : meth : ` QAbstractItemModel . removeRows ` method .
: param row : Row .
: type row : int
: param count : Count .
: type count : int
: param parent : Parent .
: type parent : QModelIndex
: return : Method success .... | parent_node = self . get_node ( parent )
self . beginRemoveRows ( parent , row , row + count - 1 )
success = True
for i in range ( count ) :
success *= True if parent_node . remove_child ( row ) else False
self . endRemoveRows ( )
return success |
def decode_mail_header ( value , default_charset = 'us-ascii' ) :
"""Decode a header value into a unicode string .""" | try :
headers = decode_header ( value )
except email . errors . HeaderParseError :
return str_decode ( str_encode ( value , default_charset , 'replace' ) , default_charset )
else :
for index , ( text , charset ) in enumerate ( headers ) :
logger . debug ( "Mail header no. {index}: {data} encoding {c... |
def populate_results_dict ( self , sample , gene , total_mismatches , genome_pos , amplicon_length , contig , primer_set ) :
"""Populate the results dictionary with the required key : value pairs
: param sample : type MetadataObject : Current metadata sample to process
: param gene : type STR : Gene of interest... | sample [ self . analysistype ] . result_dict [ gene ] = { 'total_mismatches' : total_mismatches , 'genome_pos' : genome_pos , 'amplicon_length' : amplicon_length , 'contig' : contig , 'primer_set' : primer_set } |
def save_yaml ( self , outFile ) :
"""saves the config parameters to a json file""" | with open ( outFile , 'w' ) as myfile :
print ( yaml . dump ( self . params ) , file = myfile ) |
def ParseFileObject ( self , parser_mediator , file_object ) :
"""Parses a Windows Recycler INFO2 file - like object .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
file _ object ( dfvfs . FileIO ) : file - like object ... | # Since this header value is really generic it is hard not to use filename
# as an indicator too .
# TODO : Rethink this and potentially make a better test .
filename = parser_mediator . GetFilename ( )
if not filename . startswith ( 'INFO2' ) :
return
file_header_map = self . _GetDataTypeMap ( 'recycler_info2_file... |
def access_cache ( self , key = None , key_location_on_param = 0 , expire = None , auto_update = True , cache_loader = None , cache_writer = None , timeout = 1 ) :
"""The decorator for simplifying of use cache , it supports auto - update
cache ( if parameter auto _ update is True ) , load cache from other level c... | def decorate ( func ) :
@ functools . wraps ( func )
def wrapper ( * args , ** kwargs ) :
k = None
if len ( args ) - 1 >= key_location_on_param :
k = args [ key_location_on_param ]
if key is not None :
k = key
cache_result = self . get ( key = k , timeout ... |
def get_settings_json ( self ) :
"""Convert generator settings to JSON .
Returns
` dict `
JSON data .""" | return { 'scanner' : None if self . scanner is None else self . scanner . save ( ) , 'parser' : None if self . parser is None else self . parser . save ( ) } |
def signHostCsr ( self , xcsr , signas , outp = None , sans = None ) :
'''Signs a host CSR with a CA keypair .
Args :
cert ( OpenSSL . crypto . X509Req ) : The certificate signing request .
signas ( str ) : The CA keypair name to sign the CSR with .
outp ( synapse . lib . output . Output ) : The output buff... | pkey = xcsr . get_pubkey ( )
name = xcsr . get_subject ( ) . CN
return self . genHostCert ( name , csr = pkey , signas = signas , outp = outp , sans = sans ) |
def clause ( self , * args , ** kwargs ) :
"""Adds a ` lunr . Clause ` to this query .
Unless the clause contains the fields to be matched all fields will be
matched . In addition a default boost of 1 is applied to the clause .
If the first argument is a ` lunr . Clause ` it will be mutated and added ,
othe... | if args and isinstance ( args [ 0 ] , Clause ) :
clause = args [ 0 ]
else :
clause = Clause ( * args , ** kwargs )
if not clause . fields :
clause . fields = self . all_fields
if ( clause . wildcard & Query . WILDCARD_LEADING ) and ( clause . term [ 0 ] != Query . WILDCARD ) :
clause . term = Query . WI... |
def generate_secret_file ( file_path , pattern , service , environment , clients ) :
"""Generate a parameter files with it ' s secrets encrypted in KMS
Args :
file _ path ( string ) : Path to the parameter file to be encrypted
pattern ( string ) : Pattern to do fuzzy string matching
service ( string ) : Ser... | changed = False
with open ( file_path ) as json_file :
data = json . load ( json_file , object_pairs_hook = OrderedDict )
try :
for key , value in data [ "params" ] [ environment ] . items ( ) :
if pattern in key :
if "aws:kms:decrypt" in value :
print ( "... |
def conversions ( self ) :
"""Returns a string showing the available conversions .
Useful tool in interactive mode .""" | return "\n" . join ( str ( self . to ( unit ) ) for unit in self . supported_units ) |
def delete_runtime_class ( self , name , ** kwargs ) :
"""delete a RuntimeClass
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . delete _ runtime _ class ( name , async _ req = True )
> > > result = thread . ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . delete_runtime_class_with_http_info ( name , ** kwargs )
else :
( data ) = self . delete_runtime_class_with_http_info ( name , ** kwargs )
return data |
def registerAtomType ( self , parameters ) :
"""Register a new atom type .""" | name = parameters [ 'name' ]
if name in self . _atomTypes :
raise ValueError ( 'Found multiple definitions for atom type: ' + name )
atom_class = parameters [ 'class' ]
mass = _convertParameterToNumber ( parameters [ 'mass' ] )
element = None
if 'element' in parameters :
element , custom = self . _create_elemen... |
def _get_reconciled_name_object ( self , other ) :
"""If the result of a set operation will be self ,
return self , unless the name changes , in which
case make a shallow copy of self .""" | name = get_op_result_name ( self , other )
if self . name != name :
return self . _shallow_copy ( name = name )
return self |
def validate ( self ) :
"""method traverse tree and performs following activities :
* requests a job record in STATE _ EMBRYO if no job record is currently assigned to the node
* requests nodes for reprocessing , if STATE _ PROCESSED node relies on unfinalized nodes
* requests node for skipping if it is daily... | # step 1 : request Job record if current one is not set
if self . job_record is None :
self . tree . timetable . assign_job_record ( self )
# step 2 : define if current node has a younger sibling
next_timeperiod = time_helper . increment_timeperiod ( self . time_qualifier , self . timeperiod )
has_younger_sibling =... |
async def log_transaction ( self , ** params ) :
"""Writing transaction to database""" | if params . get ( "message" ) :
params = json . loads ( params . get ( "message" , "{}" ) )
if not params :
return { "error" : 400 , "reason" : "Missed required fields" }
coinid = params . get ( "coinid" )
if not coinid in [ "QTUM" , "PUT" ] :
return { "error" : 400 , "reason" : "Missed or invalid coinid" }... |
def compute_edge_reduction ( self ) -> float :
"""Compute the edge reduction . Costly computation""" | nb_init_edge = self . init_edge_number ( )
nb_poweredge = self . edge_number ( )
return ( nb_init_edge - nb_poweredge ) / ( nb_init_edge ) |
def tick_all ( self , times ) :
"""Tick all the EWMAs for the given number of times""" | for i in range ( times ) :
for avg in ( self . m1 , self . m5 , self . m15 , self . day ) :
avg . tick ( ) |
def launch ( in_name , out_name , script_path , partitioner = False , files = ( ) , jobconfs = ( ) , cmdenvs = ( ) , libjars = ( ) , input_format = None , output_format = None , copy_script = True , wait = True , hstreaming = None , name = None , use_typedbytes = True , use_seqoutput = True , use_autoinput = True , rem... | if isinstance ( files , ( str , unicode ) ) or isinstance ( jobconfs , ( str , unicode ) ) or isinstance ( cmdenvs , ( str , unicode ) ) :
raise TypeError ( 'files, jobconfs, and cmdenvs must be iterators of strings and not strings!' )
jobconfs = _listeq_to_dict ( jobconfs )
cmdenvs = _listeq_to_dict ( cmdenvs )
l... |
def continue_task ( cls , logger = None , task_id = _TASK_ID_NOT_SUPPLIED ) :
"""Start a new action which is part of a serialized task .
@ param logger : The L { eliot . ILogger } to which to write
messages , or C { None } if the default one should be used .
@ param task _ id : A serialized task identifier , ... | if task_id is _TASK_ID_NOT_SUPPLIED :
raise RuntimeError ( "You must supply a task_id keyword argument." )
if isinstance ( task_id , bytes ) :
task_id = task_id . decode ( "ascii" )
uuid , task_level = task_id . split ( "@" )
action = cls ( logger , uuid , TaskLevel . fromString ( task_level ) , "eliot:remote_t... |
def install_passband ( fname , local = True ) :
"""Install a passband from a local file . This simply copies the file into the
install path - but beware that clearing the installation will clear the
passband as well
If local = False , you must have permissions to access the installation directory""" | pbdir = _pbdir_local if local else _pbdir_global
shutil . copy ( fname , pbdir )
init_passband ( os . path . join ( pbdir , fname ) ) |
def read_header ( stream , codec ) :
"""Decodes an image header .
Wraps the openjp2 library function opj _ read _ header .
Parameters
stream : STREAM _ TYPE _ P
The JPEG2000 stream .
codec : codec _ t
The JPEG2000 codec to read .
Returns
imagep : reference to ImageType instance
The image structure... | ARGTYPES = [ STREAM_TYPE_P , CODEC_TYPE , ctypes . POINTER ( ctypes . POINTER ( ImageType ) ) ]
OPENJP2 . opj_read_header . argtypes = ARGTYPES
OPENJP2 . opj_read_header . restype = check_error
imagep = ctypes . POINTER ( ImageType ) ( )
OPENJP2 . opj_read_header ( stream , codec , ctypes . byref ( imagep ) )
return im... |
def fetch_title ( self , url , hostname_tag = False , friendly_errors = False ) :
"""Fetch the document at * url * and return a ` Deferred ` yielding
the document title or summary as a Unicode string . * url * may be
a Unicode string IRI , a byte string URI , or a Twisted ` URL ` .
If * hostname _ tag * is tr... | title = None
if isinstance ( url , unicode ) :
url = URL . fromText ( url )
elif isinstance ( url , str ) :
url = URL . fromText ( url . decode ( 'ascii' ) )
current = url
response = None
for _ in xrange ( self . max_soft_redirects ) :
last_response = response
# This encoding should be safe , since asUR... |
def run_account ( account , region , policies_config , output_path , cache_period , cache_path , metrics , dryrun , debug ) :
"""Execute a set of policies on an account .""" | logging . getLogger ( 'custodian.output' ) . setLevel ( logging . ERROR + 1 )
CONN_CACHE . session = None
CONN_CACHE . time = None
# allow users to specify interpolated output paths
if '{' not in output_path :
output_path = os . path . join ( output_path , account [ 'name' ] , region )
cache_path = os . path . join... |
def deploy_service_contracts ( self , token_address : str , user_deposit_whole_balance_limit : int , ) :
"""Deploy 3rd party service contracts""" | chain_id = int ( self . web3 . version . network )
deployed_contracts : DeployedContracts = { 'contracts_version' : self . contract_version_string ( ) , 'chain_id' : chain_id , 'contracts' : { } , }
self . _deploy_and_remember ( CONTRACT_SERVICE_REGISTRY , [ token_address ] , deployed_contracts )
user_deposit = self . ... |
def countInSample ( binaryWord , spikeTrain ) :
"""Counts the times in which a binary pattern ( e . g . [ 1 0 0 1 1 0 1 ] ) occurs in a spike train
@ param binaryWord ( array ) binary vector to be search within the spike train matrix .
@ param spikeTrain ( array ) matrix of spike trains . Dimensions of binary w... | count = 0
timeSteps = np . shape ( spikeTrain ) [ 1 ]
for i in range ( timeSteps ) :
if np . dot ( binaryWord , spikeTrain [ : , i ] ) == np . count_nonzero ( binaryWord ) :
count += 1
# print i
return count |
def directives ( entrystream , type = None ) :
"""Pull directives out of the specified entry stream .
: param entrystream : a stream of entries
: param type : retrieve only directives of the specified type ; set to
: code : ` None ` to retrieve all directives""" | for directive in entry_type_filter ( entrystream , tag . Directive ) :
if not type or type == directive . type :
yield directive |
def on_batch_end ( self ) :
"""Finalize batch processing""" | for callback in self . callbacks :
callback . on_batch_end ( self )
# Even with all the experience replay , we count the single rollout as a single batch
self . epoch_info . result_accumulator . calculate ( self ) |
def rmon_event_entry_event_description ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
rmon = ET . SubElement ( config , "rmon" , xmlns = "urn:brocade.com:mgmt:brocade-rmon" )
event_entry = ET . SubElement ( rmon , "event-entry" )
event_index_key = ET . SubElement ( event_entry , "event-index" )
event_index_key . text = kwargs . pop ( 'event_index' )
event_description =... |
def get_all_entries ( self , charge_to_discharge = True ) :
"""Return all entries input for the electrode .
Args :
charge _ to _ discharge :
order from most charge to most discharged state ? Defaults to
True .
Returns :
A list of all entries in the electrode ( both stable and unstable ) ,
ordered by a... | all_entries = list ( self . get_stable_entries ( ) )
all_entries . extend ( self . get_unstable_entries ( ) )
# sort all entries by amount of working ion ASC
fsrt = lambda e : e . composition . get_atomic_fraction ( self . working_ion )
all_entries = sorted ( [ e for e in all_entries ] , key = fsrt )
return all_entries... |
def fromNow ( offset , dateObj = None ) :
"""Generate a ` datetime . datetime ` instance which is offset using a string .
See the README . md for a full example , but offset could be ' 1 day ' for
a datetime object one day in the future""" | # We want to handle past dates as well as future
future = True
offset = offset . lstrip ( )
if offset . startswith ( '-' ) :
future = False
offset = offset [ 1 : ] . lstrip ( )
if offset . startswith ( '+' ) :
offset = offset [ 1 : ] . lstrip ( )
# Parse offset
m = r . match ( offset )
if m is None :
ra... |
def _file_to_folder ( gi , fname , sample_info , libitems , library , folder ) :
"""Check if file exists on Galaxy , if not upload to specified folder .""" | full_name = os . path . join ( folder [ "name" ] , os . path . basename ( fname ) )
# Handle VCF : Galaxy reports VCF files without the gzip extension
file_type = "vcf_bgzip" if full_name . endswith ( ".vcf.gz" ) else "auto"
if full_name . endswith ( ".vcf.gz" ) :
full_name = full_name . replace ( ".vcf.gz" , ".vcf... |
def analysis_title_header_element ( feature , parent ) :
"""Retrieve analysis title header string from definitions .""" | _ = feature , parent
# NOQA
header = analysis_title_header [ 'string_format' ]
return header . capitalize ( ) |
def handleContractDetails ( self , msg , end = False ) :
"""handles contractDetails and contractDetailsEnd""" | if end : # mark as downloaded
self . _contract_details [ msg . reqId ] [ 'downloaded' ] = True
# move details from temp to permanent collector
self . contract_details [ msg . reqId ] = self . _contract_details [ msg . reqId ]
del self . _contract_details [ msg . reqId ]
# adjust fields if multi cont... |
def _run_pyroma ( setup_file , show_lint_files ) :
"""Run pyroma .""" | from pyroma import projectdata , ratings
from prospector . message import Message , Location
_debug_linter_status ( "pyroma" , setup_file , show_lint_files )
return_dict = dict ( )
data = projectdata . get_data ( os . getcwd ( ) )
all_tests = ratings . ALL_TESTS
for test in [ mod ( ) for mod in [ t . __class__ for t in... |
def pauli_commuting_sets ( element : Pauli ) -> Tuple [ Pauli , ... ] :
"""Gather the terms of a Pauli polynomial into commuting sets .
Uses the algorithm defined in ( Raeisi , Wiebe , Sanders ,
arXiv : 1108.4318 , 2011 ) to find commuting sets . Except uses commutation
check from arXiv : 1405.5749v2""" | if len ( element ) < 2 :
return ( element , )
groups : List [ Pauli ] = [ ]
# typing : List [ Pauli ]
for term in element :
pterm = Pauli ( ( term , ) )
assigned = False
for i , grp in enumerate ( groups ) :
if paulis_commute ( grp , pterm ) :
groups [ i ] = grp + pterm
a... |
def should_use_custom_repo ( args , cd_conf , repo_url ) :
"""A boolean to determine the logic needed to proceed with a custom repo
installation instead of cramming everything nect to the logic operator .""" | if repo_url : # repo _ url signals a CLI override , return False immediately
return False
if cd_conf :
if cd_conf . has_repos :
has_valid_release = args . release in cd_conf . get_repos ( )
has_default_repo = cd_conf . get_default_repo ( )
if has_valid_release or has_default_repo :
... |
def _switch_defined ( self , switch_ip ) :
"""Verify this ip address is defined ( for Nexus ) .""" | switch = cfg . CONF . ml2_cisco . nexus_switches . get ( switch_ip )
if switch and switch . username and switch . password :
return True
else :
return False |
def expand_gallery ( generator , metadata ) :
"""Expand a gallery tag to include all of the files in a specific directory under IMAGE _ PATH
: param pelican : The pelican instance
: return : None""" | if "gallery" not in metadata or metadata [ 'gallery' ] is None :
return
# If no gallery specified , we do nothing
lines = [ ]
base_path = _image_path ( generator )
in_path = path . join ( base_path , metadata [ 'gallery' ] )
template = generator . settings . get ( 'GALLERY_TEMPLATE' , DEFAULT_TEMPLATE )
thumbnail_n... |
def do_server ( self , arg ) :
"""Usage :
server on
server off
server restart
server log
server help""" | if arg [ 'on' ] :
self . server_on ( )
elif arg [ 'off' ] :
self . server_off ( )
elif arg [ 'restart' ] :
self . server_restart ( )
elif arg [ 'log' ] :
self . server_log ( )
else :
self . help_server ( ) |
def Blaster ( inputfile , databases , db_path , out_path = '.' , min_cov = 0.6 , threshold = 0.9 , blast = 'blastn' , cut_off = True ) :
'''BLAST wrapper method , that takes a simple input and produces a overview
list of the hits to templates , and their alignments
Usage
> > > import os , subprocess , collect... | min_cov = 100 * float ( min_cov )
threshold = 100 * float ( threshold )
# For alignment
gene_align_query = dict ( )
# will contain the sequence alignment lines
gene_align_homo = dict ( )
# will contain the sequence alignment homolog string
gene_align_sbjct = dict ( )
# will contain the sequence alignment allele string
... |
def csv_to_pickle ( path = ROOT / "raw" , clean = False ) :
"""Convert all CSV files in path to pickle .""" | for file in os . listdir ( path ) :
base , ext = os . path . splitext ( file )
if ext != ".csv" :
continue
LOG ( f"converting {file} to pickle" )
df = pd . read_csv ( path / file , low_memory = True )
WRITE_DF ( df , path / ( base + "." + FILE_EXTENSION ) , ** WRITE_DF_OPTS )
if clean :
... |
def subsystems ( cls ) :
"""Returns all subsystem types used by all tasks , in no particular order .
: API : public""" | ret = set ( )
for goal in cls . all ( ) :
ret . update ( goal . subsystems ( ) )
return ret |
def _on_timeline_update ( self , event ) :
"""Timeline update broadcast from Abode SocketIO server .""" | if isinstance ( event , ( tuple , list ) ) :
event = event [ 0 ]
event_type = event . get ( 'event_type' )
event_code = event . get ( 'event_code' )
if not event_type or not event_code :
_LOGGER . warning ( "Invalid timeline update event: %s" , event )
return
_LOGGER . debug ( "Timeline event received: %s -... |
def run_ci_bootstrap ( ns_run , estimator_list , ** kwargs ) :
"""Uses bootstrap resampling to calculate credible intervals on the
distribution of sampling errors ( the uncertainty on the calculation )
for a single nested sampling run .
For more details about bootstrap resampling for estimating sampling
err... | cred_int = kwargs . pop ( 'cred_int' )
# No default , must specify
bs_values = run_bootstrap_values ( ns_run , estimator_list , ** kwargs )
# estimate specific confidence intervals
# formulae for alpha CI on estimator T = 2 T ( x ) - G ^ { - 1 } ( T ( x * ) )
# where G is the CDF of the bootstrap resamples
expected_est... |
def convert_weights_to_numpy ( weights_dict ) :
"""Convert weights to numpy""" | return dict ( [ ( k . replace ( "arg:" , "" ) . replace ( "aux:" , "" ) , v . asnumpy ( ) ) for k , v in weights_dict . items ( ) ] ) |
def receive_one_ping ( self , current_socket ) :
"""Receive the ping from the socket . timeout = in ms .""" | timeout = self . timeout / 1000.0
while True : # Loop while waiting for packet or timeout
select_start = default_timer ( )
inputready , outputready , exceptready = select . select ( [ current_socket ] , [ ] , [ ] , timeout )
select_duration = ( default_timer ( ) - select_start )
if inputready == [ ] : #... |
def __decl_types ( decl ) :
"""implementation details""" | types = [ ]
bases = list ( decl . __class__ . __bases__ )
if 'pygccxml' in decl . __class__ . __module__ :
types . append ( decl . __class__ )
while bases :
base = bases . pop ( )
if base is declaration . declaration_t :
continue
if base is byte_info . byte_info :
continue
if base is... |
def reconnect_all ( self ) :
"""Re - establish connection to all instances""" | for role in self . Instances . keys ( ) :
for connection in self . Instances [ role ] :
connection . reconnect ( ) |
def submain ( p ) :
"""completly set - up a package in the target dir ( using cookie cutter )""" | parser = argparse . ArgumentParser ( description = 'Bootstrap a Python Package with Love.' )
parser . add_argument ( 'name' , metavar = 'name' , type = str , nargs = '?' , help = 'a potential package name' )
parser . add_argument ( 'target_dir' , type = str , nargs = '?' , help = 'target directory in which to create th... |
def get_address_by_id ( cls , address_id , ** kwargs ) :
"""Find Address
Return single instance of Address by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . get _ address _ by _ id ( address _ id , async... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _get_address_by_id_with_http_info ( address_id , ** kwargs )
else :
( data ) = cls . _get_address_by_id_with_http_info ( address_id , ** kwargs )
return data |
def main ( ) :
"""NAME
sites _ locations . py
DESCRIPTION
reads in er _ sites . txt file and finds all locations and bounds of locations
outputs er _ locations . txt file
SYNTAX
sites _ locations . py [ command line options ]
OPTIONS
- h prints help message and quits
- f : specimen input er _ site... | # set defaults
site_file = "er_sites.txt"
loc_file = "er_locations.txt"
Names , user = [ ] , "unknown"
Done = [ ]
version_num = pmag . get_version ( )
args = sys . argv
dir_path = '.'
# get command line stuff
if '-WD' in args :
ind = args . index ( "-WD" )
dir_path = args [ ind + 1 ]
if "-h" in args :
print... |
def _download_query ( self , as_of ) :
"""Formulate the specific query needed for download
Not intended to be called by developers directly .
: param as _ of : Date in ' YYYYMMDD ' format
: type as _ of : string""" | c = self . institution . client ( )
q = c . bank_account_query ( number = self . number , date = as_of , account_type = self . account_type , bank_id = self . routing_number )
return q |
def pick_contiguous_unused_ports ( num_ports , retry_interval_secs = 3 , retry_attempts = 5 ) :
"""Reserves and returns a list of ` num _ ports ` contiguous unused ports .""" | for _ in range ( retry_attempts ) :
start_port = portpicker . pick_unused_port ( )
if start_port is not None :
ports = [ start_port + p for p in range ( num_ports ) ]
if all ( portpicker . is_port_free ( p ) for p in ports ) :
return ports
else :
return_ports ( po... |
def _receiveFromListener ( self , quota : Quota ) -> int :
"""Receives messages from listener
: param quota : number of messages to receive
: return : number of received messages""" | i = 0
incoming_size = 0
while i < quota . count and incoming_size < quota . size :
try :
ident , msg = self . listener . recv_multipart ( flags = zmq . NOBLOCK )
if not msg : # Router probing sends empty message on connection
continue
incoming_size += len ( msg )
i += 1
... |
def _exitOnSignal ( sigName , message ) :
"""Handles a signal with sys . exit .
Some of these signals ( SIGPIPE , for example ) don ' t exist or are invalid on
Windows . So , ignore errors that might arise .""" | import signal
try :
sigNumber = getattr ( signal , sigName )
except AttributeError : # the signal constants defined in the signal module are defined by
# whether the C library supports them or not . So , SIGPIPE might not
# even be defined .
return
def handler ( sig , f ) :
sys . exit ( message )
try :
... |
def ParseRow ( self , parser_mediator , row_offset , row ) :
"""Parses a line of the log file and produces events .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs .
row _ offset ( int ) : number of the corresponding line .... | filename = row . get ( 'name' , None )
md5_hash = row . get ( 'md5' , None )
mode = row . get ( 'mode_as_string' , None )
inode_number = row . get ( 'inode' , None )
if '-' in inode_number :
inode_number , _ , _ = inode_number . partition ( '-' )
try :
inode_number = int ( inode_number , 10 )
except ( TypeError... |
def _get_child_class ( self , path ) :
"""Return the appropriate child class given a subdirectory path .
Args :
path ( str ) : The path to the subdirectory .
Returns : An uninstantiated BIDSNode or one of its subclasses .""" | if self . _child_entity is None :
return BIDSNode
for i , child_ent in enumerate ( listify ( self . _child_entity ) ) :
template = self . available_entities [ child_ent ] . directory
if template is None :
return BIDSNode
template = self . root_path + template
# Construct regex search pattern... |
def build_stop_timetable ( feed : "Feed" , stop_id : str , dates : List [ str ] ) -> DataFrame :
"""Return a DataFrame containing the timetable for the given stop ID
and dates .
Parameters
feed : Feed
stop _ id : string
ID of the stop for which to build the timetable
dates : string or list
A YYYYMMDD ... | dates = feed . restrict_dates ( dates )
if not dates :
return pd . DataFrame ( )
t = pd . merge ( feed . trips , feed . stop_times )
t = t [ t [ "stop_id" ] == stop_id ] . copy ( )
a = feed . compute_trip_activity ( dates )
frames = [ ]
for date in dates : # Slice to stops active on date
ids = a . loc [ a [ dat... |
def filter ( self , given_filter , apply_zerovalue = False ) :
"""Apply filter into all values
Params
< lambda > | < function > given _ filter
< bool > only _ nonzero""" | get_ = self . get___method
set_ = self . set___method
max_value = self . max_value
for table_id in range ( self . depth ) :
for cell_id in range ( self . width ) :
val = get_ ( self , table_id , cell_id )
if val or apply_zerovalue :
val = given_filter ( val )
val = max_value ... |
def img2img_transformer_base ( ) :
"""Base params for local1d attention .""" | hparams = image_transformer2d_base ( )
# learning related flags
hparams . layer_preprocess_sequence = "n"
hparams . layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate .
hparams . learning_rate = 0.2
hparams . layer_prepostprocess_dropout = 0.1
hparams . learning_rate_warmup_st... |
def cell_complete ( self , cell , cell_index = None , ** kwargs ) :
"""Finalize metadata for a cell and save notebook .
Optionally called by engines during execution to finalize the
metadata for a cell and save the notebook to the output path .""" | end_time = self . now ( )
if self . log_output :
ceel_num = cell_index + 1 if cell_index is not None else ''
logger . info ( 'Ending Cell {:-<43}' . format ( ceel_num ) )
# Ensure our last cell messages are not buffered by python
sys . stdout . flush ( )
sys . stderr . flush ( )
cell . metadata . pa... |
def make_contrib ( superclass , func = None ) :
"""Returns a suitable contribute _ to _ class ( ) method for the Field subclass .
If ' func ' is passed in , it is the existing contribute _ to _ class ( ) method on
the subclass and it is called before anything else . It is assumed in this
case that the existin... | def contribute_to_class ( self , cls , name ) :
if func :
func ( self , cls , name )
else :
super ( superclass , self ) . contribute_to_class ( cls , name )
setattr ( cls , self . name , Creator ( self ) )
return contribute_to_class |
def makeUnicodeToGlyphNameMapping ( self ) :
"""Return the Unicode to glyph name mapping for the current font .""" | # Try to get the " best " Unicode cmap subtable if this writer is running
# in the context of a FeatureCompiler , else create a new mapping from
# the UFO glyphs
compiler = self . context . compiler
cmap = None
if compiler is not None :
table = compiler . ttFont . get ( "cmap" )
if table is not None :
c... |
def peep_port ( paths ) :
"""Convert a peep requirements file to one compatble with pip - 8 hashing .
Loses comments and tromps on URLs , so the result will need a little manual
massaging , but the hard part - - the hash conversion - - is done for you .""" | if not paths :
print ( 'Please specify one or more requirements files so I have ' 'something to port.\n' )
return COMMAND_LINE_ERROR
comes_from = None
for req in chain . from_iterable ( _parse_requirements ( path , package_finder ( argv ) ) for path in paths ) :
req_path , req_line = path_and_line ( req )
... |
def run_filter_radia ( job , bams , radia_file , univ_options , radia_options , chrom ) :
"""This module will run filterradia on the RNA and DNA bams .
ARGUMENTS
1 . bams : REFER ARGUMENTS of run _ radia ( )
2 . univ _ options : REFER ARGUMENTS of run _ radia ( )
3 . radia _ file : < JSid of vcf generated b... | job . fileStore . logToMaster ( 'Running filter-radia on %s:%s' % ( univ_options [ 'patient' ] , chrom ) )
work_dir = job . fileStore . getLocalTempDir ( )
input_files = { 'rna.bam' : bams [ 'tumor_rna' ] , 'rna.bam.bai' : bams [ 'tumor_rnai' ] , 'tumor.bam' : bams [ 'tumor_dna' ] , 'tumor.bam.bai' : bams [ 'tumor_dnai... |
def connect ( self ) :
"""Initializes a connection to the smtp server
: return : True on success , False otherwise""" | connection_method = 'SMTP_SSL' if self . ssl else 'SMTP'
self . _logger . debug ( 'Trying to connect via {}' . format ( connection_method ) )
smtp = getattr ( smtplib , connection_method )
if self . port :
self . _smtp = smtp ( self . address , self . port )
else :
self . _smtp = smtp ( self . address )
self . ... |
def handle ( self , path , method = 'GET' ) :
"""( deprecated ) Execute the first matching route callback and return
the result . : exc : ` HTTPResponse ` exceptions are catched and returned .
If : attr : ` Bottle . catchall ` is true , other exceptions are catched as
well and returned as : exc : ` HTTPError ... | depr ( "This method will change semantics in 0.10. Try to avoid it." )
if isinstance ( path , dict ) :
return self . _handle ( path )
return self . _handle ( { 'PATH_INFO' : path , 'REQUEST_METHOD' : method . upper ( ) } ) |
def reverse_timezone ( self , query , timeout = DEFAULT_SENTINEL ) :
"""Find the timezone for a point in ` query ` .
GeoNames always returns a timezone : if the point being queried
doesn ' t have an assigned Olson timezone id , a ` ` pytz . FixedOffset ` `
timezone is used to produce the : class : ` geopy . t... | ensure_pytz_is_installed ( )
try :
lat , lng = self . _coerce_point_to_string ( query ) . split ( ',' )
except ValueError :
raise ValueError ( "Must be a coordinate pair or Point" )
params = { "lat" : lat , "lng" : lng , "username" : self . username , }
url = "?" . join ( ( self . api_timezone , urlencode ( par... |
def encode_hook ( self , hook , msg ) :
"""Encodes a commit hook dict into the protobuf message . Used in
bucket properties .
: param hook : the hook to encode
: type hook : dict
: param msg : the protobuf message to fill
: type msg : riak . pb . riak _ pb2 . RpbCommitHook
: rtype riak . pb . riak _ pb2... | if 'name' in hook :
msg . name = str_to_bytes ( hook [ 'name' ] )
else :
self . encode_modfun ( hook , msg . modfun )
return msg |
def topics_count ( self ) :
"""Returns the number of topics associated with the current node and its descendants .""" | return self . obj . direct_topics_count + sum ( n . topics_count for n in self . children ) |
def custom_covariance ( self , beta ) :
"""Creates Covariance Matrix for a given Beta Vector
( Not necessarily the OLS covariance )
Parameters
beta : np . array
Contains untransformed starting values for latent variables
Returns
A Covariance Matrix""" | cov_matrix = np . zeros ( ( self . ylen , self . ylen ) )
parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] )
return custom_covariance_matrix ( cov_matrix , self . ylen , self . lags , parm ) |
def transform_future ( transformation , future ) :
"""Returns a new future that will resolve with a transformed value
Takes the resolution value of ` future ` and applies transformation ( * future . result ( ) )
to it before setting the result of the new future with the transformed value . If
future ( ) resol... | new_future = tornado_Future ( )
def _transform ( f ) :
assert f is future
if f . exc_info ( ) is not None :
new_future . set_exc_info ( f . exc_info ( ) )
else :
try :
new_future . set_result ( transformation ( f . result ( ) ) )
except Exception : # An exception here idi... |
def interpolate_mrms_day ( start_date , variable , interp_type , mrms_path , map_filename , out_path ) :
"""For a given day , this module interpolates hourly MRMS data to a specified latitude and
longitude grid , and saves the interpolated grids to CF - compliant netCDF4 files .
Args :
start _ date ( datetime... | try :
print ( start_date , variable )
end_date = start_date + timedelta ( hours = 23 )
mrms = MRMSGrid ( start_date , end_date , variable , mrms_path )
if mrms . data is not None :
if map_filename [ - 3 : ] == "map" :
mapping_data = make_proj_grids ( * read_arps_map_file ( map_filena... |
def experimental_design ( self ) -> Any :
"""Return a markdown summary of the samples on this sample sheet .
This property supports displaying rendered markdown only when running
within an IPython interpreter . If we are not running in an IPython
interpreter , then print out a nicely formatted ASCII table .
... | if not self . samples :
raise ValueError ( 'No samples in sample sheet' )
markdown = tabulate ( [ [ getattr ( s , h , '' ) for h in DESIGN_HEADER ] for s in self . samples ] , headers = DESIGN_HEADER , tablefmt = 'pipe' , )
return maybe_render_markdown ( markdown ) |
def start ( self ) :
"""Start ZAP authentication""" | super ( ) . start ( )
self . __poller = zmq . asyncio . Poller ( )
self . __poller . register ( self . zap_socket , zmq . POLLIN )
self . __task = asyncio . ensure_future ( self . __handle_zap ( ) ) |
def prepend_string ( t , string ) :
"""Prepend a string to a target node as text .""" | node = t . tree
if node . text is not None :
node . text += string
else :
node . text = string |
def visit_module ( self , node ) :
"""return an astroid . Module node as string""" | docs = '"""%s"""\n\n' % node . doc if node . doc else ""
return docs + "\n" . join ( n . accept ( self ) for n in node . body ) + "\n\n" |
def time_left ( self , key ) :
"""Gets the amount of time an item has left in the cache ( in seconds ) , before it is evicted .
: param key : Key to check time for .
: returns : int""" | self . _evict_old ( )
if key not in self . _store :
raise KeyError ( "key {0!r} does not exist in cache" . format ( key ) )
return self . timeout - ( time . time ( ) - self . _store [ key ] [ 1 ] ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.