signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def parseLines ( self ) :
"""Form an AST for the code and produce a new version of the source .""" | inAst = parse ( '' . join ( self . lines ) , self . inFilename )
# Visit all the nodes in our tree and apply Doxygen tags to the source .
self . visit ( inAst ) |
def get_details ( self ) :
"""Finds songs details
: return : Dictionary with songs details about title , artist , album and
year""" | title = str ( self . get_title ( ) ) . strip ( )
artist = str ( self . get_artist ( ) ) . strip ( )
album = str ( self . get_album ( ) ) . strip ( )
year = str ( self . get_year ( ) ) . strip ( )
return { "title" : title , "artist" : artist , "album" : album , "year" : year } |
def get_task_runs ( self , json_file = None ) :
"""Load all project Task Runs from Tasks .""" | if self . project is None :
raise ProjectError
loader = create_task_runs_loader ( self . project . id , self . tasks , json_file , self . all )
self . task_runs , self . task_runs_file = loader . load ( )
self . _check_project_has_taskruns ( )
self . task_runs_df = dataframer . create_task_run_data_frames ( self . ... |
def _get_federation_info ( address_or_id , federation_service , fed_type = 'name' ) :
"""Send a federation query to a Stellar Federation service .
Note : The preferred method of making this call is via
: function : ` federation ` , as it handles error checking and parsing of
arguments .
: param str address ... | params = { 'q' : address_or_id , 'type' : fed_type }
r = requests . get ( federation_service , params = params )
if r . status_code == 200 :
return r . json ( )
else :
return None |
def pkt_check ( * args , func = None ) :
"""Check if arguments are valid packets .""" | func = func or inspect . stack ( ) [ 2 ] [ 3 ]
for var in args :
dict_check ( var , func = func )
dict_check ( var . get ( 'frame' ) , func = func )
enum_check ( var . get ( 'protocol' ) , func = func )
real_check ( var . get ( 'timestamp' ) , func = func )
ip_check ( var . get ( 'src' ) , var . get... |
def get_msgs_for_lagged_nodes ( self ) -> List [ ViewChangeDone ] : # Should not return a list , only done for compatibility with interface
"""Returns the last accepted ` ViewChangeDone ` message .
If no view change has happened returns ViewChangeDone
with view no 0 to a newly joined node""" | # TODO : Consider a case where more than one node joins immediately ,
# then one of the node might not have an accepted
# ViewChangeDone message
messages = [ ]
accepted = self . _accepted_view_change_done_message
if accepted :
messages . append ( ViewChangeDone ( self . last_completed_view_no , * accepted ) )
elif ... |
def replace_by_field ( self , field_name , field_value , fields , typecast = False , ** options ) :
"""Replaces the first record to match field name and value .
All Fields are updated to match the new ` ` fields ` ` provided .
If a field is not included in ` ` fields ` ` , value will bet set to null .
To upda... | record = self . match ( field_name , field_value , ** options )
return { } if not record else self . replace ( record [ 'id' ] , fields , typecast ) |
def get_file_service_properties ( self , timeout = None ) :
'''Gets the properties of a storage account ' s File service , including
Azure Storage Analytics .
: param int timeout :
The timeout parameter is expressed in seconds .
: return : The file service properties .
: rtype :
: class : ` ~ azure . st... | request = HTTPRequest ( )
request . method = 'GET'
request . host_locations = self . _get_host_locations ( )
request . path = _get_path ( )
request . query = { 'restype' : 'service' , 'comp' : 'properties' , 'timeout' : _int_to_str ( timeout ) , }
return self . _perform_request ( request , _convert_xml_to_service_prope... |
def read_detections ( fname ) :
"""Read detections from a file to a list of Detection objects .
: type fname : str
: param fname : File to read from , must be a file written to by Detection . write .
: returns : list of : class : ` eqcorrscan . core . match _ filter . Detection `
: rtype : list
. . note :... | f = open ( fname , 'r' )
detections = [ ]
for index , line in enumerate ( f ) :
if index == 0 :
continue
# Skip header
if line . rstrip ( ) . split ( '; ' ) [ 0 ] == 'Template name' :
continue
# Skip any repeated headers
detection = line . rstrip ( ) . split ( '; ' )
dete... |
def _parse_cli_args ( ) :
"""Parse the arguments from CLI using ArgumentParser
: return : The arguments parsed by ArgumentParser
: rtype : Namespace""" | parser = argparse . ArgumentParser ( )
parser . add_argument ( '-g' , help = 'The photoset id to be downloaded' , metavar = '<photoset_id>' )
parser . add_argument ( '-s' , default = 1 , help = ( 'Image size. 12 is smallest, 1 is original size. ' 'Default: 1' ) , type = int , choices = xrange ( 0 , 10 ) , metavar = '<n... |
def log ( self , n = None , ** kwargs ) :
"""Run the repository log command
Returns :
str : output of log command ( ` ` git log - n < n > < - - kwarg = value > ` ` )""" | kwargs [ 'format' ] = kwargs . pop ( 'template' , self . template )
cmd = [ 'git' , 'log' ]
if n :
cmd . append ( '-n%d' % n )
cmd . extend ( ( ( '--%s=%s' % ( k , v ) ) for ( k , v ) in iteritems ( kwargs ) ) )
try :
output = self . sh ( cmd , shell = False )
if "fatal: bad default revision 'HEAD'" in outp... |
def raw_xml ( self ) -> _RawXML :
"""Bytes representation of the XML content .
( ` learn more < http : / / www . diveintopython3 . net / strings . html > ` _ ) .""" | if self . _xml :
return self . _xml
else :
return etree . tostring ( self . element , encoding = 'unicode' ) . strip ( ) . encode ( self . encoding ) |
def diffuser_conical ( Di1 , Di2 , l = None , angle = None , fd = None , Re = None , roughness = 0.0 , method = 'Rennels' ) :
r'''Returns the loss coefficient for any conical pipe diffuser .
This calculation has four methods available .
The ' Rennels ' [ 1 ] _ formulas are as follows ( three different formulas ... | beta = Di1 / Di2
beta2 = beta * beta
if angle is not None :
angle_rad = radians ( angle )
l = ( Di2 - Di1 ) / ( 2.0 * tan ( 0.5 * angle_rad ) )
elif l is not None :
angle_rad = 2.0 * atan ( 0.5 * ( Di2 - Di1 ) / l )
angle = degrees ( angle_rad )
else :
raise Exception ( 'Either `l` or `angle` must b... |
def get_xy_dataset_statistics_pandas ( dataframe , x_series , y_series , fcorrect_x_cutoff = 1.0 , fcorrect_y_cutoff = 1.0 , x_fuzzy_range = 0.1 , y_scalar = 1.0 , ignore_null_values = False , bootstrap_data = False , expect_negative_correlation = False , STDev_cutoff = 1.0 , run_standardized_analysis = True , check_mu... | x_values = dataframe [ x_series ] . tolist ( )
y_values = dataframe [ y_series ] . tolist ( )
return _get_xy_dataset_statistics ( x_values , y_values , fcorrect_x_cutoff = fcorrect_x_cutoff , fcorrect_y_cutoff = fcorrect_y_cutoff , x_fuzzy_range = x_fuzzy_range , y_scalar = y_scalar , ignore_null_values = ignore_null_v... |
def all_synonyms ( self , include_label = False ) :
"""Retrieves all synonyms
Arguments
include _ label : bool
If True , include label / names as Synonym objects
Returns
list [ Synonym ]
: class : ` Synonym ` objects""" | syns = [ ]
for n in self . nodes ( ) :
syns = syns + self . synonyms ( n , include_label = include_label )
return syns |
def update ( self , response , ** kwargs ) :
'''If a record matching the instance already exists in the database , update
both the column and venue column attributes , else create a new record .''' | response_cls = super ( LocationResponseClassLegacyAccessor , self ) . _get_instance ( ** kwargs )
if response_cls :
setattr ( response_cls , self . column , self . accessor ( response ) )
setattr ( response_cls , self . venue_column , self . venue_accessor ( response ) )
_action_and_commit ( response_cls , ... |
def positioning_headlines ( headlines ) :
"""Strips unnecessary whitespaces / tabs if first header is not left - aligned""" | left_just = False
for row in headlines :
if row [ - 1 ] == 1 :
left_just = True
break
if not left_just :
for row in headlines :
row [ - 1 ] -= 1
return headlines |
def get_null_snr ( self ) :
"""Get the coherent Null SNR for this row .""" | null_snr_sq = ( numpy . asarray ( self . get_sngl_snrs ( ) . values ( ) ) ** 2 ) . sum ( ) - self . snr ** 2
if null_snr_sq < 0 :
return 0
else :
return null_snr_sq ** ( 1. / 2. ) |
def rank ( self ) :
"""Returns an ` ` int ` ` of the team ' s rank at the time the game was played .""" | rank = re . findall ( r'\d+' , self . _rank )
if len ( rank ) == 0 :
return None
return rank [ 0 ] |
def from_numpy ( ndarr , arr , alpha_merge = 0.05 , max_depth = 2 , min_parent_node_size = 30 , min_child_node_size = 30 , split_titles = None , split_threshold = 0 , weights = None , variable_types = None , dep_variable_type = 'categorical' ) :
"""Create a CHAID object from numpy
Parameters
ndarr : numpy . nda... | vectorised_array = [ ]
variable_types = variable_types or [ 'nominal' ] * ndarr . shape [ 1 ]
for ind , col_type in enumerate ( variable_types ) :
title = None
if split_titles is not None :
title = split_titles [ ind ]
if col_type == 'ordinal' :
col = OrdinalColumn ( ndarr [ : , ind ] , name... |
def set_value ( ctx , key , value ) :
"""Assigns values to config file entries . If the value is omitted ,
you will be prompted , with the input hidden if it is sensitive .
$ ddev config set github . user foo
New setting :
[ github ]
user = " foo " """ | scrubbing = False
if value is None :
scrubbing = key in SECRET_KEYS
value = click . prompt ( 'Value for `{}`' . format ( key ) , hide_input = scrubbing )
if key in ( 'core' , 'extras' , 'agent' ) and not value . startswith ( '~' ) :
value = os . path . abspath ( value )
user_config = new_config = ctx . obj
... |
def ratio_area_clay_total ( ConcClay , material , DiamTube , RatioHeightDiameter ) :
"""Return the surface area of clay normalized by total surface area .
Total surface area is a combination of clay and reactor wall
surface areas . This function is used to estimate how much coagulant
actually goes to the clay... | return ( 1 / ( 1 + ( 2 * material . Diameter / ( 3 * DiamTube * ratio_clay_sphere ( RatioHeightDiameter ) * ( ConcClay / material . Density ) ) ) ) ) |
def volume_usage ( self , year = None , month = None ) :
"""Retrieves Cloudant volume usage data , optionally for a given
year and month .
: param int year : Year to query against , for example 2014.
Optional parameter . Defaults to None . If used , it must be
accompanied by ` ` month ` ` .
: param int mo... | endpoint = '/' . join ( ( self . server_url , '_api' , 'v2' , 'usage' , 'data_volume' ) )
return self . _usage_endpoint ( endpoint , year , month ) |
def remove_oxidation_states ( self ) :
"""Removes oxidation states from a structure .""" | for site in self . sites :
new_sp = collections . defaultdict ( float )
for el , occu in site . species . items ( ) :
sym = el . symbol
new_sp [ Element ( sym ) ] += occu
site . species = new_sp |
def read ( cls , iprot ) :
'''Read a new object from the given input protocol and return the object .
: type iprot : thryft . protocol . _ input _ protocol . _ InputProtocol
: rtype : pastpy . gen . database . impl . dummy . dummy _ database _ configuration . DummyDatabaseConfiguration''' | init_kwds = { }
iprot . read_struct_begin ( )
while True :
ifield_name , ifield_type , _ifield_id = iprot . read_field_begin ( )
if ifield_type == 0 : # STOP
break
elif ifield_name == 'images_per_object' :
init_kwds [ 'images_per_object' ] = iprot . read_i32 ( )
elif ifield_name == 'obje... |
def checkout_and_create_branch ( repo , name ) :
"""Checkout branch . Create it if necessary""" | local_branch = repo . branches [ name ] if name in repo . branches else None
if not local_branch :
if name in repo . remotes . origin . refs : # If origin branch exists but not local , git . checkout is the fatest way
# to create local branch with origin link automatically
msg = repo . git . checkout ( ... |
def _maxlength ( X ) :
"""Returns the maximum length of signal trajectories X""" | N = 0
for x in X :
if len ( x ) > N :
N = len ( x )
return N |
def get_organizations ( self , since = github . GithubObject . NotSet ) :
""": calls : ` GET / organizations < http : / / developer . github . com / v3 / orgs # list - all - organizations > ` _
: param since : integer
: rtype : : class : ` github . PaginatedList . PaginatedList ` of : class : ` github . Organiz... | assert since is github . GithubObject . NotSet or isinstance ( since , ( int , long ) ) , since
url_parameters = dict ( )
if since is not github . GithubObject . NotSet :
url_parameters [ "since" ] = since
return github . PaginatedList . PaginatedList ( github . NamedUser . NamedUser , self . __requester , "/organi... |
def discover ( self , ip ) :
'''Discover the network starting at the defined root node IP .
Recursively enumerate the network tree up to self . depth .
Populates self . nodes [ ] as a list of discovered nodes in the
network with self . root _ node being the root .
This function will discover the network wit... | if ( self . verbose > 0 ) :
print ( 'Discovery codes:\n' ' . depth %s connection error\n' ' %s discovering node %s numerating adjacencies\n' ' %s include node %s leaf node\n' % ( DCODE_ERR_SNMP_STR , DCODE_DISCOVERED_STR , DCODE_STEP_INTO_STR , DCODE_INCLUDE_STR , DCODE_LEAF_STR ) )
p... |
def destroy_record ( client = None , found_record = None , record = '' , zone_id = '' ) :
"""Destroy an individual DNS record .
Args :
client ( botocore . client . Route53 ) : Route 53 boto3 client .
found _ record ( dict ) : Route 53 record set : :
{ ' Name ' : ' unicorn . forrest . dev . example . com . '... | LOG . debug ( 'Found DNS record: %s' , found_record )
if found_record [ 'Name' ] . strip ( '.' ) == record :
dns_json = get_template ( template_file = 'destroy/destroy_dns.json.j2' , record = json . dumps ( found_record ) )
dns_dict = json . loads ( dns_json )
client . change_resource_record_sets ( HostedZo... |
def read_chunk_header ( self ) :
'''Read a single chunk ' s header .
Returns :
tuple : 2 - item tuple with the size of the content in the chunk and
the raw header byte string .
Coroutine .''' | # _ logger . debug ( ' Reading chunk . ' )
try :
chunk_size_hex = yield from self . _connection . readline ( )
except ValueError as error :
raise ProtocolError ( 'Invalid chunk size: {0}' . format ( error ) ) from error
if not chunk_size_hex . endswith ( b'\n' ) :
raise NetworkError ( 'Connection closed.' )... |
def encode_request ( request_line , ** headers ) :
'''Creates the data for a SSDP request .
Args :
request _ line ( string ) : The request line for the request ( e . g .
` ` " M - SEARCH * HTTP / 1.1 " ` ` ) .
headers ( dict of string - > string ) : Dictionary of header name - header
value pairs to presen... | lines = [ request_line ]
lines . extend ( [ '%s: %s' % kv for kv in headers . items ( ) ] )
return ( '\r\n' . join ( lines ) + '\r\n\r\n' ) . encode ( 'utf-8' ) |
def emails ( self , qs ) :
"""Single entry with email only in the format of :
my @ address . com ,""" | self . stdout . write ( ",\n" . join ( ent [ 'email' ] for ent in qs ) )
self . stdout . write ( "\n" ) |
def to_csvline ( self , with_header = False ) :
"""Return a string with data in CSV format""" | string = ""
if with_header :
string += "# " + " " . join ( at for at in AbinitTimerSection . FIELDS ) + "\n"
string += ", " . join ( str ( v ) for v in self . to_tuple ( ) ) + "\n"
return string |
def humanise_exception ( exception ) :
"""Humanise a python exception by giving the class name and traceback .
The function will return a tuple with the exception name and the traceback .
: param exception : Exception object .
: type exception : Exception
: return : A tuple with the exception name and the t... | trace = '' . join ( traceback . format_tb ( sys . exc_info ( ) [ 2 ] ) )
name = exception . __class__ . __name__
return name , trace |
def base_recherche_rapide ( self , base , pattern , to_string_hook = None ) :
"""Return a collection of access matching ` pattern ` .
` to _ string _ hook ` is an optionnal callable dict - > str to map record to string . Default to _ record _ to _ string""" | Ac = self . ACCES
if pattern == "*" :
return groups . Collection ( Ac ( base , i ) for i in self )
if len ( pattern ) >= MIN_CHAR_SEARCH : # Needed chars .
sub_patterns = pattern . split ( " " )
try :
regexps = tuple ( re . compile ( sub_pattern , flags = re . I ) for sub_pattern in sub_patterns )
... |
def verify ( self ) :
"""Verifies expectations on all doubled objects .
: raise : ` ` MockExpectationError ` ` on the first expectation that is not satisfied , if any .""" | if self . _is_verified :
return
for proxy in self . _proxies . values ( ) :
proxy . verify ( )
self . _is_verified = True |
def _pooling_general ( inputs , reducer , init_val , rescaler = None , pool_size = ( 2 , 2 ) , strides = None , padding = 'VALID' ) :
"""Helper : general pooling computation used in pooling layers later .""" | spatial_strides = strides or ( 1 , ) * len ( pool_size )
rescale = rescaler ( pool_size , spatial_strides , padding ) if rescaler else None
dims = ( 1 , ) + pool_size + ( 1 , )
# NHWC
strides = ( 1 , ) + spatial_strides + ( 1 , )
out = lax . reduce_window ( inputs , init_val , reducer , dims , strides , padding )
retur... |
def stop_subscribe ( self ) :
"""This function is used to stop the event loop created when subscribe is called . But this function doesn ' t
stop the thread and should be avoided until its completely developed .""" | asyncio . gather ( * asyncio . Task . all_tasks ( ) ) . cancel ( )
self . event_loop . stop ( )
self . event_loop . close ( ) |
def create_account ( self , account_type , currency ) :
"""Create an account
https : / / docs . kucoin . com / # create - an - account
: param account _ type : Account type - main or trade
: type account _ type : string
: param currency : Currency code
: type currency : string
. . code : : python
acco... | data = { 'type' : account_type , 'currency' : currency }
return self . _post ( 'accounts' , True , data = data ) |
def summarize_variables ( variables = None ) :
"""Logs a summary of variable information .
This function groups Variables by dtype and prints out the number of Variables
and the total number of scalar values for each datatype , as well as the total
memory consumed .
For Variables of type tf . string , the m... | variable_counts = count_variables_by_type ( variables = variables )
total_num_scalars = 0
total_num_bytes = 0
# Sort by string representation of type name , so output is deterministic .
for dtype in sorted ( variable_counts , key = lambda dtype : "%r" % dtype ) :
var_info_for_type = variable_counts [ dtype ]
nu... |
def _set_openflowPo ( self , v , load = False ) :
"""Setter method for openflowPo , mapped from YANG variable / interface / port _ channel / openflowPo ( container )
If this variable is read - only ( config : false ) in the
source YANG file , then _ set _ openflowPo is considered as a private
method . Backend... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = openflowPo . openflowPo , is_container = 'container' , presence = False , yang_name = "openflowPo" , rest_name = "openflow" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_path... |
def coerce ( self , value , resource ) :
"""Get a dict with attributes from ` ` value ` ` .
Arguments
value : ?
The value to get some resources from .
resource : dataql . resources . Object
The ` ` Object ` ` object used to obtain this value from the original one .
Returns
dict
A dictionary containi... | return { r . name : self . registry . solve_resource ( value , r ) for r in resource . resources } |
def createKmerProfile ( self , k , profileCsvFN ) :
'''TODO : this method is olddddd , needs to be ported into BasicBWT AND reworked to do this better
@ param k - the length of the k - mers to profile
@ param profileCsvFN - the filename of the csv to create''' | searches = [ ( '' , 0 , self . bwt . shape [ 0 ] ) ]
normTotal = 0
lines = [ ]
while len ( searches ) > 0 :
( seq , start , end ) = searches . pop ( 0 )
if len ( seq ) == k :
lines . append ( seq + ',' + str ( end - start ) )
normTotal += ( end - start ) ** 2
else :
nls = self . getF... |
def pretrain ( self , train_set , validation_set = None ) :
"""Perform Unsupervised pretraining of the DBN .""" | self . do_pretrain = True
def set_params_func ( rbmmachine , rbmgraph ) :
params = rbmmachine . get_parameters ( graph = rbmgraph )
self . encoding_w_ . append ( params [ 'W' ] )
self . encoding_b_ . append ( params [ 'bh_' ] )
return SupervisedModel . pretrain_procedure ( self , self . rbms , self . rbm_gr... |
def get_instructions ( self , cm , size , insn , idx ) :
""": param cm : a ClassManager object
: type cm : : class : ` ClassManager ` object
: param size : the total size of the buffer
: type size : int
: param insn : a raw buffer where are the instructions
: type insn : string
: param idx : a start add... | self . odex = cm . get_odex_format ( )
max_idx = size * calcsize ( '=H' )
if max_idx > len ( insn ) :
max_idx = len ( insn )
# Get instructions
while idx < max_idx :
obj = None
classic_instruction = True
op_value = insn [ idx ]
# print " % x % x " % ( op _ value , idx )
# payload instructions or... |
def system_find_analyses ( input_params = { } , always_retry = True , ** kwargs ) :
"""Invokes the / system / findAnalyses API method .
For more info , see : https : / / wiki . dnanexus . com / API - Specification - v1.0.0 / Search # API - method % 3A - % 2Fsystem % 2FfindAnalyses""" | return DXHTTPRequest ( '/system/findAnalyses' , input_params , always_retry = always_retry , ** kwargs ) |
def loads ( s , encoding = None , cls = None , object_hook = None , ** kw ) :
"""Deserialize ` ` s ` ` ( a ` ` str ` ` or ` ` unicode ` ` instance containing a JSON
document ) to a Python object .
If ` ` s ` ` is a ` ` str ` ` instance and is encoded with an ASCII based encoding
other than utf - 8 ( e . g . l... | if cls is None :
cls = JSONDecoder
if object_hook is not None :
kw [ 'object_hook' ] = object_hook
return cls ( encoding = encoding , ** kw ) . decode ( s ) |
def initialize ( self , conf , ctx ) :
"""Initialization steps :
1 . Get : func : ` ~ birding . search . search _ manager _ from _ config ` .
2 . Prepare to track searched terms as to avoid redundant searches .""" | self . manager = get_search_manager ( )
config = get_config ( ) [ 'TwitterSearchBolt' ]
self . term_shelf = shelf_from_config ( config ) |
def delete ( self , using = None ) :
"""If the organization user is also the owner , this should not be deleted
unless it ' s part of a cascade from the Organization .
If there is no owner then the deletion should proceed .""" | from organizations . exceptions import OwnershipRequired
try :
if self . organization . owner . organization_user . pk == self . pk :
raise OwnershipRequired ( _ ( "Cannot delete organization owner " "before organization or transferring ownership." ) )
# TODO This line presumes that OrgOwner model can ' t b... |
def gen_add ( src1 , src2 , dst ) :
"""Return an ADD instruction .""" | assert src1 . size == src2 . size
return ReilBuilder . build ( ReilMnemonic . ADD , src1 , src2 , dst ) |
def GetFormatStringAttributeNames ( self ) :
"""Retrieves the attribute names in the format string .
Returns :
set ( str ) : attribute names .""" | if self . _format_string_attribute_names is None :
self . _format_string_attribute_names = ( self . _FORMAT_STRING_ATTRIBUTE_NAME_RE . findall ( self . FORMAT_STRING ) )
return set ( self . _format_string_attribute_names ) |
def transform_folder ( args ) :
"""Transform all the files in the source dataset for the given command and save
the results as a single pickle file in the destination dataset
: param args : tuple with the following arguments :
- the command name : ' zero ' , ' one ' , ' two ' , . . .
- transforms to apply t... | command , ( transform , src , dest ) = args
try :
print ( progress . value , "remaining" )
# Apply transformations to all files
data = [ ]
data_dir = os . path . join ( src , command )
for filename in os . listdir ( data_dir ) :
path = os . path . join ( data_dir , filename )
data . ... |
def _get_elmt_amt_in_rxt ( self , rxt ) :
"""Computes total number of atoms in a reaction formula for elements
not in external reservoir . This method is used in the calculation
of reaction energy per mol of reaction formula .
Args :
rxt ( Reaction ) : a reaction .
Returns :
Total number of atoms for no... | return sum ( [ rxt . get_el_amount ( e ) for e in self . pd . elements ] ) |
def _save ( self , acl , predefined , client ) :
"""Helper for : meth : ` save ` and : meth : ` save _ predefined ` .
: type acl : : class : ` google . cloud . storage . acl . ACL ` , or a compatible list .
: param acl : The ACL object to save . If left blank , this will save
current entries .
: type predef... | query_params = { "projection" : "full" }
if predefined is not None :
acl = [ ]
query_params [ self . _PREDEFINED_QUERY_PARAM ] = predefined
if self . user_project is not None :
query_params [ "userProject" ] = self . user_project
path = self . save_path
client = self . _require_client ( client )
result = cl... |
def put ( files , remote_path = None , recursive = False , preserve_times = False , saltenv = 'base' , ** kwargs ) :
'''Transfer files and directories to remote host .
files
A single path or a list of paths to be transferred .
remote _ path
The path on the remote device where to store the files .
recursiv... | scp_client = _prepare_connection ( ** kwargs )
put_kwargs = { 'recursive' : recursive , 'preserve_times' : preserve_times }
if remote_path :
put_kwargs [ 'remote_path' ] = remote_path
cached_files = [ ]
if not isinstance ( files , ( list , tuple ) ) :
files = [ files ]
for file_ in files :
cached_file = __s... |
def update_health_check ( HealthCheckId = None , HealthCheckVersion = None , IPAddress = None , Port = None , ResourcePath = None , FullyQualifiedDomainName = None , SearchString = None , FailureThreshold = None , Inverted = None , HealthThreshold = None , ChildHealthChecks = None , EnableSNI = None , Regions = None , ... | pass |
def set_rule ( self , name , properties ) :
"""Set a rules as object attribute .
Arguments :
name ( string ) : Rule name to set as attribute name .
properties ( dict ) : Dictionnary of properties .""" | self . _rule_attrs . append ( name )
setattr ( self , name , properties ) |
def pause_point ( self , msg = 'SHUTIT PAUSE POINT' , shutit_pexpect_child = None , print_input = True , level = 1 , resize = True , color = '32' , default_msg = None , interact = False , wait = - 1 ) :
"""Inserts a pause in the build session , which allows the user to try
things out before continuing . Ignored i... | shutit_global . shutit_global_object . yield_to_draw ( )
if ( not shutit_global . shutit_global_object . determine_interactive ( ) or shutit_global . shutit_global_object . interactive < 1 or shutit_global . shutit_global_object . interactive < level ) :
return True
shutit_pexpect_child = shutit_pexpect_child or se... |
def dedent ( lines ) :
"""De - indent based on the first line ' s indentation .""" | if len ( lines ) != 0 :
first_lstrip = lines [ 0 ] . lstrip ( )
strip_len = len ( lines [ 0 ] ) - len ( first_lstrip )
for line in lines :
if len ( line [ : strip_len ] . strip ( ) ) != 0 :
raise ValueError ( 'less indentation than first line: ' + line )
else :
yield ... |
def format_table ( rows , sep = ' ' ) :
"""Format table
: param sep : separator between columns
: type sep : unicode on python2 | str on python3
Given the table : :
table = [
[ ' foo ' , ' bar ' , ' foo ' ] ,
[1 , 2 , 3 ] ,
[ ' 54a5a05d - c83b - 4bb5 - bd95 - d90d6ea4a878 ' ] ,
[ ' foo ' , 45 , ' b... | max_col_length = [ 0 ] * 100
# calculate max length for each col
for row in rows :
for index , ( col , length ) in enumerate ( zip ( row , max_col_length ) ) :
if len ( text_type ( col ) ) > length :
max_col_length [ index ] = len ( text_type ( col ) )
formated_rows = [ ]
for row in rows :
f... |
def one_to_many ( df , unitcol , manycol ) :
"""Assert that a many - to - one relationship is preserved between two
columns . For example , a retail store will have have distinct
departments , each with several employees . If each employee may
only work in a single department , then the relationship of the
... | subset = df [ [ manycol , unitcol ] ] . drop_duplicates ( )
for many in subset [ manycol ] . unique ( ) :
if subset [ subset [ manycol ] == many ] . shape [ 0 ] > 1 :
msg = "{} in {} has multiple values for {}" . format ( many , manycol , unitcol )
raise AssertionError ( msg )
return df |
def propagate_type_and_convert_call ( result , node ) :
'''Propagate the types variables and convert tmp call to real call operation''' | calls_value = { }
calls_gas = { }
call_data = [ ]
idx = 0
# use of while len ( ) as result can be modified during the iteration
while idx < len ( result ) :
ins = result [ idx ]
if isinstance ( ins , TmpCall ) :
new_ins = extract_tmp_call ( ins , node . function . contract )
if new_ins :
... |
def set ( self ) -> None :
"""Set the internal flag to ` ` True ` ` . All waiters are awakened .
Calling ` . wait ` once the flag is set will not block .""" | if not self . _value :
self . _value = True
for fut in self . _waiters :
if not fut . done ( ) :
fut . set_result ( None ) |
def system_qos_qos_service_policy_attach_rbridge_id_remove_rb_remove_range ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
system_qos = ET . SubElement ( config , "system-qos" , xmlns = "urn:brocade.com:mgmt:brocade-policer" )
qos = ET . SubElement ( system_qos , "qos" )
service_policy = ET . SubElement ( qos , "service-policy" )
direction_key = ET . SubElement ( service_policy , "direction" )
direction_k... |
def filter_desc ( self , graintype = None , group = None , reference = None , size = None , phase = None ) :
'''This routine is to filter for description elements . You can
check what is available in the description by running ,
> > > i . header _ desc ( )
where i is the instance you loaded .
You can run th... | # filter for graintype
if graintype != None :
indexing = [ ]
# index file on which lines to pick
if type ( graintype ) == str :
graintype = [ graintype ]
# filter
for typ in graintype :
for i in range ( len ( self . desc ) ) :
if self . desc [ i ] [ self . descdict [ 'Typ... |
def tag ( self , resource_id ) :
"""Update the request URI to include the Tag for specific retrieval .
Args :
resource _ id ( string ) : The tag name .""" | self . _request_uri = '{}/{}' . format ( self . _request_uri , self . tcex . safetag ( resource_id ) ) |
def uncluster_annotations ( self , input_annotations , reverse_pipe ) :
'''Update the annotations hash provided by pplacer to include all
representatives within each cluster
Parameters
input _ annotations : hash
Classifications for each representative sequence of the clusters .
each key being the sequence... | output_annotations = { }
for placed_alignment_file_path , clusters in self . seq_library . iteritems ( ) :
if reverse_pipe and placed_alignment_file_path . endswith ( "_reverse_clustered.fa" ) :
continue
placed_alignment_file = os . path . basename ( placed_alignment_file_path )
cluster_classificati... |
def find ( self , tagtype , ** kwargs ) :
'''Get the first tag with a type in this token''' | for t in self . __tags :
if t . tagtype == tagtype :
return t
if 'default' in kwargs :
return kwargs [ 'default' ]
else :
raise LookupError ( "Token {} is not tagged with the speficied tagtype ({})" . format ( self , tagtype ) ) |
def lognormal ( mu , sigma , random_state ) :
'''mu : float or array _ like of floats
sigma : float or array _ like of floats
random _ state : an object of numpy . random . RandomState''' | return np . exp ( normal ( mu , sigma , random_state ) ) |
def subset ( self , sel0 = None , sel1 = None ) :
"""Make a sub - selection of variants and haplotypes .
Parameters
sel0 : array _ like
Boolean array or array of indices selecting variants .
sel1 : array _ like
Boolean array or array of indices selecting haplotypes .
Returns
out : HaplotypeArray
See... | return subset_haplotype_array ( self , sel0 , sel1 , cls = type ( self ) , subset = subset ) |
def delta ( d1 , d2 , opt = 'd' ) :
"""Compute difference between given 2 dates in month / day .""" | delta = 0
if opt == 'm' :
while True :
mdays = monthrange ( d1 . year , d1 . month ) [ 1 ]
d1 += timedelta ( days = mdays )
if d1 <= d2 :
delta += 1
else :
break
else :
delta = ( d2 - d1 ) . days
return delta |
def setup_scrapy ( ) :
"""This is not needed as we pass ' LOG _ ENABLED ' : False to scrapy at init time""" | def replace_configure_logging ( install_root_handler = False , settings = None ) :
fake_use ( install_root_handler )
fake_use ( settings )
def replace_log_scrapy_info ( settings = None ) :
fake_use ( settings )
# scrapy stuff
import scrapy . utils . log
# for configure _ logging
import scrapy . crawler
# co... |
def set_xlimits_for_all ( self , row_column_list = None , min = None , max = None ) :
"""Set x - axis limits of specified subplots .
: param row _ column _ list : a list containing ( row , column ) tuples to
specify the subplots , or None to indicate * all * subplots .
: type row _ column _ list : list or Non... | if row_column_list is None :
self . limits [ 'xmin' ] = min
self . limits [ 'xmax' ] = max
else :
for row , column in row_column_list :
self . set_xlimits ( row , column , min , max ) |
def read_messages ( self ) -> str :
"""returns a string of new device messages separated by newlines
: return :""" | if self . backend == Backends . grc :
errors = self . __dev . read_errors ( )
if "FATAL: " in errors :
self . fatal_error_occurred . emit ( errors [ errors . index ( "FATAL: " ) : ] )
return errors
elif self . backend == Backends . native :
messages = "\n" . join ( self . __dev . device_messages... |
def delete ( self ) :
"""Delete a record from the database .""" | if self . _on_delete is not None :
return self . _on_delete ( self )
return self . _query . delete ( ) |
def suspend ( self ) :
"""Suspends this VirtualBox VM .""" | vm_state = yield from self . _get_vm_state ( )
if vm_state == "running" :
yield from self . _control_vm ( "pause" )
self . status = "suspended"
log . info ( "VirtualBox VM '{name}' [{id}] suspended" . format ( name = self . name , id = self . id ) )
else :
log . warn ( "VirtualBox VM '{name}' [{id}] can... |
def _from_dict ( cls , _dict ) :
"""Initialize a DialogNode object from a json dictionary .""" | args = { }
if 'dialog_node' in _dict :
args [ 'dialog_node' ] = _dict . get ( 'dialog_node' )
else :
raise ValueError ( 'Required property \'dialog_node\' not present in DialogNode JSON' )
if 'description' in _dict :
args [ 'description' ] = _dict . get ( 'description' )
if 'conditions' in _dict :
args ... |
def getCanonicalID ( iname , xrd_tree ) :
"""Return the CanonicalID from this XRDS document .
@ param iname : the XRI being resolved .
@ type iname : unicode
@ param xrd _ tree : The XRDS output from the resolver .
@ type xrd _ tree : ElementTree
@ returns : The XRI CanonicalID or None .
@ returntype : ... | xrd_list = xrd_tree . findall ( xrd_tag )
xrd_list . reverse ( )
try :
canonicalID = xri . XRI ( xrd_list [ 0 ] . findall ( canonicalID_tag ) [ 0 ] . text )
except IndexError :
return None
childID = canonicalID . lower ( )
for xrd in xrd_list [ 1 : ] : # XXX : can ' t use rsplit until we require python > = 2.4.... |
def _onShortcutSelectAndScroll ( self , down ) :
"""Ctrl + Shift + Up / Down pressed .
Select line and scroll viewport""" | cursor = self . textCursor ( )
cursor . movePosition ( QTextCursor . Down if down else QTextCursor . Up , QTextCursor . KeepAnchor )
self . setTextCursor ( cursor )
self . _onShortcutScroll ( down ) |
def addvFunc ( self , solution , EndOfPrdvP ) :
'''Creates the value function for this period and adds it to the solution .
Parameters
solution : ConsumerSolution
The solution to this single period problem , likely including the
consumption function , marginal value function , etc .
EndOfPrdvP : np . arra... | self . makeEndOfPrdvFunc ( EndOfPrdvP )
solution . vFunc = self . makevFunc ( solution )
return solution |
def _collapse_table_root ( current , dsn , pc ) :
"""Create a table with items in root given the current time series entry
: param dict current : Current time series entry
: param str dsn : Dataset name
: param str pc : paleoData or chronData
: return dict _ tmp _ table : Table data""" | logger_ts . info ( "enter collapse_table_root" )
_table_name , _variable_name = _get_current_names ( current , dsn , pc )
_tmp_table = { 'columns' : { } }
try :
for k , v in current . items ( ) : # These are the main table keys that we should be looking for
for i in [ 'filename' , 'googleWorkSheetKey' , 'ta... |
def get_uncompleted_tasks ( self ) :
"""Return all of a user ' s uncompleted tasks .
. . warning : : Requires Todoist premium .
: return : A list of uncompleted tasks .
: rtype : list of : class : ` pytodoist . todoist . Task `
> > > from pytodoist import todoist
> > > user = todoist . login ( ' john . do... | tasks = ( p . get_uncompleted_tasks ( ) for p in self . get_projects ( ) )
return list ( itertools . chain . from_iterable ( tasks ) ) |
def _highlightBracket ( self , bracket , qpart , block , columnIndex ) :
"""Highlight bracket and matching bracket
Return tuple of QTextEdit . ExtraSelection ' s""" | try :
matchedBlock , matchedColumnIndex = self . _findMatchingBracket ( bracket , qpart , block , columnIndex )
except _TimeoutException : # not found , time is over
return [ ]
# highlight nothing
if matchedBlock is not None :
self . currentMatchedBrackets = ( ( block , columnIndex ) , ( matchedBlock , matc... |
def grading_means_passed ( self ) :
'''Information if the given grading means passed .
Non - graded assignments are always passed .''' | if self . assignment . is_graded ( ) :
if self . grading and self . grading . means_passed :
return True
else :
return False
else :
return True |
def cleanup ( ) :
"""Clean up the installation directory .""" | lib_dir = os . path . join ( os . environ [ 'CONTAINER_DIR' ] , '_lib' )
if os . path . exists ( lib_dir ) :
shutil . rmtree ( lib_dir )
os . mkdir ( lib_dir ) |
def classical_strength_of_connection ( A , theta = 0.0 , norm = 'abs' ) :
"""Classical Strength Measure .
Return a strength of connection matrix using the classical AMG measure
An off - diagonal entry A [ i , j ] is a strong connection iff : :
A [ i , j ] > = theta * max ( | A [ i , k ] | ) , where k ! = i ( ... | if sparse . isspmatrix_bsr ( A ) :
blocksize = A . blocksize [ 0 ]
else :
blocksize = 1
if not sparse . isspmatrix_csr ( A ) :
warn ( "Implicit conversion of A to csr" , sparse . SparseEfficiencyWarning )
A = sparse . csr_matrix ( A )
if ( theta < 0 or theta > 1 ) :
raise ValueError ( 'expected thet... |
def send_unsent ( self ) :
"""Emails that were not being able to send will be stored in : attr : ` self . unsent ` .
Use this function to attempt to send these again""" | for i in range ( len ( self . unsent ) ) :
recipients , msg_string = self . unsent . pop ( i )
self . _attempt_send ( recipients , msg_string ) |
def _send_batch ( self , batch ) :
"""Sends a batch to the destination server via HTTP REST API""" | try :
json_batch = '[' + ',' . join ( batch ) + ']'
# Make JSON array string
logger . debug ( consts . LOG_MSG_SENDING_BATCH , len ( batch ) , len ( json_batch ) , self . _rest_url )
res = self . _session . post ( self . _rest_url , data = json_batch , headers = consts . CONTENT_TYPE_JSON )
logger .... |
def lambdafan ( func ) :
"""simple decorator that will auto fan out async style in lambda .
outside of lambda , this will invoke synchrously .""" | if 'AWS_LAMBDA_FUNCTION_NAME' not in os . environ :
return func
@ functools . wraps ( func )
def scaleout ( * args , ** kw ) :
client = boto3 . client ( 'lambda' )
client . invoke ( FunctionName = os . environ [ 'AWS_LAMBDA_FUNCTION_NAME' ] , InvocationType = 'Event' , Payload = dumps ( { 'event' : 'fanout'... |
def _jtime ( self , timestamp ) :
"""Convert datetime or unix _ timestamp into Time""" | if isinstance ( timestamp , datetime ) :
timestamp = time . mktime ( timestamp . timetuple ( ) )
return self . _sc . _jvm . Time ( long ( timestamp * 1000 ) ) |
def calc_thresholds ( rbh , file_name , thresholds = [ False , False , False , False ] , stdevs = 2 ) :
"""if thresholds are not specififed , calculate based on the distribution of normalized bit scores""" | calc_threshold = thresholds [ - 1 ]
norm_threshold = { }
for pair in itertools . permutations ( [ i for i in rbh ] , 2 ) :
if pair [ 0 ] not in norm_threshold :
norm_threshold [ pair [ 0 ] ] = { }
norm_threshold [ pair [ 0 ] ] [ pair [ 1 ] ] = { }
out = open ( file_name , 'w' )
print ( '#### summary of ... |
def _partition ( iter_dims , data_sources ) :
"""Partition data sources into
1 . Dictionary of data sources associated with radio sources .
2 . List of data sources to feed multiple times .
3 . List of data sources to feed once .""" | src_nr_vars = set ( source_var_types ( ) . values ( ) )
iter_dims = set ( iter_dims )
src_data_sources = collections . defaultdict ( list )
feed_many = [ ]
feed_once = [ ]
for ds in data_sources : # Is this data source associated with
# a radio source ( point , gaussian , etc . ? )
src_int = src_nr_vars . intersect... |
def sfo ( x0 , rho , optimizer , num_steps = 50 ) :
"""Proximal operator for an arbitrary function minimized via the Sum - of - Functions optimizer ( SFO )
Notes
SFO is a function optimizer for the
case where the target function breaks into a sum over minibatches , or a sum
over contributing functions . It ... | # set the current parameter value of SFO to the given value
optimizer . set_theta ( x0 , float ( rho ) )
# set the previous ADMM location as the flattened paramter array
optimizer . theta_admm_prev = optimizer . theta_original_to_flat ( x0 )
# run the optimizer for n steps
return optimizer . optimize ( num_steps = num_... |
def parse_reference ( reference ) :
"""parse provided image reference into < image _ repository > : < tag >
: param reference : str , e . g . ( registry . fedoraproject . org / fedora : 27)
: return : collection ( tuple or list ) , ( " registry . fedoraproject . org / fedora " , " 27 " )""" | if ":" in reference :
im , tag = reference . rsplit ( ":" , 1 )
if "/" in tag : # this is case when there is port in the registry URI
return ( reference , "latest" )
else :
return ( im , tag )
else :
return ( reference , "latest" ) |
def reference_pix_from_wcs ( frames , pixref , origin = 1 ) :
"""Compute reference pixels between frames using WCS information .
The sky world coordinates are computed on * pixref * using
the WCS of the first frame in the sequence . Then , the
pixel coordinates of the reference sky world - coordinates
are c... | result = [ ]
with frames [ 0 ] . open ( ) as hdulist :
wcsh = wcs . WCS ( hdulist [ 0 ] . header )
skyref = wcsh . wcs_pix2world ( [ pixref ] , origin )
result . append ( pixref )
for idx , frame in enumerate ( frames [ 1 : ] ) :
with frame . open ( ) as hdulist :
wcsh = wcs . WCS ( hdulist [ 0 ... |
def _apply_krauss ( krauss : Union [ Tuple [ np . ndarray ] , Sequence [ Any ] ] , args : 'ApplyChannelArgs' ) -> np . ndarray :
"""Directly apply the kraus operators to the target tensor .""" | # Initialize output .
args . out_buffer [ : ] = 0
# Stash initial state into buffer0.
np . copyto ( dst = args . auxiliary_buffer0 , src = args . target_tensor )
# Special case for single - qubit operations .
if krauss [ 0 ] . shape == ( 2 , 2 ) :
return _apply_krauss_single_qubit ( krauss , args )
# Fallback to np... |
async def create_account ( self , ** params ) :
"""Describes , validates data .""" | logging . debug ( "\n\n[+] -- Create account debugging. " )
model = { "unique" : [ "email" , "public_key" ] , "required" : ( "public_key" , ) , "default" : { "count" : len ( settings . AVAILABLE_COIN_ID ) , "level" : 2 , "news_count" : 0 , "email" : None } , "optional" : ( "phone" , ) }
message = json . loads ( params ... |
def request_json ( self , url , params = None , data = None , as_objects = True , retry_on_error = True , method = None ) :
"""Get the JSON processed from a page .
: param url : the url to grab content from .
: param params : a dictionary containing the GET data to put in the url
: param data : a dictionary c... | if not url . endswith ( '.json' ) :
url += '.json'
response = self . _request ( url , params , data , method = method , retry_on_error = retry_on_error )
hook = self . _json_reddit_objecter if as_objects else None
# Request url just needs to be available for the objecter to use
self . _request_url = url
# pylint : ... |
def do_kick ( self , sender , body , args ) :
"""Kick a member from the chatroom . Must be Admin to kick users""" | if sender . get ( 'ADMIN' ) != True :
return
for user in args :
self . kick_user ( user ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.