signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_sql ( self ) :
"""Generates the sql used for the limit clause of a Query
: return : the sql for the limit clause of a Query
: rtype : str""" | sql = ''
if self . limit and self . limit > 0 :
sql += 'LIMIT {0} ' . format ( self . limit )
if self . offset and self . offset > 0 :
sql += 'OFFSET {0} ' . format ( self . offset )
return sql |
def set_include_rts ( self , rts ) :
"""Sets ' include _ rts ' parameter . When set to False , the timeline will strip any native retweets from the returned timeline
: param rts : Boolean triggering the usage of the parameter
: raises : TwitterSearchException""" | if not isinstance ( rts , bool ) :
raise TwitterSearchException ( 1008 )
self . arguments . update ( { 'include_rts' : 'true' if rts else 'false' } ) |
def main ( argString = None ) :
"""The main function .
: param argString : the options .
: type argString : list
These are the steps :
1 . Prints the options .
2 . Computes the frequencies using Plinl ( : py : func : ` computeFrequency ` ) .
3 . Finds markers with MAF of 0 , and saves them in a file
(... | # Getting and checking the options
args = parseArgs ( argString )
checkArgs ( args )
logger . info ( "Options used:" )
for key , value in vars ( args ) . iteritems ( ) :
logger . info ( " --{} {}" . format ( key . replace ( "_" , "-" ) , value ) )
# Compute frequency using plink
logger . info ( "Computing the freq... |
def tree_is_in_collection ( collection , study_id = None , tree_id = None ) :
"""Takes a collection object ( or a filepath to collection object ) , returns
True if it includes a decision to include the specified tree""" | included = collection_to_included_trees ( collection )
study_id = study_id . strip ( )
tree_id = tree_id . strip ( )
for decision in included :
if decision [ 'studyID' ] == study_id and decision [ 'treeID' ] == tree_id :
return True
return False |
def parse_args ( ) :
"""Parse the command line arguments""" | parser = argparse . ArgumentParser ( description = "Generate secrets for YubiKeys using YubiHSM" , add_help = True , formatter_class = argparse . ArgumentDefaultsHelpFormatter , )
parser . add_argument ( '-D' , '--device' , dest = 'device' , default = default_device , required = False , help = 'YubiHSM device' , )
pars... |
def socketpair ( family = socket . AF_INET , type = socket . SOCK_STREAM , proto = 0 ) :
"""Emulate the Unix socketpair ( ) function on Windows .""" | # We create a connected TCP socket . Note the trick with setblocking ( 0)
# that prevents us from having to create a thread .
lsock = socket . socket ( family , type , proto )
lsock . bind ( ( 'localhost' , 0 ) )
lsock . listen ( 1 )
addr , port = lsock . getsockname ( )
csock = socket . socket ( family , type , proto ... |
def document_path_path ( cls , project , database , document_path ) :
"""Return a fully - qualified document _ path string .""" | return google . api_core . path_template . expand ( "projects/{project}/databases/{database}/documents/{document_path=**}" , project = project , database = database , document_path = document_path , ) |
def lookup ( cls , basenote ) :
"""Look up note in registered annotations , walking class tree .""" | # Walk method resolution order , which includes current class .
for c in cls . mro ( ) :
if 'provider_registry' not in vars ( c ) : # class is a mixin , super to base class , or never registered .
continue
if basenote in c . provider_registry : # note is in the registry .
return c . provider_reg... |
def find_undeclared_variables ( ast ) :
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime . Because at compile time it ' s not known which
variables will be used depending on the path the execution takes at
runtime , all variables are returned .
> > > from jinja... | codegen = TrackingCodeGenerator ( ast . environment )
codegen . visit ( ast )
return codegen . undeclared_identifiers |
def _generate_remark_str ( self , end_of_line = '\n' ) :
"""Generate a series of remarks that the user should consider
when interpreting the summary statistics .""" | warnings = { }
msg = '{}' . format ( end_of_line )
# generate warnings for continuous variables
if self . _continuous : # highlight far outliers
outlier_mask = self . cont_describe . far_outliers > 1
outlier_vars = list ( self . cont_describe . far_outliers [ outlier_mask ] . dropna ( how = 'all' ) . index )
... |
def set ( clear = False , ** defaults ) :
"""Set default parameters for : class : ` lsqfit . nonlinear _ fit ` .
Use to set default values for parameters : ` ` svdcut ` ` ,
` ` debug ` ` , ` ` tol ` ` , ` ` maxit ` ` , and ` ` fitter ` ` . Can also set
parameters specific to the fitter specified by the ` ` fi... | old_defaults = dict ( nonlinear_fit . DEFAULTS )
if clear :
nonlinear_fit . DEFAULTS = { }
for k in defaults :
if k == 'fitter' and defaults [ k ] not in nonlinear_fit . FITTERS :
raise ValueError ( 'unknown fitter: ' + str ( defaults [ k ] ) )
nonlinear_fit . DEFAULTS [ k ] = defaults [ k ]
return ... |
def _on_gateway ( self , header , payload , rest , addr ) :
"""Records a discovered gateway , for connecting to later .""" | if payload . get ( 'service' ) == SERVICE_UDP :
self . gateway = Gateway ( addr [ 0 ] , payload [ 'port' ] , header . gateway )
self . gateway_found_event . set ( ) |
def put ( self , file_obj , full_path , overwrite = False ) :
"""Upload a file .
> > > nd . put ( ' . / flower . png ' , ' / Picture / flower . png ' )
> > > nd . put ( open ( ' . / flower . png ' , ' r ' ) , ' / Picture / flower . png ' )
: param file _ obj : A file - like object to check whether possible to... | try :
file_obj = open ( file_obj , 'r' )
except :
file_obj = file_obj
# do nothing
content = file_obj . read ( )
file_name = os . path . basename ( full_path )
now = datetime . datetime . now ( ) . isoformat ( )
url = nurls [ 'put' ] + full_path
if overwrite :
overwrite = 'T'
else :
overwrite = 'F'
head... |
def create_table_from_tabledata ( self , table_data , primary_key = None , add_primary_key_column = False , index_attrs = None ) :
"""Create a table from : py : class : ` tabledata . TableData ` .
: param tabledata . TableData table _ data : Table data to create .
: param str primary _ key : | primary _ key |
... | self . __create_table_from_tabledata ( table_data , primary_key , add_primary_key_column , index_attrs ) |
def cql_query_with_prepare ( query , statement_name , statement_arguments , callback_errors = None , contact_points = None , port = None , cql_user = None , cql_pass = None , ** kwargs ) :
'''Run a query on a Cassandra cluster and return a dictionary .
This function should not be used asynchronously for SELECTs -... | # Backward - compatibility with Python 3.7 : " async " is a reserved word
asynchronous = kwargs . get ( 'async' , False )
try :
cluster , session = _connect ( contact_points = contact_points , port = port , cql_user = cql_user , cql_pass = cql_pass )
except CommandExecutionError :
log . critical ( 'Could not ge... |
def add_compression ( self , compression = True ) :
"""Add an instruction enabling or disabling compression for the transmitted raster image lines .
Not all models support compression . If the specific model doesn ' t support it but this method
is called trying to enable it , either a warning is set or an excep... | if self . model not in compressionsupport :
self . _unsupported ( "Trying to set compression on a printer that doesn't support it" )
return
self . _compression = compression
self . data += b'\x4D'
self . data += bytes ( [ compression << 1 ] ) |
def write_parent ( self , url_data ) :
"""Write url _ data . parent _ url .""" | self . write ( self . part ( 'parenturl' ) + self . spaces ( "parenturl" ) )
txt = url_data . parent_url
if url_data . line > 0 :
txt += _ ( ", line %d" ) % url_data . line
if url_data . column > 0 :
txt += _ ( ", col %d" ) % url_data . column
if url_data . page > 0 :
txt += _ ( ", page %d" ) % url_data . p... |
def prep_jid ( nocache = False , passed_jid = None ) :
'''Return a job id and prepare the job id directory
This is the function responsible for making sure jids don ' t collide
( unless its passed a jid ) . So do what you have to do to make sure that
stays the case''' | conn = _get_conn ( )
if conn is None :
return None
cur = conn . cursor ( )
if passed_jid is None :
jid = _gen_jid ( cur )
else :
jid = passed_jid
while not jid :
log . info ( "jid clash, generating a new one" )
jid = _gen_jid ( cur )
cur . close ( )
conn . close ( )
return jid |
def confd_state_internal_cdb_datastore_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
confd_state = ET . SubElement ( config , "confd-state" , xmlns = "http://tail-f.com/yang/confd-monitoring" )
internal = ET . SubElement ( confd_state , "internal" )
cdb = ET . SubElement ( internal , "cdb" )
datastore = ET . SubElement ( cdb , "datastore" )
name = ET . SubElement ( da... |
def getServiceJobsToStart ( self , maxWait ) :
""": param float maxWait : Time in seconds to wait to get a job before returning .
: return : a tuple of ( serviceJobStoreID , memory , cores , disk , . . ) representing
a service job to start .
: rtype : toil . job . ServiceJobNode""" | try :
serviceJob = self . _serviceJobGraphsToStart . get ( timeout = maxWait )
assert self . jobsIssuedToServiceManager >= 0
self . jobsIssuedToServiceManager -= 1
return serviceJob
except Empty :
return None |
def GetNumberOfEventSources ( self ) :
"""Retrieves the number event sources .
Returns :
int : number of event sources .""" | number_of_event_sources = self . _CountStoredAttributeContainers ( self . _CONTAINER_TYPE_EVENT_SOURCE )
number_of_event_sources += self . _GetNumberOfSerializedAttributeContainers ( self . _CONTAINER_TYPE_EVENT_SOURCE )
return number_of_event_sources |
def get_session ( self , sid , namespace = None ) :
"""Return the user session for a client .
The only difference with the : func : ` socketio . Server . get _ session `
method is that when the ` ` namespace ` ` argument is not given the
namespace associated with the class is used .""" | return self . server . get_session ( sid , namespace = namespace or self . namespace ) |
def p_exit ( p ) :
"""statement : EXIT WHILE
| EXIT DO
| EXIT FOR""" | q = p [ 2 ]
p [ 0 ] = make_sentence ( 'EXIT_%s' % q )
for i in gl . LOOPS :
if q == i [ 0 ] :
return
syntax_error ( p . lineno ( 1 ) , 'Syntax Error: EXIT %s out of loop' % q ) |
def list_arj ( archive , compression , cmd , verbosity , interactive ) :
"""List an ARJ archive .""" | cmdlist = [ cmd ]
if verbosity > 1 :
cmdlist . append ( 'v' )
else :
cmdlist . append ( 'l' )
if not interactive :
cmdlist . append ( '-y' )
cmdlist . extend ( [ '-r' , archive ] )
return cmdlist |
def _read_para_puzzle ( self , code , cbit , clen , * , desc , length , version ) :
"""Read HIP PUZZLE parameter .
Structure of HIP PUZZLE parameter [ RFC 5201 ] [ RFC 7401 ] :
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
| Type | Length |
| # K , 1 byte | Lifetime | Opaque , 2 ... | if version == 1 and clen != 12 :
raise ProtocolError ( f'HIPv{version}: [Parano {code}] invalid format' )
_numk = self . _read_unpack ( 1 )
_time = self . _read_unpack ( 1 )
_opak = self . _read_fileng ( 2 )
_rand = self . _read_unpack ( clen - 4 )
puzzle = dict ( type = desc , critical = cbit , length = clen , num... |
def _windows_iqn ( ) :
'''Return iSCSI IQN from a Windows host .''' | ret = [ ]
wmic = salt . utils . path . which ( 'wmic' )
if not wmic :
return ret
namespace = r'\\root\WMI'
path = 'MSiSCSIInitiator_MethodClass'
get = 'iSCSINodeName'
cmd_ret = salt . modules . cmdmod . run_all ( '{0} /namespace:{1} path {2} get {3} /format:table' '' . format ( wmic , namespace , path , get ) )
for... |
def gather_demonstrations_as_hdf5 ( directory , out_dir ) :
"""Gathers the demonstrations saved in @ directory into a
single hdf5 file , and another directory that contains the
raw model . xml files .
The strucure of the hdf5 file is as follows .
data ( group )
date ( attribute ) - date of collection
ti... | # store model xmls in this directory
model_dir = os . path . join ( out_dir , "models" )
if os . path . isdir ( model_dir ) :
shutil . rmtree ( model_dir )
os . makedirs ( model_dir )
hdf5_path = os . path . join ( out_dir , "demo.hdf5" )
f = h5py . File ( hdf5_path , "w" )
# store some metadata in the attributes o... |
def read_metrics ( self , els_client = None ) :
"""Reads the bibliographic metrics for this author from api . elsevier . com
and updates self . data with them . Returns True if successful ; else ,
False .""" | try :
api_response = els_client . exec_request ( self . uri + "?field=document-count,cited-by-count,citation-count,h-index,dc:identifier" )
data = api_response [ self . __payload_type ] [ 0 ]
if not self . data :
self . _data = dict ( )
self . _data [ 'coredata' ] = dict ( )
self . _data... |
def stubs_clustering ( network , use_reduced_coordinates = True , line_length_factor = 1.0 ) :
"""Cluster network by reducing stubs and stubby trees
( i . e . sequentially reducing dead - ends ) .
Parameters
network : pypsa . Network
use _ reduced _ coordinates : boolean
If True , do not average clusters ... | busmap = busmap_by_stubs ( network )
# reset coordinates to the new reduced guys , rather than taking an average
if use_reduced_coordinates : # TODO : FIX THIS HACK THAT HAS UNEXPECTED SIDE - EFFECTS ,
# i . e . network is changed in place ! !
network . buses . loc [ busmap . index , [ 'x' , 'y' ] ] = network . bus... |
def target_str_to_list ( target_str ) :
"""Parses a targets string into a list of individual targets .""" | new_list = list ( )
for target in target_str . split ( ',' ) :
target = target . strip ( )
target_list = target_to_list ( target )
if target_list :
new_list . extend ( target_list )
else :
LOGGER . info ( "{0}: Invalid target value" . format ( target ) )
return None
return list (... |
async def kill_job ( self , message : BackendKillJob ) :
"""Handles ` kill ` messages . Kill things .""" | try :
if message . job_id in self . _container_for_job :
self . _containers_killed [ self . _container_for_job [ message . job_id ] ] = "killed"
await self . _docker . kill_container ( self . _container_for_job [ message . job_id ] )
else :
self . _logger . warning ( "Cannot kill contain... |
def _create_context_manager ( self , mode ) :
"Create a context manager that sends ' mode ' commands to the client ." | class mode_context_manager ( object ) :
def __enter__ ( * a ) :
self . send_packet ( { 'cmd' : 'mode' , 'data' : mode } )
def __exit__ ( * a ) :
self . send_packet ( { 'cmd' : 'mode' , 'data' : 'restore' } )
return mode_context_manager ( ) |
def collapse_short_branches ( self , threshold ) :
'''Collapse internal branches ( not terminal branches ) with length less than or equal to ` ` threshold ` ` . A branch length of ` ` None ` ` is considered 0
Args :
` ` threshold ` ` ( ` ` float ` ` ) : The threshold to use when collapsing branches''' | if not isinstance ( threshold , float ) and not isinstance ( threshold , int ) :
raise RuntimeError ( "threshold must be an integer or a float" )
elif threshold < 0 :
raise RuntimeError ( "threshold cannot be negative" )
q = deque ( ) ;
q . append ( self . root )
while len ( q ) != 0 :
next = q . popleft ( ... |
def difference ( self , * others ) :
"""Return the difference of two or more sets as a new set .
> > > from ngram import NGram
> > > a = NGram ( [ ' spam ' , ' eggs ' ] )
> > > b = NGram ( [ ' spam ' , ' ham ' ] )
> > > list ( a . difference ( b ) )
[ ' eggs ' ]""" | return self . copy ( super ( NGram , self ) . difference ( * others ) ) |
def post ( self , path , data = None , json_data = None , params = None ) :
"""Perform POST request""" | r = requests . post ( url = self . url + path , data = data , json = json_data , params = params , timeout = self . timeout )
try :
r . raise_for_status ( )
except requests . exceptions . HTTPError :
raise SwitcheoApiException ( r . json ( ) [ 'error_code' ] , r . json ( ) [ 'error_message' ] , r . json ( ) [ '... |
def label ( self , request , tag ) :
"""Render the label of the wrapped L { Parameter } or L { ChoiceParameter } instance .""" | if self . parameter . label :
tag [ self . parameter . label ]
return tag |
def get_software_info ( self ) :
"""Return the current software status .""" | self . request ( EP_GET_SOFTWARE_INFO )
return { } if self . last_response is None else self . last_response . get ( 'payload' ) |
def cli ( ctx , profile , region , lambda_fn , config , debug ) :
"""cruddy is a CLI interface to the cruddy handler . It can be used in one
of two ways .
First , you can pass in a ` ` - - config ` ` option which is a JSON file
containing all of your cruddy parameters and the CLI will create a cruddy
handle... | ctx . obj = CLIHandler ( profile , region , lambda_fn , config , debug ) |
def ungrant_role ( self , principal , role , object = None ) :
"""Ungrant ` role ` to ` user ` ( either globally , if ` object ` is None , or
on the specific ` object ` ) .""" | assert principal
principal = unwrap ( principal )
session = object_session ( object ) if object is not None else db . session
manager = self . _current_user_manager ( session = session )
args = { "role" : role , "object" : object , "anonymous" : False , "user" : None , "group" : None , }
query = session . query ( RoleA... |
def seek ( self , pos , whence = _SEEK_SET ) :
"""Set the current position of this file .
: Parameters :
- ` pos ` : the position ( or offset if using relative
positioning ) to seek to
- ` whence ` ( optional ) : where to seek
from . : attr : ` os . SEEK _ SET ` ( ` ` 0 ` ` ) for absolute file
positioni... | if whence == _SEEK_SET :
new_pos = pos
elif whence == _SEEK_CUR :
new_pos = self . __position + pos
elif whence == _SEEK_END :
new_pos = int ( self . length ) + pos
else :
raise IOError ( 22 , "Invalid value for `whence`" )
if new_pos < 0 :
raise IOError ( 22 , "Invalid value for `pos` - must be pos... |
def rules ( self , x , y ) : # type : ( int , int ) - > List [ Type [ Rule ] ]
"""Get rules at specific position in the structure .
: param x : X coordinate
: param y : Y coordinate
: return : List of rules""" | return [ r for r in self . _field [ y ] [ x ] ] |
def monitored ( name , ** params ) :
'''Makes sure an URL is monitored by uptime . Checks if URL is already
monitored , and if not , adds it .''' | ret = { 'name' : name , 'changes' : { } , 'result' : None , 'comment' : '' }
if __salt__ [ 'uptime.check_exists' ] ( name = name ) :
ret [ 'result' ] = True
ret [ 'comment' ] = 'URL {0} is already monitored' . format ( name )
ret [ 'changes' ] = { }
return ret
if not __opts__ [ 'test' ] :
url_monito... |
def trunc ( qstart , qend , sstart , send , qlen , slen ) :
"""Check if a query sequence is truncated by the end of a subject sequence
Args :
qstart ( int pandas . Series ) : Query sequence start index
qend ( int pandas . Series ) : Query sequence end index
sstart ( int pandas . Series ) : Subject sequence ... | ssum2 = ( send + sstart ) / 2.0
sabs2 = np . abs ( send - sstart ) / 2.0
smax = ssum2 + sabs2
smin = ssum2 - sabs2
q_match_len = np . abs ( qstart - qend ) + 1
return ( q_match_len < qlen ) & ( ( smax >= slen ) | ( smin <= 1 ) ) |
def opened ( self ) :
"""Handler called when the WebSocket connection is opened . The first
thing to do then is to authenticate ourselves .""" | request = { 'type' : 'authenticate' , 'token' : self . _token , 'userAgent' : '{} ws4py/{}' . format ( version . user_agent , ws4py . __version__ ) , }
self . send ( json . dumps ( request ) ) |
def is_writeable ( value , ** kwargs ) :
"""Indicate whether ` ` value ` ` is a writeable file .
. . caution : :
This validator does * * NOT * * work correctly on a Windows file system . This
is due to the vagaries of how Windows manages its file system and the
various ways in which it can manage file permi... | if sys . platform in [ 'win32' , 'cygwin' ] :
raise NotImplementedError ( 'not supported on Windows' )
try :
validators . writeable ( value , allow_empty = False , ** kwargs )
except SyntaxError as error :
raise error
except Exception :
return False
return True |
def email ( self , repo , event , fields , dryrun = False ) :
"""Sends an email to the configured recipients for the specified event .
: arg repo : the name of the repository to include in the email subject .
: arg event : one of [ " start " , " success " , " failure " , " timeout " , " error " ] .
: arg fiel... | tcontents = self . _get_template ( event , "txt" , fields )
hcontents = self . _get_template ( event , "html" , fields )
if tcontents is not None and hcontents is not None :
return Email ( self . server , repo , self . settings [ repo ] , tcontents , hcontents , dryrun ) |
def posterior_to_xarray ( self ) :
"""Convert the posterior to an xarray dataset .""" | var_names = self . pymc3 . util . get_default_varnames ( # pylint : disable = no - member
self . trace . varnames , include_transformed = False )
data = { }
for var_name in var_names :
data [ var_name ] = np . array ( self . trace . get_values ( var_name , combine = False , squeeze = False ) )
return dict_to_datase... |
def initialize_worker ( self , process_num = None ) :
"""inits producer for a simulation run on a single process""" | for p in self . producers :
p . initialize_worker ( process_num )
# self . initial _ state . process = process _ num
self . random . seed ( hash ( self . seed ) + hash ( process_num ) ) |
def _try_coerce_args ( self , values , other ) :
"""provide coercion to our input arguments""" | if np . any ( notna ( other ) ) and not self . _can_hold_element ( other ) : # coercion issues
# let higher levels handle
raise TypeError ( "cannot convert {} to an {}" . format ( type ( other ) . __name__ , type ( self ) . __name__ . lower ( ) . replace ( 'Block' , '' ) ) )
return values , other |
def save ( self ) :
"""Convert to JSON .
Returns
` dict `
JSON data .""" | data = super ( ) . save ( )
data [ 'state_sizes' ] = self . state_sizes
data [ 'reset_on_sentence_end' ] = self . reset_on_sentence_end
return data |
def delete ( gandi , domain , zone_id , name , type , value ) :
"""Delete a record entry for a domain""" | if not zone_id :
result = gandi . domain . info ( domain )
zone_id = result [ 'zone_id' ]
if not zone_id :
gandi . echo ( 'No zone records found, domain %s doesn\'t seems to be ' 'managed at Gandi.' % domain )
return
if not name and not type and not value :
proceed = click . confirm ( 'This command ... |
def get_revision_history ( brain_or_object ) :
"""Get the revision history for the given brain or context .
: param brain _ or _ object : A single catalog brain or content object
: type brain _ or _ object : ATContentType / DexterityContentType / CatalogBrain
: returns : Workflow history
: rtype : obj""" | obj = get_object ( brain_or_object )
chv = ContentHistoryView ( obj , safe_getattr ( obj , "REQUEST" , None ) )
return chv . fullHistory ( ) |
def parse_options ( ) :
"""Parse command line arguments .
Returns :
options , args""" | parser = argparse . ArgumentParser ( description = 'Video downloader by radzak.' , prog = 'RTVdownloader' )
urls_group = parser . add_mutually_exclusive_group ( required = True )
urls_group . add_argument ( 'urls' , type = str , metavar = 'URL' , default = [ ] , nargs = '*' , help = 'urls of sites containing videos you... |
def do_options ( self , labels : Sequence [ str ] , values : Sequence [ Union [ str , int ] ] ) -> Sequence [ Dict ] :
"""Replace the checkbox options .
Parameters
labels : array - like
List of strings which will be visible to the user .
values : array - like
List of values associated with the labels that... | return [ { 'label' : label , 'value' : value } for label , value in zip ( labels , values ) ] |
def writelines_nl ( fileobj : TextIO , lines : Iterable [ str ] ) -> None :
"""Writes lines , plus terminating newline characters , to the file .
( Since : func : ` fileobj . writelines ` doesn ' t add newlines . . .
http : / / stackoverflow . com / questions / 13730107 / writelines - writes - lines - without -... | # noqa
fileobj . write ( '\n' . join ( lines ) + '\n' ) |
def get_term_before ( aterm ) :
"""Returns a uw _ sws . models . Term object ,
for the term before the term given .""" | prev_year = aterm . year
prev_quarter = QUARTER_SEQ [ QUARTER_SEQ . index ( aterm . quarter ) - 1 ]
if prev_quarter == "autumn" :
prev_year -= 1
return get_term_by_year_and_quarter ( prev_year , prev_quarter ) |
def execute ( self , time_interval ) :
"""Execute the factor over the given time interval . Note that this is normally done by the workflow ,
but can also be done on the factor directly
: param time _ interval : The time interval
: return : self ( for chaining )""" | logging . info ( '{} running from {} to {}' . format ( self . tool . __class__ . __name__ , time_interval . start , time_interval . end ) )
# Execute the tool to produce the output plate values
output_plate_values = { }
if self . input_plate :
for ipv in self . input_plate . values :
if ipv in self . source... |
def from_files ( controller , track_path , log_level = logging . ERROR ) :
"""Create rocket instance using project file connector""" | rocket = Rocket ( controller , track_path = track_path , log_level = log_level )
rocket . connector = FilesConnector ( track_path , controller = controller , tracks = rocket . tracks )
return rocket |
def draw_categories ( self ) :
"""Draw the category labels on the Canvas""" | for label in self . _category_labels . values ( ) :
label . destroy ( )
self . _category_labels . clear ( )
canvas_width = 0
for category in ( sorted ( self . _categories . keys ( ) if isinstance ( self . _categories , dict ) else self . _categories ) if not isinstance ( self . _categories , OrderedDict ) else self... |
def condor_submit ( submit_file ) :
"""Submit a condor job described by the given file . Parse an external id for
the submission or return None and a reason for the failure .""" | external_id = None
try :
submit = Popen ( ( 'condor_submit' , submit_file ) , stdout = PIPE , stderr = STDOUT )
message , _ = submit . communicate ( )
if submit . returncode == 0 :
external_id = parse_external_id ( message , type = 'condor' )
else :
message = PROBLEM_PARSING_EXTERNAL_ID
... |
async def wait ( self , timeout = None ) :
"""Wait for this operation to finish .
You can specify an optional timeout that defaults to no timeout if
None is passed . The result of the operation is returned from this
method . If the operation raised an exception , it is reraised from this
method .
Args :
... | await asyncio . wait_for ( self . _future , timeout )
if self . _exception is not None :
self . _raise_exception ( )
return self . _result |
def handle_receive ( request : RequestType , user : UserType = None , sender_key_fetcher : Callable [ [ str ] , str ] = None , skip_author_verification : bool = False ) -> Tuple [ str , str , List ] :
"""Takes a request and passes it to the correct protocol .
Returns a tuple of :
- sender id
- protocol name
... | logger . debug ( "handle_receive: processing request: %s" , request )
found_protocol = identify_protocol_by_request ( request )
logger . debug ( "handle_receive: using protocol %s" , found_protocol . PROTOCOL_NAME )
protocol = found_protocol . Protocol ( )
sender , message = protocol . receive ( request , user , sender... |
def verify ( self , proof , chal , state ) :
"""This returns True if the proof matches the challenge and file state
: param proof : the proof that was returned from the server
: param chal : the challenge sent to the server
: param state : the state of the file , which can be encrypted""" | state . decrypt ( self . key )
index = KeyedPRF ( chal . key , state . chunks )
v = KeyedPRF ( chal . key , chal . v_max )
f = KeyedPRF ( state . f_key , self . prime )
alpha = KeyedPRF ( state . alpha_key , self . prime )
rhs = 0
for i in range ( 0 , chal . chunks ) :
rhs += v . eval ( i ) * f . eval ( index . eva... |
def _compute_mfcc_pure_python ( self ) :
"""Compute MFCCs using the pure Python code .""" | self . log ( u"Computing MFCCs using pure Python code..." )
try :
self . __mfcc = MFCC ( rconf = self . rconf , logger = self . logger ) . compute_from_data ( self . audio_file . audio_samples , self . audio_file . audio_sample_rate ) . transpose ( )
self . log ( u"Computing MFCCs using pure Python code... done... |
def process_exception ( self , request , exception ) :
"""Log error info when exception occurred .""" | log_format = self . _get_log_format ( request )
if log_format is None :
return
params = self . _get_parameters_from_request ( request , True )
params [ 'message' ] = exception
params [ 'http_status' ] = '-'
self . OPERATION_LOG . info ( log_format , params ) |
def new_max_pool ( self , name : str , kernel_size : tuple , stride_size : tuple , padding = 'SAME' , input_layer_name : str = None ) :
"""Creates a new max pooling layer .
: param name : name for the layer .
: param kernel _ size : tuple containing the size of the kernel ( Width , Height )
: param stride _ s... | self . __validate_padding ( padding )
input_layer = self . __network . get_layer ( input_layer_name )
output = tf . nn . max_pool ( input_layer , ksize = [ 1 , kernel_size [ 1 ] , kernel_size [ 0 ] , 1 ] , strides = [ 1 , stride_size [ 1 ] , stride_size [ 0 ] , 1 ] , padding = padding , name = name )
self . __network .... |
def parse_localclasspath ( self , tup_tree ) :
"""Parse a LOCALCLASSPATH element and return the class path it represents
as a CIMClassName object .
< ! ELEMENT LOCALCLASSPATH ( LOCALNAMESPACEPATH , CLASSNAME ) >""" | self . check_node ( tup_tree , 'LOCALCLASSPATH' )
k = kids ( tup_tree )
if len ( k ) != 2 :
raise CIMXMLParseError ( _format ( "Element {0!A} has invalid number of child elements " "{1!A} (expecting two child elements " "(LOCALNAMESPACEPATH, CLASSNAME))" , name ( tup_tree ) , k ) , conn_id = self . conn_id )
namesp... |
def findSettingsModule ( ) :
"Find the settings module dot path within django ' s manage . py file" | try :
with open ( 'manage.py' , 'r' ) as manage :
manage_contents = manage . read ( )
search = re . search ( r"([\"\'](?P<module>[a-z\.]+)[\"\'])" , manage_contents )
if search : # django version < 1.7
settings_mod = search . group ( "module" )
else : # in 1.7 , manage . ... |
def pk_prom ( word ) :
'''Return the number of stressed light syllables .''' | LIGHT = r'[ieaAoO]{1}[\.]*(u|y)(\.|$)'
# # if the word is not monosyllabic , lop off the final syllable , which is
# # extrametrical
# if ' . ' in word :
# word = word [ : word . rindex ( ' . ' ) ]
# gather the indices of syllable boundaries
delimiters = [ 0 , ] + [ i for i , char in enumerate ( word ) if char == '.' ]... |
def compute ( self ) :
"""Compute and return one solution . This method checks whether the
hard part of the formula is satisfiable , i . e . an MCS can be
extracted . If the formula is satisfiable , the model computed by the
SAT call is used as an * over - approximation * of the MCS in the
method : func : `... | self . setd = [ ]
self . satc = [ False for cl in self . soft ]
# satisfied clauses
self . solution = None
self . bb_assumps = [ ]
# backbone assumptions
self . ss_assumps = [ ]
# satisfied soft clause assumptions
if self . oracle . solve ( ) : # hard part is satisfiable = > there is a solution
self . _filter_satis... |
def includeRect ( self , r ) :
"""Extend rectangle to include rectangle r .""" | if not len ( r ) == 4 :
raise ValueError ( "bad sequ. length" )
self . x0 , self . y0 , self . x1 , self . y1 = TOOLS . _union_rect ( self , r )
return self |
def is_contradictory ( self , other ) :
"""Returns True if the two DictCells are unmergeable .""" | if not isinstance ( other , DictCell ) :
raise Exception ( "Incomparable" )
for key , val in self :
if key in other . __dict__ [ 'p' ] and val . is_contradictory ( other . __dict__ [ 'p' ] [ key ] ) :
return True
return False |
def _process_change ( self , payload , user , repo , repo_url , project , event , properties ) :
"""Consumes the JSON as a python object and actually starts the build .
: arguments :
payload
Python Object that represents the JSON sent by GitHub Service
Hook .""" | changes = [ ]
refname = payload [ 'ref' ]
# We only care about regular heads or tags
match = re . match ( r"^refs/(heads|tags)/(.+)$" , refname )
if not match :
log . msg ( "Ignoring refname `{}': Not a branch" . format ( refname ) )
return changes
category = None
# None is the legacy category for when hook onl... |
def mm_top1 ( n_items , data , initial_params = None , alpha = 0.0 , max_iter = 10000 , tol = 1e-8 ) :
"""Compute the ML estimate of model parameters using the MM algorithm .
This function computes the maximum - likelihood ( ML ) estimate of model
parameters given top - 1 data ( see : ref : ` data - top1 ` ) , ... | return _mm ( n_items , data , initial_params , alpha , max_iter , tol , _mm_top1 ) |
def _button_plus_clicked ( self , n ) :
"""Create a new colorpoint .""" | self . _button_save . setEnabled ( True )
self . insert_colorpoint ( self . _colorpoint_list [ n ] [ 0 ] , self . _colorpoint_list [ n ] [ 1 ] , self . _colorpoint_list [ n ] [ 2 ] )
self . _build_gui ( ) |
def cmd ( ) :
"""Help to run the command line
: return :""" | if os . path . isfile ( os . path . join ( os . path . join ( CWD , "juicy.py" ) ) ) :
import_module ( "juicy" )
else :
print ( "ERROR: Missing <<'juicy.py'>> @ %s" % CWD )
cli ( ) |
def async_refresh ( self , * args , ** kwargs ) :
"""Trigger an asynchronous job to refresh the cache""" | # We trigger the task with the class path to import as well as the
# ( a ) args and kwargs for instantiating the class
# ( b ) args and kwargs for calling the ' refresh ' method
try :
enqueue_task ( dict ( klass_str = self . class_path , obj_args = self . get_init_args ( ) , obj_kwargs = self . get_init_kwargs ( ) ... |
def _dataset_concat ( datasets , dim , data_vars , coords , compat , positions ) :
"""Concatenate a sequence of datasets along a new or existing dimension""" | from . dataset import Dataset
if compat not in [ 'equals' , 'identical' ] :
raise ValueError ( "compat=%r invalid: must be 'equals' " "or 'identical'" % compat )
dim , coord = _calc_concat_dim_coord ( dim )
# Make sure we ' re working on a copy ( we ' ll be loading variables )
datasets = [ ds . copy ( ) for ds in d... |
def from_xdr ( cls , xdr ) :
"""Create an : class : ` Asset ` object from its base64 encoded XDR
representation .
: param bytes xdr : The base64 encoded XDR Asset object .
: return : A new : class : ` Asset ` object from its encoded XDR
representation .""" | xdr_decoded = base64 . b64decode ( xdr )
asset = Xdr . StellarXDRUnpacker ( xdr_decoded )
asset_xdr_object = asset . unpack_Asset ( )
asset = Asset . from_xdr_object ( asset_xdr_object )
return asset |
def __data_url ( self ) :
"""URL for posting metrics to the host agent . Only valid when announced .""" | path = AGENT_DATA_PATH % self . from_ . pid
return "http://%s:%s/%s" % ( self . host , self . port , path ) |
def dataflow_to_dataset ( df , types ) :
"""Wrap a dataflow to tf . data . Dataset .
This function will also reset the dataflow .
If the dataflow itself is finite , the returned dataset is also finite .
Therefore , if used for training , you ' ll need to add ` . repeat ( ) ` on the returned
dataset .
Args... | # TODO theoretically it can support dict
assert isinstance ( df , DataFlow ) , df
assert isinstance ( types , ( list , tuple ) ) , types
df = MapData ( df , lambda dp : tuple ( dp ) )
df . reset_state ( )
ds = tf . data . Dataset . from_generator ( df . get_data , tuple ( types ) )
return ds |
def _draw_frame ( self , framedata ) :
"""Reads , processes and draws the frames .
If needed for color maps , conversions to gray scale are performed . In
case the images are no color images and no custom color maps are
defined , the colormap ` gray ` is applied .
This function is called by TimedAnimation .... | original = self . read_frame ( )
if original is None :
self . update_info ( self . info_string ( message = 'Finished.' , frame = framedata ) )
return
if self . original is not None :
processed = self . process_frame ( original . copy ( ) )
if self . cmap_original is not None :
original = to_gray... |
def get_region ( self , move_x , move_y ) :
"""Get region around a location .""" | top_left = ( max ( move_y - 1 , 0 ) , max ( move_x - 1 , 0 ) )
bottom_right = ( min ( move_y + 1 , self . board_height - 1 ) , min ( move_x + 1 , self . board_width - 1 ) )
region_sum = self . mine_map [ top_left [ 0 ] : bottom_right [ 0 ] + 1 , top_left [ 1 ] : bottom_right [ 1 ] + 1 ] . sum ( )
return top_left , bott... |
def generate_completions ( event ) :
r"""Tab - completion : where the first tab completes the common suffix and the
second tab lists all the completions .""" | b = event . current_buffer
# When already navigating through completions , select the next one .
if b . complete_state :
b . complete_next ( )
else :
event . cli . start_completion ( insert_common_part = True , select_first = False ) |
def _scale_to_int ( X , max_val = None ) :
"""Scales the array X such that it contains only integers .""" | if max_val is None :
X = X / _gcd_array ( X )
else :
X = X / max ( 1 / max_val , _gcd_array ( X ) )
return [ int ( entry ) for entry in X ] |
def generate_model ( self , model_name = None , outfile = None ) :
"""Generate a counts model map from an XML model file using
gtmodel .
Parameters
model _ name : str
Name of the model . If no name is given it will use the
baseline model .
outfile : str
Override the name of the output model file .""" | if model_name is not None :
model_name = os . path . splitext ( model_name ) [ 0 ]
if model_name is None or model_name == '' :
srcmdl = self . files [ 'srcmdl' ]
else :
srcmdl = self . get_model_path ( model_name )
if not os . path . isfile ( srcmdl ) :
raise Exception ( "Model file does not exist: %s" ... |
def get ( key , default = - 1 ) :
"""Backport support for original codes .""" | if isinstance ( key , int ) :
return Setting ( key )
if key not in Setting . _member_map_ :
extend_enum ( Setting , key , default )
return Setting [ key ] |
def run_cortex ( align_bams , items , ref_file , assoc_files , region = None , out_file = None ) :
"""Top level entry to regional de - novo based variant calling with cortex _ var .""" | raise NotImplementedError ( "Cortex currently out of date and needs reworking." )
if len ( align_bams ) == 1 :
align_bam = align_bams [ 0 ]
config = items [ 0 ] [ "config" ]
else :
raise NotImplementedError ( "Need to add multisample calling for cortex_var" )
if out_file is None :
out_file = "%s-cortex.... |
def parse_header ( input_array ) :
"""Parse the header and return it along with the input array minus the header .
: param input _ array the array to parse
: return the codec , the length of the decoded array , the parameter and the remainder
of the array""" | codec = struct . unpack ( mmtf . utils . constants . NUM_DICT [ 4 ] , input_array [ 0 : 4 ] ) [ 0 ]
length = struct . unpack ( mmtf . utils . constants . NUM_DICT [ 4 ] , input_array [ 4 : 8 ] ) [ 0 ]
param = struct . unpack ( mmtf . utils . constants . NUM_DICT [ 4 ] , input_array [ 8 : 12 ] ) [ 0 ]
return codec , len... |
def render_registration ( self ) :
'''Render pinned points on video frame as red rectangle .''' | surface = self . get_surface ( )
if self . canvas is None or self . df_canvas_corners . shape [ 0 ] == 0 :
return surface
corners = self . df_canvas_corners . copy ( )
corners [ 'w' ] = 1
transform = self . canvas . shapes_to_canvas_transform
canvas_corners = corners . values . dot ( transform . T . values ) . T
po... |
def _sort_records_map ( records ) :
"""Map function sorting records .
Converts records to KeyValue protos , sorts them by key and writes them
into new GCS file . Creates _ OutputFile entity to record resulting
file name .
Args :
records : list of records which are serialized KeyValue protos .""" | ctx = context . get ( )
l = len ( records )
key_records = [ None ] * l
logging . debug ( "Parsing" )
for i in range ( l ) :
proto = kv_pb . KeyValue ( )
proto . ParseFromString ( records [ i ] )
key_records [ i ] = ( proto . key ( ) , records [ i ] )
logging . debug ( "Sorting" )
key_records . sort ( cmp = ... |
def cast ( keys , data ) :
"""Cast a set of keys and an array to a Matrix object .""" | matrix = Matrix ( )
matrix . keys = keys
matrix . data = data
return matrix |
def _get_template ( self , template_name , template_file ) :
"""Returns a Jinja2 template of the specified file .""" | template = os . path . join ( self . location , 'templates' , template_name , template_file )
return jinja2 . Template ( open ( template ) . read ( ) ) |
def send ( self , message_type , data , callback = None , one_way = False ) :
"""Sends a message of message _ type
Args :
message _ type ( validator _ pb2 . Message ) : enum value
data ( bytes ) : serialized protobuf
callback ( function ) : a callback function to call when a
response to this message is re... | message = validator_pb2 . Message ( correlation_id = _generate_id ( ) , content = data , message_type = message_type )
fut = future . Future ( message . correlation_id , message . content , callback , timeout = self . _connection_timeout )
if not one_way :
self . _futures . put ( fut )
self . _send_receive_thread .... |
def get ( self , template_name ) :
"""Get a specific template""" | template = db . Template . find_one ( template_name = template_name )
if not template :
return self . make_response ( 'No such template found' , HTTP . NOT_FOUND )
return self . make_response ( { 'template' : template } ) |
def openlines ( image , linelength = 10 , dAngle = 10 , mask = None ) :
"""Do a morphological opening along lines of different angles .
Return difference between max and min response to different angles for each pixel .
This effectively removes dots and only keeps lines .
image - pixel image to operate on
l... | nAngles = 180 // dAngle
openingstack = np . zeros ( ( nAngles , image . shape [ 0 ] , image . shape [ 1 ] ) , image . dtype )
for iAngle in range ( nAngles ) :
angle = dAngle * iAngle
se = strel_line ( linelength , angle )
openingstack [ iAngle , : , : ] = opening ( image , mask = mask , footprint = se )
im... |
def clone ( self , document ) :
'''Serialize a document , remove its _ id , and deserialize as a new
object''' | wrapped = document . wrap ( )
if '_id' in wrapped :
del wrapped [ '_id' ]
return type ( document ) . unwrap ( wrapped , session = self ) |
def _download_log ( self , url , output_file ) :
"""Saves log returned by the message bus .""" | logger . info ( "Saving log %s to %s" , url , output_file )
def _do_log_download ( ) :
try :
return self . session . get ( url )
# pylint : disable = broad - except
except Exception as err :
logger . error ( err )
# log file may not be ready yet , wait a bit
for __ in range ( 5 ) :
log_d... |
def delete_firewall_rule ( self , firewall_rule ) :
'''Deletes the specified firewall rule''' | firewall_rule_id = self . _find_firewall_rule_id ( firewall_rule )
ret = self . network_conn . delete_firewall_rule ( firewall_rule_id )
return ret if ret else True |
def to_lines ( s ) :
"""Like ` str . splitlines ( ) ` , except that an empty string results in a
one - element list and a trailing newline results in a trailing empty string
( and all without re - implementing Python ' s changing line - splitting
algorithm ) .
> > > to _ lines ( ' ' )
> > > to _ lines ( '... | lines = s . splitlines ( True )
if not lines :
return [ '' ]
if lines [ - 1 ] . splitlines ( ) != [ lines [ - 1 ] ] :
lines . append ( '' )
for i , l in enumerate ( lines ) :
l2 = l . splitlines ( )
assert len ( l2 ) in ( 0 , 1 )
lines [ i ] = l2 [ 0 ] if l2 else ''
if PY2 and isinstance ( s , str )... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.