signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def get_handler ( progname , fmt = None , datefmt = None , project_id = None , credentials = None , debug_thread_worker = False , ** _ ) :
"""Helper function to create a Stackdriver handler .
See ` ulogger . stackdriver . CloudLoggingHandlerBuilder ` for arguments
and supported keyword arguments .
Returns :
... | builder = CloudLoggingHandlerBuilder ( progname , fmt = fmt , datefmt = datefmt , project_id = project_id , credentials = credentials , debug_thread_worker = debug_thread_worker )
return builder . get_handler ( ) |
def data_file ( self ) :
"""Gets the full path to the file in which to save / load configured data .""" | path = os . getcwd ( ) + '/' + self . lazy_folder
return path + self . data_filename |
def tacacs_server_host_protocol ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
tacacs_server = ET . SubElement ( config , "tacacs-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
host = ET . SubElement ( tacacs_server , "host" )
hostname_key = ET . SubElement ( host , "hostname" )
hostname_key . text = kwargs . pop ( 'hostname' )
use_vrf_key = ET . SubElem... |
def estimateExportTilesSize ( self , exportBy , levels , tilePackage = False , exportExtent = "DEFAULTEXTENT" , areaOfInterest = None , async = True ) :
"""The estimateExportTilesSize operation is an asynchronous task that
allows estimation of the size of the tile package or the cache data
set that you download... | url = self . _url + "/estimateExportTilesSize"
params = { "f" : "json" , "levels" : levels , "exportBy" : exportBy , "tilePackage" : tilePackage , "exportExtent" : exportExtent }
params [ "levels" ] = levels
if not areaOfInterest is None :
if isinstance ( areaOfInterest , Polygon ) :
template = { "features"... |
def get_user ( self , uid , disabled = False ) :
'''given a uid , returns
first _ name ( string ) : User ' s first name ,
image1 ( string ) : User ' s profile image ,
email ( string ) : User ' s email address ,
create _ date ( string ) : The creation date ,
last _ name ( string ) : User ' s last name ,
... | path = "/api/v3/publisher/user/get"
data = { 'api_token' : self . api_token , 'aid' : self . app_id , 'uid' : uid , 'disabled' : disabled , }
r = requests . get ( self . base_url + path , data = data )
if r . status_code == 2 :
raise ValueError ( path + ":" + r . reason )
# An Auth issue
if r . status_code == 2004 ... |
def get_dummy_request ( language = None ) :
"""Returns a Request instance populated with cms specific attributes .""" | if settings . ALLOWED_HOSTS and settings . ALLOWED_HOSTS != "*" :
host = settings . ALLOWED_HOSTS [ 0 ]
else :
host = Site . objects . get_current ( ) . domain
request = RequestFactory ( ) . get ( "/" , HTTP_HOST = host )
request . session = { }
request . LANGUAGE_CODE = language or settings . LANGUAGE_CODE
# N... |
def channels_remove_owner ( self , room_id , user_id , ** kwargs ) :
"""Removes the role of owner from a user in the current channel .""" | return self . __call_api_post ( 'channels.removeOwner' , roomId = room_id , userId = user_id , kwargs = kwargs ) |
def hmget ( self , key , field , * fields , encoding = _NOTSET ) :
"""Get the values of all the given fields .""" | return self . execute ( b'HMGET' , key , field , * fields , encoding = encoding ) |
def title ( self , value ) :
"""Setter for * * self . _ _ title * * attribute .
: param value : Attribute value .
: type value : unicode""" | if value is not None :
assert type ( value ) is unicode , "'{0}' attribute: '{1}' type is not 'unicode'!" . format ( "title" , value )
self . __title = value |
def trial_end ( self , trial_job_id , success ) :
"""trial _ end
Parameters
trial _ job _ id : int
trial job id
success : bool
True if succssfully finish the experiment , False otherwise""" | if trial_job_id in self . running_history :
if success :
cnt = 0
history_sum = 0
self . completed_avg_history [ trial_job_id ] = [ ]
for each in self . running_history [ trial_job_id ] :
cnt += 1
history_sum += each
self . completed_avg_history [ t... |
def get_jid ( jid ) :
'''Return the information returned when the specified job id was executed''' | jid_dir = salt . utils . jid . jid_dir ( jid , _job_dir ( ) , __opts__ [ 'hash_type' ] )
serial = salt . payload . Serial ( __opts__ )
ret = { }
# Check to see if the jid is real , if not return the empty dict
if not os . path . isdir ( jid_dir ) :
return ret
for fn_ in os . listdir ( jid_dir ) :
if fn_ . start... |
def SysRem ( time , flux , err , ncbv = 5 , niter = 50 , sv_win = 999 , sv_order = 3 , ** kwargs ) :
'''Applies : py : obj : ` SysRem ` to a given set of light curves .
: param array _ like time : The time array for all of the light curves
: param array _ like flux : A 2D array of the fluxes for each of the lig... | nflx , tlen = flux . shape
# Get normalized fluxes
med = np . nanmedian ( flux , axis = 1 ) . reshape ( - 1 , 1 )
y = flux - med
# Compute the inverse of the variances
invvar = 1. / err ** 2
# The CBVs for this set of fluxes
cbvs = np . zeros ( ( ncbv , tlen ) )
# Recover ` ncbv ` components
for n in range ( ncbv ) : #... |
def _get_or_convert_magnitude ( self , mag_letter ) :
"""Takes input of the magnitude letter and ouputs the magnitude fetched from the catalogue or a converted value
: return :""" | allowed_mags = "UBVJIHKLMN"
catalogue_mags = 'BVIJHK'
if mag_letter not in allowed_mags or not len ( mag_letter ) == 1 :
raise ValueError ( "Magnitude letter must be a single letter in {0}" . format ( allowed_mags ) )
mag_str = 'mag' + mag_letter
mag_val = self . getParam ( mag_str )
if isNanOrNone ( mag_val ) and ... |
def calculate_slope ( x_coord1 , y_coord1 , x_coord2 , y_coord2 ) :
"""This Python function calculates the slope of a line defined by two points .
Examples :
> > > calculate _ slope ( 4 , 2 , 2 , 5)
-1.5
> > > calculate _ slope ( 2 , 4 , 4 , 6)
> > > calculate _ slope ( 1 , 2 , 4 , 2)
Args :
x _ coord... | return ( float ( ( y_coord2 - y_coord1 ) ) / ( x_coord2 - x_coord1 ) ) |
def parse_coverage_args ( argv ) :
"""Parse command line arguments , returning a dict of
valid options :
' coverage _ xml ' : COVERAGE _ XML ,
' html _ report ' : None | HTML _ REPORT ,
' external _ css _ file ' : None | CSS _ FILE ,
where ` COVERAGE _ XML ` , ` HTML _ REPORT ` , and ` CSS _ FILE ` are pa... | parser = argparse . ArgumentParser ( description = DESCRIPTION )
parser . add_argument ( 'coverage_xml' , type = str , help = COVERAGE_XML_HELP , nargs = '+' )
parser . add_argument ( '--html-report' , metavar = 'FILENAME' , type = str , default = None , help = HTML_REPORT_HELP )
parser . add_argument ( '--external-css... |
def traceback ( frame , parent = False ) :
"""Pick frame info from current caller ' s ` frame ` .
Args :
* frame : : type : ` frame ` instance , use : func : ` inspect . currentframe ` .
* parent : whether to get outer frame ( caller ) traceback info , : data : ` False ` by default .
Returns :
: class : `... | # Traceback ( filename = ' < stdin > ' , lineno = 1 , function = ' < module > ' , code _ context = None , index = None )
if parent is True : # frame itself will always be placed @ the first index of its outerframes .
outers = inspect . getouterframes ( frame )
traceback = ( len ( outers ) == 1 ) and None or ins... |
def parse_parts ( self , file , boundary , content_length ) :
"""Generate ` ` ( ' file ' , ( name , val ) ) ` ` and
` ` ( ' form ' , ( name , val ) ) ` ` parts .""" | in_memory = 0
for ellt , ell in self . parse_lines ( file , boundary , content_length ) :
if ellt == _begin_file :
headers , name , filename = ell
is_file = True
guard_memory = False
filename , container = self . start_file_streaming ( filename , headers , content_length )
_w... |
def get_dynamodb_type ( self , val ) :
"""Take a scalar Python value and return a string representing
the corresponding Amazon DynamoDB type . If the value passed in is
not a supported type , raise a TypeError .""" | dynamodb_type = None
if is_num ( val ) :
dynamodb_type = 'N'
elif is_str ( val ) :
dynamodb_type = 'S'
elif isinstance ( val , ( set , frozenset ) ) :
if False not in map ( is_num , val ) :
dynamodb_type = 'NS'
elif False not in map ( is_str , val ) :
dynamodb_type = 'SS'
if dynamodb_typ... |
def list_traces ( self , project_id = None , view = None , page_size = None , start_time = None , end_time = None , filter_ = None , order_by = None , page_token = None , ) :
"""Returns of a list of traces that match the filter conditions .
Args :
project _ id ( Optional [ str ] ) : ID of the Cloud project wher... | if project_id is None :
project_id = self . project
if start_time is not None :
start_time = _datetime_to_pb_timestamp ( start_time )
if end_time is not None :
end_time = _datetime_to_pb_timestamp ( end_time )
return self . trace_api . list_traces ( project_id = project_id , view = view , page_size = page_s... |
def extractRuntime ( runtime_dirs ) :
"""Used to find the correct static lib name to pass to gcc""" | names = [ str ( item ) for name in runtime_dirs for item in os . listdir ( name ) ]
string = '\n' . join ( names )
result = extract ( RUNTIME_PATTERN , string , condense = True )
return result |
def generate_key ( self ) :
"""Ask mist . io to randomly generate a private ssh - key to be
used with the creation of a new Key
: returns : A string of a randomly generated ssh private key""" | req = self . request ( self . uri + "/keys" )
private_key = req . post ( ) . json ( )
return private_key [ 'priv' ] |
def get ( self ) :
"""Returns the spanning - tree configuration as a dict object
The dictionary object represents the entire spanning - tree
configuration derived from the nodes running config . This
includes both globally configuration attributes as well as
interfaces and instances . See the StpInterfaces ... | return dict ( interfaces = self . interfaces . getall ( ) , instances = self . instances . getall ( ) ) |
def get_template_substitution_values ( self , value ) :
"""Return value - related substitutions .""" | return { 'initial' : os . path . basename ( conditional_escape ( value ) ) , 'initial_url' : conditional_escape ( value . url ) , } |
def requires_private_key ( func ) :
"""Decorator for functions that require the private key to be defined .""" | def func_wrapper ( self , * args , ** kwargs ) :
if hasattr ( self , "_DiffieHellman__private_key" ) :
func ( self , * args , ** kwargs )
else :
self . generate_private_key ( )
func ( self , * args , ** kwargs )
return func_wrapper |
def get_container_setting ( name , container , settings ) :
'''Get the value of the setting for the IIS container .
. . versionadded : : 2016.11.0
Args :
name ( str ) : The name of the IIS container .
container ( str ) : The type of IIS container . The container types are :
AppPools , Sites , SslBindings ... | ret = dict ( )
ps_cmd = list ( )
ps_cmd_validate = list ( )
container_path = r"IIS:\{0}\{1}" . format ( container , name )
if not settings :
log . warning ( 'No settings provided' )
return ret
ps_cmd . append ( r'$Settings = @{};' )
for setting in settings : # Build the commands to verify that the property name... |
def _process_net_mhcii ( mhc_file , normal = False ) :
"""Process the results from running NetMHCIIpan binding predictions into a pandas dataframe .
: param str mhc _ file : Output file containing netmhciipan mhcii : peptide binding predictions
: param bool normal : Is this processing the results of a normal ? ... | results = pandas . DataFrame ( columns = [ 'allele' , 'pept' , 'tumor_pred' , 'core' , 'peptide_name' ] )
with open ( mhc_file , 'r' ) as mf :
peptides = set ( )
# Get the allele from the first line and skip the second line
allele = re . sub ( '-DQB' , '/DQB' , mf . readline ( ) . strip ( ) )
_ = mf . r... |
def pause ( self , container ) :
"""Pauses all processes within a container .
Args :
container ( str ) : The container to pause
Raises :
: py : class : ` docker . errors . APIError `
If the server returns an error .""" | url = self . _url ( '/containers/{0}/pause' , container )
res = self . _post ( url )
self . _raise_for_status ( res ) |
def server_group_field_data ( request ) :
"""Returns a list of tuples of all server groups .
Generates a list of server groups available . And returns a list of
( id , name ) tuples .
: param request : django http request object
: return : list of ( id , name ) tuples""" | server_groups = server_group_list ( request )
if server_groups :
server_groups_list = [ ( sg . id , sg . name ) for sg in server_groups ]
server_groups_list . sort ( key = lambda obj : obj [ 1 ] )
return [ ( "" , _ ( "Select Server Group" ) ) , ] + server_groups_list
return [ ( "" , _ ( "No server groups av... |
def downzip ( url , destination = './sample_data/' ) :
"""Download , unzip and delete .""" | # url = " http : / / 147.228.240.61 / queetech / sample - data / jatra _ 06mm _ jenjatra . zip "
logmsg = "downloading from '" + url + "'"
print ( logmsg )
logger . debug ( logmsg )
local_file_name = os . path . join ( destination , 'tmp.zip' )
urllibr . urlretrieve ( url , local_file_name )
datafile = zipfile . ZipFil... |
def reset ( self ) :
"""Reset the widget , and clear the scene .""" | self . minimum = None
self . maximum = None
self . start_time = None
# datetime , absolute start time
self . idx_current = None
self . idx_markers = [ ]
self . idx_annot = [ ]
if self . scene is not None :
self . scene . clear ( )
self . scene = None |
def warn_quirks ( message , recommend , pattern , index ) :
"""Warn quirks .""" | import traceback
import bs4
# noqa : F401
# Acquire source code line context
paths = ( MODULE , sys . modules [ 'bs4' ] . __path__ [ 0 ] )
tb = traceback . extract_stack ( )
previous = None
filename = None
lineno = None
for entry in tb :
if ( PY35 and entry . filename . startswith ( paths ) ) or ( not PY35 and entr... |
def install_module ( self , install_optional = False , production_only = False , force = False , frozen_lockfile = True , node_paths = None ) :
"""Returns a command that when executed will install node package .
: param install _ optional : True to install optional dependencies .
: param production _ only : Tru... | args = self . _get_installation_args ( install_optional = install_optional , production_only = production_only , force = force , frozen_lockfile = frozen_lockfile )
return self . run_command ( args = args , node_paths = node_paths ) |
def get ( self , request , bot_id , id , format = None ) :
"""Get environment variable by id
serializer : EnvironmentVarSerializer
responseMessages :
- code : 401
message : Not authenticated""" | return super ( EnvironmentVarDetail , self ) . get ( request , bot_id , id , format ) |
def status ( self , ) :
"""The global status that summerizes all actions
The status will be calculated in the following order :
If any error occured , the status will be : data : ` ActionStatus . ERROR ` .
If any failure occured , the status will be : data : ` ActionStatus . FAILURE ` .
If all actions were ... | status = ActionStatus ( ActionStatus . SUCCESS , "All actions succeeded." )
for a in self . actions :
if a . status . value == ActionStatus . ERROR :
status = ActionStatus ( ActionStatus . ERROR , "Error: action \"%s\" raised an error!" % a . name , a . status . traceback )
break
if a . status .... |
def all_lemmas ( self ) :
'''A generator over all the lemmas in the GermaNet database .''' | for lemma_dict in self . _mongo_db . lexunits . find ( ) :
yield Lemma ( self , lemma_dict ) |
def to_number ( result_type , value , default = None , minimum = None , maximum = None ) :
"""Cast ` value ` to numeric ` result _ type ` if possible
Args :
result _ type ( type ) : Numerical type to convert to ( one of : int , float , . . . )
value ( str | unicode ) : Value to convert
default ( result _ ty... | try :
return capped ( result_type ( value ) , minimum , maximum )
except ( TypeError , ValueError ) :
return default |
def extract_variables ( content ) :
"""extract all variables in content recursively .""" | if isinstance ( content , ( list , set , tuple ) ) :
variables = set ( )
for item in content :
variables = variables | extract_variables ( item )
return variables
elif isinstance ( content , dict ) :
variables = set ( )
for key , value in content . items ( ) :
variables = variables |... |
def set_index ( self , schema , name , fields , ** index_options ) :
"""add an index to the table
schema - - Schema ( )
name - - string - - the name of the index
fields - - array - - the fields the index should be on
* * index _ options - - dict - - any index options that might be useful to create the index... | with self . transaction ( ** index_options ) as connection :
index_options [ 'connection' ] = connection
self . _set_index ( schema , name , fields , ** index_options )
return True |
def coerce ( value ) :
"""Coerces a Bool , None , or int into Bit / Propositional form""" | if isinstance ( value , BoolCell ) :
return value
elif isinstance ( value , Cell ) :
raise CellConstructionFailure ( "Cannot convert %s to BoolCell" % type ( value ) )
elif value in [ 1 , T ] :
return BoolCell ( T )
elif value in [ 0 , - 1 , F ] :
return BoolCell ( F )
elif value in [ None , U ] :
r... |
def tabbed_parsing_character_generator ( tmp_dir , train ) :
"""Generate source and target data from a single file .""" | character_vocab = text_encoder . ByteTextEncoder ( )
filename = "parsing_{0}.pairs" . format ( "train" if train else "dev" )
pair_filepath = os . path . join ( tmp_dir , filename )
return text_problems . text2text_generate_encoded ( text_problems . text2text_txt_tab_iterator ( pair_filepath ) , character_vocab ) |
def nb_to_html_cells ( nb ) -> list :
"""Converts notebook to an iterable of BS4 HTML nodes . Images are inline .""" | html_exporter = HTMLExporter ( )
html_exporter . template_file = 'basic'
( body , resources ) = html_exporter . from_notebook_node ( nb )
return BeautifulSoup ( body , 'html.parser' ) . findAll ( 'div' , class_ = 'cell' ) |
def filter_flags ( use , use_expand_hidden , usemasked , useforced ) :
'''. . versionadded : : 2015.8.0
Filter function to remove hidden or otherwise not normally
visible USE flags from a list .
@ type use : list
@ param use : the USE flag list to be filtered .
@ type use _ expand _ hidden : list
@ para... | portage = _get_portage ( )
# clean out some environment flags , since they will most probably
# be confusing for the user
for f in use_expand_hidden :
f = f . lower ( ) + "_"
for x in use :
if f in x :
use . remove ( x )
# clean out any arch ' s
archlist = portage . settings [ "PORTAGE_ARCHL... |
def get_items ( self , page = 1 , order_by = None , filters = None ) :
"""Fetch database for items matching .
Args :
page ( int ) :
which page will be sliced
slice size is ` ` self . per _ page ` ` .
order _ by ( str ) :
a field name to order query by .
filters ( dict ) :
a ` ` filter name ` ` : ` `... | start = ( page - 1 ) * self . per_page
query = self . get_query ( )
if order_by is not None :
query = query . order_by ( self . _get_field ( order_by ) )
if filters is not None :
query = self . _filter ( query , filters )
return query . offset ( start ) . limit ( self . per_page ) , self . count ( query ) |
def temporal_snr ( signal_dset , noise_dset , mask = None , prefix = 'temporal_snr.nii.gz' ) :
'''Calculates temporal SNR by dividing average signal of ` ` signal _ dset ` ` by SD of ` ` noise _ dset ` ` .
` ` signal _ dset ` ` should be a dataset that contains the average signal value ( i . e . , nothing that ha... | for d in [ ( 'mean' , signal_dset ) , ( 'stdev' , noise_dset ) ] :
new_d = nl . suffix ( d [ 1 ] , '_%s' % d [ 0 ] )
cmd = [ '3dTstat' , '-%s' % d [ 0 ] , '-prefix' , new_d ]
if mask :
cmd += [ '-mask' , mask ]
cmd += [ d [ 1 ] ]
nl . run ( cmd , products = new_d )
nl . calc ( [ nl . suffix ... |
def fetch_friends ( self , user ) :
"""fetches the friends from twitter using the
information on django - social - auth models
user is an instance of UserSocialAuth
Returns :
collection of friend objects fetched from facebook""" | # Fetch the token key and secret
if USING_ALLAUTH :
social_app = SocialApp . objects . get_current ( 'twitter' )
consumer_key = social_app . key
consumer_secret = social_app . secret
oauth_token = SocialToken . objects . get ( account = user , app = social_app ) . token
oauth_token_secret = SocialTo... |
def compare ( string1 , string2 ) :
"""Compare two strings while protecting against timing attacks
: param str string1 : the first string
: param str string2 : the second string
: returns : True if the strings are equal , False if not
: rtype : : obj : ` bool `""" | if len ( string1 ) != len ( string2 ) :
return False
result = True
for c1 , c2 in izip ( string1 , string2 ) :
result &= c1 == c2
return result |
def joint_entropy_calc ( classes , table , POP ) :
"""Calculate joint entropy .
: param classes : confusion matrix classes
: type classes : list
: param table : confusion matrix table
: type table : dict
: param POP : population
: type POP : dict
: return : joint entropy as float""" | try :
result = 0
for i in classes :
for index , j in enumerate ( classes ) :
p_prime = table [ i ] [ j ] / POP [ i ]
if p_prime != 0 :
result += p_prime * math . log ( p_prime , 2 )
return - result
except Exception :
return "None" |
def _get_pygments_extensions ( ) :
"""Return all file type extensions supported by Pygments""" | # NOTE : Leave this import here to keep startup process fast !
import pygments . lexers as lexers
extensions = [ ]
for lx in lexers . get_all_lexers ( ) :
lexer_exts = lx [ 2 ]
if lexer_exts : # Reference : This line was included for leaving untrimmed the
# extensions not starting with ` * `
other_e... |
def CreateApproval ( self , reason = None , notified_users = None , email_cc_addresses = None , keep_client_alive = False ) :
"""Create a new approval for the current user to access this client .""" | if not reason :
raise ValueError ( "reason can't be empty" )
if not notified_users :
raise ValueError ( "notified_users list can't be empty." )
approval = user_pb2 . ApiClientApproval ( reason = reason , notified_users = notified_users , email_cc_addresses = email_cc_addresses or [ ] )
args = user_pb2 . ApiCrea... |
def launch_subshell ( self , shell_cls , cmd , args , * , prompt = None , context = { } ) :
"""Launch a subshell .
The doc string of the cmdloop ( ) method explains how shell histories and
history files are saved and restored .
The design of the _ ShellBase class encourage launching of subshells through
the... | # Save history of the current shell .
readline . write_history_file ( self . history_fname )
prompt = prompt if prompt else shell_cls . __name__
mode = _ShellBase . _Mode ( shell = self , cmd = cmd , args = args , prompt = prompt , context = context , )
shell = shell_cls ( batch_mode = self . batch_mode , debug = self ... |
def _dbg ( self , level , msg ) :
"""Write debugging output to sys . stderr .""" | if level <= self . debug :
print ( msg , file = sys . stderr ) |
def parse_docstring ( whatever_has_docstring ) :
'''Parse a docstring into a semmary ( first line ) and notes ( rest of it ) .''' | try :
summary , notes = whatever_has_docstring . __doc__ . split ( '\n' , 1 )
notes = dedent ( notes ) . replace ( '\n' , ' ' )
except ValueError :
summary = whatever_has_docstring . __doc__ . strip ( )
notes = ''
return summary , notes |
def dayproc ( st , lowcut , highcut , filt_order , samp_rate , starttime , debug = 0 , parallel = True , num_cores = False , ignore_length = False , seisan_chan_names = False , fill_gaps = True ) :
"""Wrapper for dayproc to parallel multiple traces in a stream .
Works in place on data . This is employed to ensure... | # Add sanity check for filter
if isinstance ( st , Trace ) :
st = Stream ( st )
tracein = True
else :
tracein = False
if highcut and highcut >= 0.5 * samp_rate :
raise IOError ( 'Highcut must be lower than the nyquist' )
if debug > 4 :
parallel = False
# Set the start - time to a day start - cope wi... |
def _schedule_processing_blocks ( self ) :
"""Schedule Processing Blocks for execution .""" | LOG . info ( 'Starting to Schedule Processing Blocks.' )
while True :
time . sleep ( 0.5 )
if not self . _queue :
continue
if self . _num_pbcs >= self . _max_pbcs :
LOG . warning ( 'Resource limit reached!' )
continue
_inspect = Inspect ( app = APP )
if self . _queue and _ins... |
def cov ( self , ddof = None , bias = 0 ) :
'''The covariance matrix from the aggregate sample . It accepts an
optional parameter for the degree of freedoms .
: parameter ddof : If not ` ` None ` ` normalization is by ( N - ddof ) , where N is
the number of observations ; this overrides the value implied by b... | N = self . n
M = N if bias else N - 1
M = M if ddof is None else N - ddof
return ( self . sxx - outer ( self . sx , self . sx ) / N ) / M |
def grouper ( n , iterable , fillvalue = None ) :
"grouper ( 3 , ' ABCDEFG ' , ' x ' ) - - > ABC DEF Gxx" | args = [ iter ( iterable ) ] * n
return itertools . izip_longest ( fillvalue = fillvalue , * args ) |
def get_resources ( self , types = None , names = None , languages = None ) :
"""Get resources .
types = a list of resource types to search for ( None = all )
names = a list of resource names to search for ( None = all )
languages = a list of resource languages to search for ( None = all )
Return a dict of ... | return GetResources ( self . filename , types , names , languages ) |
def regex_findall_variables ( content ) :
"""extract all variable names from content , which is in format $ variable
Args :
content ( str ) : string content
Returns :
list : variables list extracted from string content
Examples :
> > > regex _ findall _ variables ( " $ variable " )
[ " variable " ]
... | try :
vars_list = [ ]
for var_tuple in variable_regex_compile . findall ( content ) :
vars_list . append ( var_tuple [ 0 ] or var_tuple [ 1 ] )
return vars_list
except TypeError :
return [ ] |
def increment ( self ) :
"""Increment the last permutation we returned to the next .""" | # Increment position from the deepest place of the tree first .
for index in reversed ( range ( self . depth ) ) :
self . indexes [ index ] += 1
# We haven ' t reached the end of board , no need to adjust upper
# level .
if self . indexes [ index ] < self . range_size :
break
# We ' ve reach... |
def addParts ( parentPart , childPath , count , index ) :
"""BUILD A hierarchy BY REPEATEDLY CALLING self METHOD WITH VARIOUS childPaths
count IS THE NUMBER FOUND FOR self PATH""" | if index == None :
index = 0
if index == len ( childPath ) :
return
c = childPath [ index ]
parentPart . count = coalesce ( parentPart . count , 0 ) + count
if parentPart . partitions == None :
parentPart . partitions = FlatList ( )
for i , part in enumerate ( parentPart . partitions ) :
if part . name ... |
def from_dynacRepr ( cls , pynacRepr ) :
"""Construct a ` ` Set4DAperture ` ` instance from the Pynac lattice element""" | energyDefnFlag = int ( pynacRepr [ 1 ] [ 0 ] [ 0 ] )
energy = float ( pynacRepr [ 1 ] [ 0 ] [ 1 ] )
phase = float ( pynacRepr [ 1 ] [ 0 ] [ 2 ] )
x = float ( pynacRepr [ 1 ] [ 0 ] [ 3 ] )
y = float ( pynacRepr [ 1 ] [ 0 ] [ 4 ] )
radius = float ( pynacRepr [ 1 ] [ 0 ] [ 5 ] )
return cls ( energy , phase , x , y , radiu... |
def run ( self ) :
"""Load table data to : class : ` EuroStatsValue ` objects""" | # - - start documentation include : eurostats - run - 1
# create a new indicator metadata object
indicator = models . EuroStatIndicator ( number = self . number , description = self . description , url = "http://ec.europa.eu/eurostat/web/products-datasets/-/tgs" + self . number )
# add / commit to get the object ID fil... |
def gaussian_tuple_prior_for_arguments ( self , arguments ) :
"""Parameters
arguments : { Prior : float }
A dictionary of arguments
Returns
tuple _ prior : TuplePrior
A new tuple prior with gaussian priors""" | tuple_prior = TuplePrior ( )
for prior_tuple in self . prior_tuples :
setattr ( tuple_prior , prior_tuple . name , arguments [ prior_tuple . prior ] )
return tuple_prior |
def _setint ( self , int_ , length = None ) :
"""Reset the bitstring to have given signed int interpretation .""" | # If no length given , and we ' ve previously been given a length , use it .
if length is None and hasattr ( self , 'len' ) and self . len != 0 :
length = self . len
if length is None or length == 0 :
raise CreationError ( "A non-zero length must be specified with an int initialiser." )
if int_ >= ( 1 << ( leng... |
def url_decode_stream ( stream , charset = 'utf-8' , decode_keys = False , include_empty = True , errors = 'replace' , separator = '&' , cls = None , limit = None , return_iterator = False ) :
"""Works like : func : ` url _ decode ` but decodes a stream . The behavior
of stream and limit follows functions like
... | if return_iterator :
cls = lambda x : x
elif cls is None :
cls = MultiDict
pair_iter = make_chunk_iter ( stream , separator , limit )
return cls ( _url_decode_impl ( pair_iter , charset , decode_keys , include_empty , errors ) ) |
def build_vcf_inversion ( x1 , x2 , genome_2bit ) :
"""Provide representation of inversion from BedPE breakpoints .""" | id1 = "hydra{0}" . format ( x1 . name )
start_coords = sorted ( [ x1 . start1 , x1 . end1 , x2 . start1 , x2 . end1 ] )
end_coords = sorted ( [ x1 . start2 , x1 . end2 , x2 . start2 , x2 . start2 ] )
start_pos = ( start_coords [ 1 ] + start_coords [ 2 ] ) // 2
end_pos = ( end_coords [ 1 ] + end_coords [ 2 ] ) // 2
base... |
def create_cfg_segment ( filename , filecontent , description , auth , url ) :
"""Takes a str into var filecontent which represents the entire content of a configuration
segment , or partial configuration file . Takes a str into var description which represents the
description of the configuration segment
: p... | payload = { "confFileName" : filename , "confFileType" : "2" , "cfgFileParent" : "-1" , "confFileDesc" : description , "content" : filecontent }
f_url = url + "/imcrs/icc/confFile"
response = requests . post ( f_url , data = ( json . dumps ( payload ) ) , auth = auth , headers = HEADERS )
try :
if response . status... |
def validate ( self , document ) :
"""Check input for Python syntax errors .""" | # When the input starts with Ctrl - Z , always accept . This means EOF in a
# Python REPL .
if document . text . startswith ( '\x1a' ) :
return
try :
if self . get_compiler_flags :
flags = self . get_compiler_flags ( )
else :
flags = 0
compile ( document . text , '<input>' , 'exec' , fla... |
def clean ( text , cls = None , ** kwargs ) :
"""Public facing function to clean ` ` text ` ` using the scrubber ` ` cls ` ` by
replacing all personal information with ` ` { { PLACEHOLDERS } } ` ` .""" | cls = cls or Scrubber
scrubber = cls ( )
return scrubber . clean ( text , ** kwargs ) |
def _intersection_with_dsis ( self , dsis ) :
"""Intersection with another : class : ` DiscreteStridedIntervalSet ` .
: param dsis : The other operand .
: return :""" | new_si_set = set ( )
for si in dsis . _si_set :
r = self . _intersection_with_si ( si )
if isinstance ( r , StridedInterval ) :
if not r . is_empty :
new_si_set . add ( r )
else : # r is a DiscreteStridedIntervalSet
new_si_set |= r . _si_set
if len ( new_si_set ) :
ret = Disc... |
def _add_months ( self , date , months ) :
"""Add ` ` months ` ` months to ` ` date ` ` .
Unfortunately we can ' t use timedeltas to add months because timedelta counts in days
and there ' s no foolproof way to add N months in days without counting the number of
days per month .""" | year = date . year + ( date . month + months - 1 ) // 12
month = ( date . month + months - 1 ) % 12 + 1
return datetime . date ( year = year , month = month , day = 1 ) |
def get_text_for_html ( html_content ) :
'''Take the HTML content ( from , for example , an email )
and construct a simple plain text version of that content
( for example , for inclusion in a multipart email message ) .''' | soup = BeautifulSoup ( html_content )
# kill all script and style elements
for script in soup ( [ "script" , "style" ] ) :
script . extract ( )
# rip it out
# Replace all links with HREF with the link text and the href in brackets
for a in soup . findAll ( 'a' , href = True ) :
a . replaceWith ( '%s <%s>' % ( a... |
def get ( self , url : StrOrURL , * , allow_redirects : bool = True , ** kwargs : Any ) -> '_RequestContextManager' :
"""Perform HTTP GET request .""" | return _RequestContextManager ( self . _request ( hdrs . METH_GET , url , allow_redirects = allow_redirects , ** kwargs ) ) |
def insertBefore ( self , node : AbstractNode , ref_node : AbstractNode ) -> AbstractNode :
"""Insert a node just before the reference node .""" | return self . _insert_before ( node , ref_node ) |
def imageFields ( self ) :
"""Returns field names of image columns .
: return : a list of field names .
. . versionadded : : 2.3.0""" | if self . _imageFields is None :
ctx = SparkContext . _active_spark_context
self . _imageFields = list ( ctx . _jvm . org . apache . spark . ml . image . ImageSchema . imageFields ( ) )
return self . _imageFields |
def nfa_word_acceptance ( nfa : dict , word : list ) -> bool :
"""Checks if a given word is accepted by a NFA .
The word w is accepted by a NFA if exists at least an
accepting run on w .
: param dict nfa : input NFA ;
: param list word : list of symbols ∈ nfa [ ' alphabet ' ] ;
: return : * ( bool ) * , T... | current_level = set ( )
current_level = current_level . union ( nfa [ 'initial_states' ] )
next_level = set ( )
for action in word :
for state in current_level :
if ( state , action ) in nfa [ 'transitions' ] :
next_level . update ( nfa [ 'transitions' ] [ state , action ] )
if len ( next_le... |
def control_circuit_breakers ( self , mode = None ) :
"""Opens or closes all circuit breakers of all MV grids .
Args
mode : str
Set mode = ' open ' to open , mode = ' close ' to close""" | for grid_district in self . mv_grid_districts ( ) :
if mode == 'open' :
grid_district . mv_grid . open_circuit_breakers ( )
elif mode == 'close' :
grid_district . mv_grid . close_circuit_breakers ( )
else :
raise ValueError ( '\'mode\' is invalid.' )
if mode == 'open' :
logger . ... |
def extract_body ( mail , types = None , field_key = 'copiousoutput' ) :
"""Returns a string view of a Message .
If the ` types ` argument is set then any encoding types there will be used
as the prefered encoding to extract . If ` types ` is None then
: ref : ` prefer _ plaintext < prefer - plaintext > ` wil... | preferred = 'text/plain' if settings . get ( 'prefer_plaintext' ) else 'text/html'
has_preferred = False
# see if the mail has our preferred type
if types is None :
has_preferred = list ( typed_subpart_iterator ( mail , * preferred . split ( '/' ) ) )
body_parts = [ ]
for part in mail . walk ( ) : # skip non - leaf... |
def Send ( self , url , opname , pyobj , nsdict = { } , soapaction = None , chain = None , ** kw ) :
"""Returns a ProcessingChain which needs to be passed to Receive if
Send is being called consecutively .""" | url = url or self . url
cookies = None
if chain is not None :
cookies = chain . flow . cookies
d = { }
d . update ( self . nsdict )
d . update ( nsdict )
if soapaction is not None :
self . addHTTPHeader ( 'SOAPAction' , soapaction )
chain = self . factory . newInstance ( )
soapdata = chain . processRequest ( py... |
def validate ( cls , job_config ) :
"""Validates relevant parameters .
This method can validate fields which it deems relevant .
Args :
job _ config : an instance of map _ job . JobConfig .
Raises :
errors . BadReaderParamsError : required parameters are missing or invalid .""" | if job_config . input_reader_cls != cls :
raise errors . BadReaderParamsError ( "Expect input reader class %r, got %r." % ( cls , job_config . input_reader_cls ) ) |
def sign ( self , encoded ) :
"""Return authentication signature of encoded bytes""" | signature = self . _hmac . copy ( )
signature . update ( encoded )
return signature . hexdigest ( ) . encode ( 'utf-8' ) |
def mavlink_packet ( self , m ) :
'''handle REMOTE _ LOG _ DATA _ BLOCK packets''' | now = time . time ( )
if m . get_type ( ) == 'REMOTE_LOG_DATA_BLOCK' :
if self . stopped : # send a stop packet every second until the other end gets the idea :
if now - self . time_last_stop_packet_sent > 1 :
if self . log_settings . verbose :
print ( "DFLogger: Sending stop pac... |
def to_long_format ( df , duration_col ) :
"""This function converts a survival analysis DataFrame to a lifelines " long " format . The lifelines " long "
format is used in a common next function , ` ` add _ covariate _ to _ timeline ` ` .
Parameters
df : DataFrame
a DataFrame in the standard survival analy... | return df . assign ( start = 0 , stop = lambda s : s [ duration_col ] ) . drop ( duration_col , axis = 1 ) |
def _initialize ( self , con ) :
"""Set up tables in SQL""" | if self . initialized :
return
SQLite3Database ( ) . _initialize ( con )
# ASE db initialization
cur = con . execute ( 'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"' )
if cur . fetchone ( ) [ 0 ] == 0 : # no reaction table
for init_command in init_commands :
con . execute ( init_command )
... |
def south_field_triple ( self ) :
"Returns a suitable description of this field for South ." | args , kwargs = introspector ( self )
kwargs . update ( { 'populate_from' : 'None' if callable ( self . populate_from ) else repr ( self . populate_from ) , 'unique_with' : repr ( self . unique_with ) } )
return ( 'autoslug.fields.AutoSlugField' , args , kwargs ) |
def stop ( self ) :
"""停止引擎""" | # 将引擎设为停止
self . __active = False
# 停止计时器
self . __timer . stop ( )
# 等待事件处理线程退出
self . __thread . join ( ) |
def rank ( self , ** kwargs ) :
"""Computes numerical rank along axis . Equal values are set to the average .
Returns :
DataManager containing the ranks of the values along an axis .""" | axis = kwargs . get ( "axis" , 0 )
numeric_only = True if axis else kwargs . get ( "numeric_only" , False )
func = self . _prepare_method ( pandas . DataFrame . rank , ** kwargs )
new_data = self . _map_across_full_axis ( axis , func )
# Since we assume no knowledge of internal state , we get the columns
# from the int... |
def _get_name ( self ) :
"""Returns the name , which is generated if it has not been already .""" | if self . _name is None :
self . _name = self . _generate_name ( )
return self . _name |
def show_fabric_trunk_info_output_show_trunk_list_trunk_list_groups_trunk_list_group ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
show_fabric_trunk_info = ET . Element ( "show_fabric_trunk_info" )
config = show_fabric_trunk_info
output = ET . SubElement ( show_fabric_trunk_info , "output" )
show_trunk_list = ET . SubElement ( output , "show-trunk-list" )
trunk_list_groups = ET . SubElement ( show_trunk_list , "t... |
def FastaIter ( handle ) :
"""generator that returns ( header , sequence ) tuples from an open FASTA file handle
Lines before the start of the first record are ignored .""" | header = None
for line in handle :
if line . startswith ( ">" ) :
if header is not None : # not the first record
yield header , "" . join ( seq_lines )
seq_lines = list ( )
header = line [ 1 : ] . rstrip ( )
else :
if header is not None : # not the first record
... |
def fetchone ( table , cols = "*" , where = ( ) , group = "" , order = ( ) , limit = ( ) , ** kwargs ) :
"""Convenience wrapper for database SELECT and fetch one .""" | return select ( table , cols , where , group , order , limit , ** kwargs ) . fetchone ( ) |
def get_a_manager ( threadPool_settings = None ) :
"""On first call , creates and returns a @ mirte . core . Manager . On
subsequent calls , returns the previously created instance .
If it is the first call , it will initialize the threadPool
with @ threadPool _ settings .""" | global __singleton_manager
if __singleton_manager is None :
def _thread_entry ( ) :
if prctl :
prctl . set_name ( 'mirte manager' )
m . run ( )
l . info ( 'manager.run() returned' )
l = logging . getLogger ( 'mirte.get_a_manager' )
l . info ( "Creating new instance" )
... |
def discover ( self , exclude = None ) :
"""Automatically discovers and registers installed formats .
If a format is already registered with an exact same name , the
discovered format will not be registered .
: param exclude : ( optional ) Exclude formats from registering""" | if exclude is None :
exclude = [ ]
elif not isinstance ( exclude , ( list , tuple ) ) :
exclude = [ exclude ]
if 'json' not in exclude and 'json' not in self . registered_formats :
self . discover_json ( )
if 'yaml' not in exclude and 'yaml' not in self . registered_formats :
self . discover_yaml ( ) |
def update ( self , request , key ) :
"""Set an email address as primary address .""" | request . UPDATE = http . QueryDict ( request . body )
email_addr = request . UPDATE . get ( 'email' )
user_id = request . UPDATE . get ( 'user' )
if not email_addr :
return http . HttpResponseBadRequest ( )
try :
email = EmailAddress . objects . get ( address = email_addr , user_id = user_id )
except EmailAddr... |
def get_child_edge ( cls , index , left_parent , right_parent ) :
"""Construct a child edge from two parent edges .""" | [ ed1 , ed2 , depend_set ] = cls . _identify_eds_ing ( left_parent , right_parent )
left_u , right_u = cls . get_conditional_uni ( left_parent , right_parent )
X = np . array ( [ [ x , y ] for x , y in zip ( left_u , right_u ) ] )
name , theta = Bivariate . select_copula ( X )
new_edge = Edge ( index , ed1 , ed2 , name... |
def shorten ( text ) :
"""Reduce text length for displaying / logging purposes .""" | if len ( text ) >= MAX_DISPLAY_LEN :
text = text [ : MAX_DISPLAY_LEN // 2 ] + "..." + text [ - MAX_DISPLAY_LEN // 2 : ]
return text |
def calc_mass_from_fit_and_conv_factor ( A , Damping , ConvFactor ) :
"""Calculates mass from the A parameter from fitting , the damping from
fitting in angular units and the Conversion factor calculated from
comparing the ratio of the z signal and first harmonic of z .
Parameters
A : float
A factor calcu... | T0 = 300
mFromA = 2 * Boltzmann * T0 / ( pi * A ) * ConvFactor ** 2 * Damping
return mFromA |
def local_manager_is_default ( self , adm_gid , gid ) :
"""Check whether gid is default group for local manager group .""" | config = self . root [ 'settings' ] [ 'ugm_localmanager' ] . attrs
rule = config [ adm_gid ]
if gid not in rule [ 'target' ] :
raise Exception ( u"group '%s' not managed by '%s'" % ( gid , adm_gid ) )
return gid in rule [ 'default' ] |
def getAllViewsAsDict ( self ) :
"""Return all the stats views ( dict ) .""" | return { p : self . _plugins [ p ] . get_views ( ) for p in self . _plugins } |
def sendPartialResponse ( self ) :
"""Send a partial response without closing the connection .
: return : < void >""" | self . requestProtocol . requestResponse [ "code" ] = ( self . responseCode )
self . requestProtocol . requestResponse [ "content" ] = ( self . responseContent )
self . requestProtocol . requestResponse [ "errors" ] = ( self . responseErrors )
self . requestProtocol . sendPartialRequestResponse ( ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.