signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def save_metadata ( self , data_dir , feature_name = None ) :
"""See base class for details .""" | # Recursively save all child features
for feature_key , feature in six . iteritems ( self . _feature_dict ) :
if feature_name :
feature_key = '-' . join ( ( feature_name , feature_key ) )
feature . save_metadata ( data_dir , feature_name = feature_key ) |
def get_project_name ( project_id , projects ) :
"""Retrieves project name for given project id
Args :
projects : List of projects
project _ id : project id
Returns : Project name or None if there is no match""" | for project in projects :
if project_id == project . id :
return project . name |
def fromexportreg ( cls , bundle , export_reg ) : # type : ( Bundle , ExportRegistration ) - > RemoteServiceAdminEvent
"""Creates a RemoteServiceAdminEvent object from an ExportRegistration""" | exc = export_reg . get_exception ( )
if exc :
return RemoteServiceAdminEvent ( RemoteServiceAdminEvent . EXPORT_ERROR , bundle , export_reg . get_export_container_id ( ) , export_reg . get_remoteservice_id ( ) , None , None , exc , export_reg . get_description ( ) , )
return RemoteServiceAdminEvent ( RemoteServiceA... |
def create_from_raw_data ( self , klass , raw_data , headers = { } ) :
"""Creates an object from raw _ data previously obtained by : attr : ` github . GithubObject . GithubObject . raw _ data ` ,
and optionaly headers previously obtained by : attr : ` github . GithubObject . GithubObject . raw _ headers ` .
: p... | return klass ( self . __requester , headers , raw_data , completed = True ) |
def fcoe_get_login_output_fcoe_login_list_fcoe_login_interface_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
fcoe_get_login = ET . Element ( "fcoe_get_login" )
config = fcoe_get_login
output = ET . SubElement ( fcoe_get_login , "output" )
fcoe_login_list = ET . SubElement ( output , "fcoe-login-list" )
fcoe_login_session_mac_key = ET . SubElement ( fcoe_login_list , "fcoe-login-session-mac" ... |
def get_vnetwork_dvpgs_output_vnetwork_dvpgs_datacenter ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_vnetwork_dvpgs = ET . Element ( "get_vnetwork_dvpgs" )
config = get_vnetwork_dvpgs
output = ET . SubElement ( get_vnetwork_dvpgs , "output" )
vnetwork_dvpgs = ET . SubElement ( output , "vnetwork-dvpgs" )
datacenter = ET . SubElement ( vnetwork_dvpgs , "datacenter" )
datacenter . ... |
def workspace_backup_add ( ctx ) :
"""Create a new backup""" | backup_manager = WorkspaceBackupManager ( Workspace ( ctx . resolver , directory = ctx . directory , mets_basename = ctx . mets_basename , automatic_backup = ctx . automatic_backup ) )
backup_manager . add ( ) |
def _get_name ( self , graph , group = None ) :
"""Convert a molecular graph into a unique name
This method is not sensitive to the order of the atoms in the graph .""" | if group is not None :
graph = graph . get_subgraph ( group , normalize = True )
fingerprint = graph . fingerprint . tobytes ( )
name = self . name_cache . get ( fingerprint )
if name is None :
name = "NM%02i" % len ( self . name_cache )
self . name_cache [ fingerprint ] = name
return name |
def css_classes ( self , extra_classes = None ) :
"""Returns a string of space - separated CSS classes for the wrapping element of this input field .""" | if hasattr ( extra_classes , 'split' ) :
extra_classes = extra_classes . split ( )
extra_classes = set ( extra_classes or [ ] )
# field _ css _ classes is an optional member of a Form optimized for django - angular
field_css_classes = getattr ( self . form , 'field_css_classes' , None )
if hasattr ( field_css_class... |
def import_pyqt5 ( ) :
"""Import PyQt5
ImportErrors raised within this function are non - recoverable""" | from PyQt5 import QtGui , QtCore , QtSvg
# Alias PyQt - specific functions for PySide compatibility .
QtCore . Signal = QtCore . pyqtSignal
QtCore . Slot = QtCore . pyqtSlot
return QtCore , QtGui , QtSvg , QT_API_PYQT5 |
def integrate ( self , t , pot , method = 'symplec4_c' , dt = None ) :
"""NAME :
integrate
PURPOSE :
integrate the orbit
INPUT :
t - list of times at which to output ( 0 has to be in this ! )
pot - potential instance or list of instances
method = ' odeint ' for scipy ' s odeint
' leapfrog ' for a si... | if hasattr ( self , '_orbInterp' ) :
delattr ( self , '_orbInterp' )
if hasattr ( self , 'rs' ) :
delattr ( self , 'rs' )
thispot = toPlanarPotential ( pot )
self . t = nu . array ( t )
self . _pot = thispot
self . orbit , msg = _integrateOrbit ( self . vxvv , thispot , t , method , dt )
return msg |
def safe_setattr ( obj , name , value ) :
"""Attempt to setattr but catch AttributeErrors .""" | try :
setattr ( obj , name , value )
return True
except AttributeError :
return False |
def tokenize ( self , data ) :
"""Tokenizes the given string . A token is a 4 - tuple of the form :
( token _ type , tag _ name , tag _ options , token _ text )
token _ type
One of : TOKEN _ TAG _ START , TOKEN _ TAG _ END , TOKEN _ NEWLINE , TOKEN _ DATA
tag _ name
The name of the tag if token _ type = T... | data = data . replace ( '\r\n' , '\n' ) . replace ( '\r' , '\n' )
pos = start = end = 0
ld = len ( data )
tokens = [ ]
while pos < ld :
start = data . find ( self . tag_opener , pos )
if start >= pos : # Check to see if there was data between this start and the last end .
if start > pos :
tl... |
def _handle_api ( self , handler , handler_args , handler_kwargs ) :
"""Handle call to subclasses and convert the output to an appropriate value""" | try :
status_code , return_value = handler ( * handler_args , ** handler_kwargs )
except APIError as error :
return error . send ( )
web . ctx . status = _convert_http_status ( status_code )
return _api_convert_output ( return_value ) |
def create_bucket ( self , bucket ) :
"""Create a new bucket .""" | details = self . _details ( method = b"PUT" , url_context = self . _url_context ( bucket = bucket ) , )
query = self . _query_factory ( details )
return self . _submit ( query ) |
def pause ( self , remaining_pause_cycles ) :
"""Pause a subscription""" | url = urljoin ( self . _url , '/pause' )
elem = ElementTreeBuilder . Element ( self . nodename )
elem . append ( Resource . element_for_value ( 'remaining_pause_cycles' , remaining_pause_cycles ) )
body = ElementTree . tostring ( elem , encoding = 'UTF-8' )
response = self . http_request ( url , 'PUT' , body , { 'Conte... |
def onEdge ( self , canvas ) :
"""Returns a list of the sides of the sprite
which are touching the edge of the canvas .
0 = Bottom
1 = Left
2 = Top
3 = Right""" | sides = [ ]
if int ( self . position [ 0 ] ) <= 0 :
sides . append ( 1 )
if ( int ( self . position [ 0 ] ) + self . image . width ) >= canvas . width :
sides . append ( 3 )
if int ( self . position [ 1 ] ) <= 0 :
sides . append ( 2 )
if ( int ( self . position [ 1 ] ) + self . image . height ) >= canvas . ... |
def slice_begin ( self , tensor_shape , pnum ) :
"""Begin position for the tensor slice for the given processor .
Args :
tensor _ shape : Shape .
pnum : int < = self . size .
Returns :
list of integers with length tensor _ shape . ndims .""" | tensor_layout = self . tensor_layout ( tensor_shape )
coordinates = pnum_to_processor_coordinates ( self . shape , pnum )
ret = [ ]
for dim_size , mesh_axis in zip ( tensor_shape . to_integer_list , tensor_layout . tensor_axis_to_mesh_axis ) :
if mesh_axis is None :
ret . append ( 0 )
else :
ret... |
def unlink ( self ) :
"""Overrides orm unlink method .
@ param self : The object pointer
@ return : True / False .""" | for room in self :
for reserv_line in room . room_reservation_line_ids :
if reserv_line . status == 'confirm' :
raise ValidationError ( _ ( 'User is not able to delete the \
room after the room in %s state \
... |
def csep_periodic ( ra , rb , L ) :
"""Return separation vectors between each pair of the two sets of points .
Parameters
ra , rb : float array - like , shape ( n , d ) and ( m , d ) in d dimensions .
Two sets of points .
L : float array , shape ( d , )
System lengths .
Returns
csep : float array - li... | seps = ra [ : , np . newaxis , : ] - rb [ np . newaxis , : , : ]
for i_dim in range ( ra . shape [ 1 ] ) :
seps_dim = seps [ : , : , i_dim ]
seps_dim [ seps_dim > L [ i_dim ] / 2.0 ] -= L [ i_dim ]
seps_dim [ seps_dim < - L [ i_dim ] / 2.0 ] += L [ i_dim ]
return seps |
def line_segment ( X0 , X1 ) :
r"""Calculate the voxel coordinates of a straight line between the two given
end points
Parameters
X0 and X1 : array _ like
The [ x , y ] or [ x , y , z ] coordinates of the start and end points of
the line .
Returns
coords : list of lists
A list of lists containing th... | X0 = sp . around ( X0 ) . astype ( int )
X1 = sp . around ( X1 ) . astype ( int )
if len ( X0 ) == 3 :
L = sp . amax ( sp . absolute ( [ [ X1 [ 0 ] - X0 [ 0 ] ] , [ X1 [ 1 ] - X0 [ 1 ] ] , [ X1 [ 2 ] - X0 [ 2 ] ] ] ) ) + 1
x = sp . rint ( sp . linspace ( X0 [ 0 ] , X1 [ 0 ] , L ) ) . astype ( int )
y = sp .... |
def _read_response ( self , may_block = False ) :
"""Wait for a response to become available , and read it .""" | # wait for response to become available
res = self . _waitfor_set ( yubikey_defs . RESP_PENDING_FLAG , may_block ) [ : 7 ]
# continue reading while response pending is set
while True :
this = self . _read ( )
flags = yubico_util . ord_byte ( this [ 7 ] )
if flags & yubikey_defs . RESP_PENDING_FLAG :
... |
def scrape ( url , params = None , user_agent = None ) :
'''Scrape a URL optionally with parameters .
This is effectively a wrapper around urllib2 . urlopen .''' | headers = { }
if user_agent :
headers [ 'User-Agent' ] = user_agent
data = params and six . moves . urllib . parse . urlencode ( params ) or None
req = six . moves . urllib . request . Request ( url , data = data , headers = headers )
f = six . moves . urllib . request . urlopen ( req )
text = f . read ( )
f . clos... |
def walk_code ( co , _prefix = '' ) :
"""Traverse a code object , finding all consts which are also code objects .
Yields pairs of ( name , code object ) .""" | name = _prefix + co . co_name
yield name , co
yield from chain . from_iterable ( walk_code ( c , _prefix = _extend_name ( name , co ) ) for c in co . co_consts if isinstance ( c , CodeType ) ) |
def form_uri ( item_content , item_class ) :
"""Form the URI for a music service element .
: param item _ content : The content dict of the item
: type item _ content : dict
: param item _ class : The class of the item
: type item _ class : Sub - class of
: py : class : ` soco . data _ structures . MusicS... | extension = None
if 'mime_type' in item_content :
extension = MIME_TYPE_TO_EXTENSION [ item_content [ 'mime_type' ] ]
out = URIS . get ( item_class )
if out :
out = out . format ( extension = extension , ** item_content )
return out |
def samReferencesToStr ( filenameOrSamfile , indent = 0 ) :
"""List SAM / BAM file reference names and lengths .
@ param filenameOrSamfile : Either a C { str } SAM / BAM file name or an
instance of C { pysam . AlignmentFile } .
@ param indent : An C { int } number of spaces to indent each line .
@ return : ... | indent = ' ' * indent
def _references ( sam ) :
result = [ ]
for i in range ( sam . nreferences ) :
result . append ( '%s%s (length %d)' % ( indent , sam . get_reference_name ( i ) , sam . lengths [ i ] ) )
return '\n' . join ( result )
if isinstance ( filenameOrSamfile , six . string_types ) :
... |
def create_slim_mapping ( self , subset = None , subset_nodes = None , relations = None , disable_checks = False ) :
"""Create a dictionary that maps between all nodes in an ontology to a subset
Arguments
ont : ` Ontology `
Complete ontology to be mapped . Assumed pre - filtered for relationship types
subse... | if subset is not None :
subset_nodes = self . extract_subset ( subset )
logger . info ( "Extracting subset: {} -> {}" . format ( subset , subset_nodes ) )
if subset_nodes is None or len ( subset_nodes ) == 0 :
raise ValueError ( "subset nodes is blank" )
subset_nodes = set ( subset_nodes )
logger . debug ( ... |
def calc_accel_tf ( self , lin , lout ) :
"""Compute the acceleration transfer function .
Parameters
lin : : class : ` ~ site . Location `
Location of input
lout : : class : ` ~ site . Location `
Location of output . Note that this would typically be midheight
of the layer .""" | tf = self . wave_at_location ( lout ) / self . wave_at_location ( lin )
return tf |
def set_alpha_value ( self , value ) :
'''setter
Learning rate .''' | if isinstance ( value , float ) is False :
raise TypeError ( "The type of __alpha_value must be float." )
self . __alpha_value = value |
def pop ( self ) :
'''Remove a the top container from the container stack''' | if not self . _containers :
raise KittyException ( 'no container to pop' )
self . _containers . pop ( )
if self . _container ( ) :
self . _container ( ) . pop ( ) |
def create_pull ( self , * args , ** kwds ) :
""": calls : ` POST / repos / : owner / : repo / pulls < http : / / developer . github . com / v3 / pulls > ` _
: param title : string
: param body : string
: param issue : : class : ` github . Issue . Issue `
: param base : string
: param head : string
: pa... | if len ( args ) + len ( kwds ) >= 4 :
return self . __create_pull_1 ( * args , ** kwds )
else :
return self . __create_pull_2 ( * args , ** kwds ) |
def find_by_index ( self , cls , index_name , value ) :
"""Find all rows matching index query - as per the gludb spec .""" | cur = self . _conn ( ) . cursor ( )
query = 'select id,value from %s where %s = ?' % ( cls . get_table_name ( ) , index_name )
found = [ ]
for row in cur . execute ( query , ( value , ) ) :
id , data = row [ 0 ] , row [ 1 ]
obj = cls . from_data ( data )
assert id == obj . id
found . append ( obj )
cur ... |
def initialize_config_values ( parsed ) :
"""Given the parsed args , initialize the dbt tracking code .
It would be nice to re - use this profile later on instead of parsing it
twice , but dbt ' s intialization is not structured in a way that makes that
easy .""" | try :
cfg = UserConfig . from_directory ( parsed . profiles_dir )
except RuntimeException :
cfg = UserConfig . from_dict ( None )
if cfg . send_anonymous_usage_stats :
dbt . tracking . initialize_tracking ( parsed . profiles_dir )
else :
dbt . tracking . do_not_track ( )
if cfg . use_colors :
dbt . ... |
def doVerify ( self ) :
"""Process the form submission , initating OpenID verification .""" | # First , make sure that the user entered something
openid_url = self . query . get ( 'openid_identifier' )
if not openid_url :
self . render ( 'Enter an OpenID Identifier to verify.' , css_class = 'error' , form_contents = openid_url )
return
immediate = 'immediate' in self . query
use_sreg = 'use_sreg' in sel... |
def cut_cross ( self , x , y , radius , data ) :
"""Cut two data subarrays that have a center at ( x , y ) and with
radius ( radius ) from ( data ) . Returns the starting pixel ( x0 , y0)
of each cut and the respective arrays ( xarr , yarr ) .""" | n = int ( round ( radius ) )
ht , wd = data . shape
x , y = int ( round ( x ) ) , int ( round ( y ) )
x0 , x1 = int ( max ( 0 , x - n ) ) , int ( min ( wd - 1 , x + n ) )
y0 , y1 = int ( max ( 0 , y - n ) ) , int ( min ( ht - 1 , y + n ) )
xarr = data [ y , x0 : x1 + 1 ]
yarr = data [ y0 : y1 + 1 , x ]
return ( x0 , y0... |
def process_exception ( self , request , e ) :
"""Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG = False .
: param request : HttpRequest
: param e : Exception""" | from jutil . email import send_email
assert isinstance ( request , HttpRequest )
full_path = request . get_full_path ( )
user = request . user
msg = '{full_path}\n{err} (IP={ip}, user={user}) {trace}' . format ( full_path = full_path , user = user , ip = get_real_ip ( request ) , err = e , trace = str ( traceback . for... |
def get_context_data ( self , ** kwargs ) :
"""Returns the context data to provide to the template .""" | context = super ( ) . get_context_data ( ** kwargs )
context [ 'topic' ] = self . object
context [ 'forum' ] = self . object . forum
return context |
def capture_heroku_database ( self ) :
"""Capture Heroku database backup .""" | self . print_message ( "Capturing database backup for app '%s'" % self . args . source_app )
args = [ "heroku" , "pg:backups:capture" , "--app=%s" % self . args . source_app , ]
if self . args . use_pgbackups :
args = [ "heroku" , "pgbackups:capture" , "--app=%s" % self . args . source_app , "--expire" , ]
subproce... |
def xpointerNewRange ( self , startindex , end , endindex ) :
"""Create a new xmlXPathObjectPtr of type range""" | if end is None :
end__o = None
else :
end__o = end . _o
ret = libxml2mod . xmlXPtrNewRange ( self . _o , startindex , end__o , endindex )
if ret is None :
raise treeError ( 'xmlXPtrNewRange() failed' )
return xpathObjectRet ( ret ) |
def post_process_images ( self , doctree ) :
"""Pick the best candidate for all image URIs .""" | super ( AbstractSlideBuilder , self ) . post_process_images ( doctree )
# figure out where this doctree is in relation to the srcdir
relative_base = ( [ '..' ] * doctree . attributes . get ( 'source' ) [ len ( self . srcdir ) + 1 : ] . count ( '/' ) )
for node in doctree . traverse ( nodes . image ) :
if node . get... |
def cms_identify ( self , url , timeout = 15 , headers = { } ) :
"""Function called when attempting to determine if a URL is identified
as being this particular CMS .
@ param url : the URL to attempt to identify .
@ param timeout : number of seconds before a timeout occurs on a http
connection .
@ param h... | self . out . debug ( "cms_identify" )
if isinstance ( self . regular_file_url , str ) :
rfu = [ self . regular_file_url ]
else :
rfu = self . regular_file_url
is_cms = False
for regular_file_url in rfu :
try :
hash = self . enumerate_file_hash ( url , regular_file_url , timeout , headers )
excep... |
def changeSuffixinASN ( asnfile , suffix ) :
"""Create a copy of the original asn file and change the name of all members
to include the suffix .""" | # Start by creating a new name for the ASN table
_new_asn = asnfile . replace ( '_asn.fits' , '_' + suffix + '_asn.fits' )
if os . path . exists ( _new_asn ) :
os . remove ( _new_asn )
# copy original ASN table to new table
shutil . copy ( asnfile , _new_asn )
# Open up the new copy and convert all MEMNAME ' s to i... |
def setup_datafind_runtime_frames_multi_calls_perifo ( cp , scienceSegs , outputDir , tags = None ) :
"""This function uses the glue . datafind library to obtain the location of all
the frame files that will be needed to cover the analysis of the data
given in scienceSegs . This function will not check if the r... | datafindcaches , _ = setup_datafind_runtime_cache_multi_calls_perifo ( cp , scienceSegs , outputDir , tags = tags )
datafindouts = convert_cachelist_to_filelist ( datafindcaches )
return datafindcaches , datafindouts |
def create_default_file ( cls , data = None , mode = None ) :
"""Create a config file and override data if specified .""" | filepath = cls . get_default_filepath ( )
if not filepath :
return False
filename = os . path . basename ( filepath )
config = read_file ( get_data_path ( ) , filename )
# Find and replace data in default config
data = data or { }
for k , v in six . iteritems ( data ) :
v = v or ""
config = re . sub ( r"^(%... |
def best_cat_heuristic_split ( self , ind , dep ) :
"""determine best categorical variable split using heuristic methods""" | split = Split ( None , None , None , None , 0 )
min_child_node_size = self . min_child_node_size
all_dep = np . unique ( dep . arr )
if len ( all_dep ) == 1 :
split . invalid_reason = InvalidSplitReason . PURE_NODE
return split
elif len ( dep . arr ) < min_child_node_size and dep . weights is None : # if not we... |
def load_h5_data ( path = '' , data_type = 'LFP' , y = None , electrode = None , warmup = 0. , scaling = 1. ) :
"""Function loading results from hdf5 file
Parameters
path : str
Path to hdf5 - file
data _ type : str
Signal types in [ ' CSD ' , ' LFP ' , ' CSDsum ' , ' LFPsum ' ] .
y : None or str
Name ... | assert y is not None or electrode is not None
if y is not None :
f = h5py . File ( os . path . join ( path , '%s_%ss.h5' % ( y , data_type ) ) )
data = f [ 'data' ] . value [ : , : , warmup : ]
if scaling != 1. :
np . random . shuffle ( data )
num_cells = int ( len ( data ) * scaling )
... |
def eliminate_diag_dom_nodes ( A , C , theta = 1.02 ) :
r"""Eliminate diagonally dominance .
Helper function that eliminates diagonally dominant rows and cols from A
in the separate matrix C . This is useful because it eliminates nodes in C
which we don ' t want coarsened . These eliminated nodes in C just be... | # Find the diagonally dominant rows in A .
A_abs = A . copy ( )
A_abs . data = np . abs ( A_abs . data )
D_abs = get_diagonal ( A_abs , norm_eq = 0 , inv = False )
diag_dom_rows = ( D_abs > ( theta * ( A_abs * np . ones ( ( A_abs . shape [ 0 ] , ) , dtype = A_abs ) - D_abs ) ) )
# Account for BSR matrices and translate... |
def load_sbml ( filename ) :
"""Load a model from a SBML file .
Parameters
filename : str
The input SBML filename .
Returns
model : NetworkModel
y0 : dict
Initial condition .
volume : Real or Real3 , optional
A size of the simulation volume .""" | import libsbml
document = libsbml . readSBML ( filename )
document . validateSBML ( )
num_errors = ( document . getNumErrors ( libsbml . LIBSBML_SEV_ERROR ) + document . getNumErrors ( libsbml . LIBSBML_SEV_FATAL ) )
if num_errors > 0 :
messages = "The generated document is not valid."
messages += " {} errors w... |
def encode_basestring ( s , _PY3 = PY3 , _q = u ( '"' ) ) :
"""Return a JSON representation of a Python string""" | if _PY3 :
if isinstance ( s , binary_type ) :
s = s . decode ( 'utf-8' )
else :
if isinstance ( s , str ) and HAS_UTF8 . search ( s ) is not None :
s = s . decode ( 'utf-8' )
def replace ( match ) :
return ESCAPE_DCT [ match . group ( 0 ) ]
return _q + ESCAPE . sub ( replace , s ) + _q |
def set_value ( self , attribute , section , value ) :
"""Sets requested attribute value .
Usage : :
> > > content = [ " [ Section A ] \\ n " , " ; Comment . \\ n " , " Attribute 1 = \\ " Value A \\ " \\ n " , " \\ n " , " [ Section B ] \\ n " , " Attribute 2 = \\ " Value B \\ " \\ n " ]
> > > sections _ file... | if not self . section_exists ( section ) :
LOGGER . debug ( "> Adding '{0}' section." . format ( section ) )
self . __sections [ section ] = OrderedDict ( ) if self . __preserve_order else dict ( )
self . __sections [ section ] [ attribute ] = value
return True |
def list ( self , include_claimed = False , echo = False , marker = None , limit = None ) :
"""Returns a list of messages for this queue .
By default only unclaimed messages are returned ; if you want claimed
messages included , pass ` include _ claimed = True ` . Also , the requester ' s
own messages are not... | return self . _message_manager . list ( include_claimed = include_claimed , echo = echo , marker = marker , limit = limit ) |
def remote_is_append_blob ( self ) : # type : ( Descriptor ) - > bool
"""Remote destination is an Azure Append Blob
: param Descriptor self : this
: rtype : bool
: return : remote is an Azure Append Blob""" | return self . entity . mode == blobxfer . models . azure . StorageModes . Append |
def calc_gradev_phase ( data , rate , mj , stride , confidence , noisetype ) :
"""see http : / / www . leapsecond . com / tools / adev _ lib . c
stride = mj for nonoverlapping allan deviation
stride = 1 for overlapping allan deviation
see http : / / en . wikipedia . org / wiki / Allan _ variance
1 1
s2y (... | d2 = data [ 2 * int ( mj ) : : int ( stride ) ]
d1 = data [ 1 * int ( mj ) : : int ( stride ) ]
d0 = data [ : : int ( stride ) ]
n = min ( len ( d0 ) , len ( d1 ) , len ( d2 ) )
if n == 0 :
RuntimeWarning ( "Data array length is too small: %i" % len ( data ) )
n = 1
v_arr = d2 [ : n ] - 2 * d1 [ : n ] + d0 [ : ... |
def atlasdb_get_zonefiles_by_block ( from_block , to_block , offset , count , name = None , con = None , path = None ) :
"""Look up all zonefile hashes in a block range . Optionally filter by name .
Returns [ { ' name ' : . . . , ' zonefile _ hash ' : . . . , ' block _ height ' : . . . , ' txid ' : . . . , ' inv ... | ret = None
if count > 100 :
return { 'error' : 'Count must be less than 100' }
with AtlasDBOpen ( con = con , path = path ) as dbcon :
sql = 'SELECT name,zonefile_hash,txid,block_height,inv_index FROM zonefiles WHERE block_height >= ? AND block_height <= ?'
args = ( from_block , to_block )
if name :
... |
def smoothing_cross_entropy ( logits , labels , vocab_size , confidence , gaussian = False ) :
"""Cross entropy with label smoothing to limit over - confidence .
Args :
logits : Tensor of shape [ batch _ size , ? , ? , ? , vocab _ size ] .
labels : Tensor of shape [ batch _ size , ? , ? , ? ] .
vocab _ size... | with tf . name_scope ( "smoothing_cross_entropy" , values = [ logits , labels ] ) : # Low confidence is given to all non - true labels , uniformly .
low_confidence = ( 1.0 - confidence ) / to_float ( vocab_size - 1 )
# Normalizing constant is the best cross - entropy value with soft targets .
# We subtract ... |
def skip ( self ) :
"""Determine whether or not this object should be skipped .
If this model instance is a parent of a single subclassed
instance , skip it . The subclassed instance will create this
parent instance for us .
TODO : Allow the user to force its creation ?""" | if self . skip_me is not None :
return self . skip_me
cls = self . instance . __class__
using = router . db_for_write ( cls , instance = self . instance )
collector = Collector ( using = using )
collector . collect ( [ self . instance ] , collect_related = False )
sub_objects = sum ( [ list ( i ) for i in collector... |
def Kdiag ( self , X , target ) :
"""Compute the diagonal of the covariance matrix associated to X .""" | foo = np . zeros ( ( X . shape [ 0 ] , X . shape [ 0 ] ) )
self . K ( X , X , foo )
target += np . diag ( foo ) |
def _detect_type_load_headers ( self , stream , statusline = None , known_format = None ) :
"""If known _ format is specified ( ' warc ' or ' arc ' ) ,
parse only as that format .
Otherwise , try parsing record as WARC , then try parsing as ARC .
if neither one succeeds , we ' re out of luck .""" | if known_format != 'arc' : # try as warc first
try :
rec_headers = self . warc_parser . parse ( stream , statusline )
return 'warc' , rec_headers
except StatusAndHeadersParserException as se :
if known_format == 'warc' :
msg = 'Invalid WARC record, first line: '
r... |
def addFile ( self , filename , fp ) :
"""Read and record protein information for a sample .
@ param filename : A C { str } file name .
@ param fp : An open file pointer to read the file ' s data from .
@ raise ValueError : If information for a pathogen / protein / sample
combination is given more than once... | if self . _sampleName :
sampleName = self . _sampleName
elif self . _sampleNameRegex :
match = self . _sampleNameRegex . search ( filename )
if match :
sampleName = match . group ( 1 )
else :
sampleName = filename
else :
sampleName = filename
outDir = join ( dirname ( filename ) , se... |
def _interpret_angle ( name , angle_object , angle_float , unit = 'degrees' ) :
"""Return an angle in radians from one of two arguments .
It is common for Skyfield routines to accept both an argument like
` alt ` that takes an Angle object as well as an ` alt _ degrees ` that
can be given a bare float or a se... | if angle_object is not None :
if isinstance ( angle_object , Angle ) :
return angle_object . radians
elif angle_float is not None :
return _unsexagesimalize ( angle_float ) * _from_degrees
raise ValueError ( 'you must either provide the {0}= parameter with' ' an Angle argument or supply the {0}_{1}= par... |
def main ( args ) :
'''Do everything awesome .''' | if SETUP :
args = _invoke ( SETUP , args )
if not args and DEFAULT :
DEFAULT ( )
else :
while args :
task = _get_task ( args [ 0 ] )
if task is None :
abort ( LOCALE [ 'error_no_task' ] , args [ 0 ] )
args = _invoke ( task , args [ 1 : ] )
if TEARDOWN :
TEARDOWN ( ) |
def union ( self , other ) :
"""Returns a FrozenList with other concatenated to the end of self .
Parameters
other : array - like
The array - like whose elements we are concatenating .
Returns
diff : FrozenList
The collection difference between self and other .""" | if isinstance ( other , tuple ) :
other = list ( other )
return type ( self ) ( super ( ) . __add__ ( other ) ) |
def _set_depth ( self , depth ) :
"""Depth setter .""" | if depth and ( ( not isinstance ( depth , int ) ) or ( isinstance ( depth , int ) and ( depth < 0 ) ) ) :
raise RuntimeError ( "Argument `depth` is not valid" )
self . _depth = depth |
def _setup_ipc ( self ) :
'''Setup the IPC PUB and SUB sockets for the proxy .''' | log . debug ( 'Setting up the internal IPC proxy' )
self . ctx = zmq . Context ( )
# Frontend
self . sub = self . ctx . socket ( zmq . SUB )
self . sub . bind ( PUB_PX_IPC_URL )
self . sub . setsockopt ( zmq . SUBSCRIBE , b'' )
log . debug ( 'Setting HWM for the proxy frontend: %d' , self . hwm )
try :
self . sub .... |
def drop_remove ( * args , ** kwargs ) :
"""Action when we need to remove dropped item .
: param * args : Position arguments .
: type * args : list
: param kwargs : Keywords arguments .
: type kwargs : dict""" | dropped_item = args [ 0 ]
field_list = kwargs [ 'field_list' ]
num_duplicate = 0
for i in range ( field_list . count ( ) ) :
if dropped_item . text ( ) == field_list . item ( i ) . text ( ) :
num_duplicate += 1
if num_duplicate > 1 : # Notes ( IS ) : For some reason , removeItemWidget is not working .
f... |
def _serve_file ( self , abspath , params ) :
"""Show a file .
The actual content of the file is rendered by _ handle _ content .""" | relpath = os . path . relpath ( abspath , self . _root )
breadcrumbs = self . _create_breadcrumbs ( relpath )
link_path = urlunparse ( [ '' , '' , relpath , '' , urlencode ( params ) , '' ] )
args = self . _default_template_args ( 'file.html' )
args . update ( { 'root_parent' : os . path . dirname ( self . _root ) , 'b... |
def do_inspect ( self , code , cursor_pos , detail_level = 0 ) :
"""Method called on help requests""" | self . _klog . info ( "{%s}" , code [ cursor_pos : cursor_pos + 10 ] )
# Find the token for which help is requested
token , start = token_at_cursor ( code , cursor_pos )
self . _klog . debug ( "token={%s} {%d}" , token , detail_level )
# Find the help for this token
if not is_magic ( token , start , code ) :
info =... |
def _if_statement ( test , if_function , else_function ) -> None :
"""Evaluate an if statement within a @ magicquil block .
If the test value is a Quil Addr then unwind it into quil code equivalent to an if then statement using jumps . Both
sides of the if statement need to be evaluated and placed into separate... | if isinstance ( test , Addr ) :
token = _program_context . set ( Program ( ) )
if_function ( )
if_program = _program_context . get ( )
_program_context . reset ( token )
if else_function :
token = _program_context . set ( Program ( ) )
else_function ( )
else_program = _progra... |
def is_analysis_compatible ( using ) :
"""Returns True if the analysis defined in Python land and ES for the connection ` using ` are compatible""" | python_analysis = collect_analysis ( using )
es_analysis = existing_analysis ( using )
if es_analysis == DOES_NOT_EXIST :
return True
# we want to ensure everything defined in Python land is exactly matched in ES land
for section in python_analysis : # there is an analysis section ( analysis , tokenizers , filters ... |
def obj2str ( obj ) :
"""String representation of an object for hashing""" | if isinstance ( obj , str_types ) :
return obj . encode ( "utf-8" )
elif isinstance ( obj , pathlib . Path ) :
return obj2str ( str ( obj ) )
elif isinstance ( obj , ( bool , int , float ) ) :
return str ( obj ) . encode ( "utf-8" )
elif obj is None :
return b"none"
elif isinstance ( obj , np . ndarray ... |
def send_message ( self , device_type , device_id , user_id , content ) :
"""主动发送消息给设备
详情请参考
https : / / iot . weixin . qq . com / wiki / new / index . html ? page = 3-4-3
: param device _ type : 设备类型 , 目前为 “ 公众账号原始ID ”
: param device _ id : 设备ID
: param user _ id : 微信用户账号的openid
: param content : 消息内容 ... | content = to_text ( base64 . b64encode ( to_binary ( content ) ) )
return self . _post ( 'transmsg' , data = { 'device_type' : device_type , 'device_id' : device_id , 'open_id' : user_id , 'content' : content } ) |
def get_wallace_tensor ( self , tau ) :
"""Gets the Wallace Tensor for determining yield strength
criteria .
Args :
tau ( 3x3 array - like ) : stress at which to evaluate
the wallace tensor""" | b = 0.5 * ( np . einsum ( "ml,kn->klmn" , tau , np . eye ( 3 ) ) + np . einsum ( "km,ln->klmn" , tau , np . eye ( 3 ) ) + np . einsum ( "nl,km->klmn" , tau , np . eye ( 3 ) ) + np . einsum ( "kn,lm->klmn" , tau , np . eye ( 3 ) ) + - 2 * np . einsum ( "kl,mn->klmn" , tau , np . eye ( 3 ) ) )
strain = self . get_strain_... |
def elem_to_internal ( elem , strip_ns = 1 , strip = 1 ) :
"""Convert an Element into an internal dictionary ( not JSON ! ) .""" | d = { }
elem_tag = elem . tag
if strip_ns :
elem_tag = strip_tag ( elem . tag )
else :
for key , value in list ( elem . attrib . items ( ) ) :
d [ '@' + key ] = value
# loop over subelements to merge them
for subelem in elem :
v = elem_to_internal ( subelem , strip_ns = strip_ns , strip = strip )
... |
def ProcessXMLAnnotation ( xml_file ) :
"""Process a single XML file containing a bounding box .""" | # pylint : disable = broad - except
try :
tree = ET . parse ( xml_file )
except Exception :
print ( 'Failed to parse: ' + xml_file , file = sys . stderr )
return None
# pylint : enable = broad - except
root = tree . getroot ( )
num_boxes = FindNumberBoundingBoxes ( root )
boxes = [ ]
for index in range ( nu... |
def _exploit ( self , trial_executor , trial , trial_to_clone ) :
"""Transfers perturbed state from trial _ to _ clone - > trial .
If specified , also logs the updated hyperparam state .""" | trial_state = self . _trial_state [ trial ]
new_state = self . _trial_state [ trial_to_clone ]
if not new_state . last_checkpoint :
logger . info ( "[pbt]: no checkpoint for trial." " Skip exploit for Trial {}" . format ( trial ) )
return
new_config = explore ( trial_to_clone . config , self . _hyperparam_mutat... |
def write ( self , data , report_id = 0 ) :
"""Writes data to the HID device on its endpoint .
Parameters :
data : data to send on the HID endpoint
report _ id : the report ID to use .
Returns :
The number of bytes written including the report ID .""" | if not self . _is_open :
raise HIDException ( "HIDDevice not open" )
write_data = bytearray ( [ report_id ] ) + bytearray ( data )
cdata = ffi . new ( "const unsigned char[]" , bytes ( write_data ) )
num_written = hidapi . hid_write ( self . _device , cdata , len ( write_data ) )
if num_written < 0 :
raise HIDE... |
def _merge ( listA , listB ) :
"""Merges two list of objects removing
repetitions .""" | listA = [ x . id for x in listA ]
listB = [ x . id for x in listB ]
listA . extend ( listB )
set_ = set ( listA )
return list ( set_ ) |
def check_for_upload_create ( self , relative_path = None ) :
"""Traverse the relative _ path tree and check for files that need to be uploaded / created .
Relativity here refers to the shared directory tree .""" | for f in os . listdir ( path_join ( self . local_path , relative_path ) if relative_path else self . local_path ) :
self . node_check_for_upload_create ( relative_path , f ) |
def _finalize_grid ( self , * axlabels ) :
"""Finalize the annotations and layout .""" | if not self . _finalized :
self . set_axis_labels ( * axlabels )
self . set_titles ( )
self . fig . tight_layout ( )
for ax , namedict in zip ( self . axes . flat , self . name_dicts . flat ) :
if namedict is None :
ax . set_visible ( False )
self . _finalized = True |
def remove ( cls , name ) :
"""Destroys collection .
: param name Collection name""" | api = Client . instance ( ) . api
api . collection ( name ) . delete ( ) |
def set_apps_list ( self ) :
"""gets installed apps and puts them into the available _ apps list""" | log . debug ( "getting apps and setting them in the internal app list..." )
cmd , url = DEVICE_URLS [ "get_apps_list" ]
result = self . _exec ( cmd , url )
self . available_apps = [ AppModel ( result [ app ] ) for app in result ] |
def elementwise_cdf ( self , p ) :
r"""Convert a sample to random variates uniform on : math : ` [ 0 , 1 ] ` .
For a univariate distribution , this is simply evaluating the CDF . To
facilitate efficient sampling , this function returns a * vector * of CDF
values , one value for each variable . Basically , the... | p = scipy . atleast_1d ( p )
if len ( p ) != len ( self . sigma ) :
raise ValueError ( "length of p must equal the number of parameters!" )
if p . ndim != 1 :
raise ValueError ( "p must be one-dimensional!" )
return scipy . asarray ( [ scipy . stats . lognorm . cdf ( v , s , loc = 0 , scale = em ) for v , s , e... |
def devop_read ( self , args , bustype ) :
'''read from device''' | if len ( args ) < 5 :
print ( "Usage: devop read <spi|i2c> name bus address regstart count" )
return
name = args [ 0 ]
bus = int ( args [ 1 ] , base = 0 )
address = int ( args [ 2 ] , base = 0 )
reg = int ( args [ 3 ] , base = 0 )
count = int ( args [ 4 ] , base = 0 )
self . master . mav . device_op_read_send (... |
def get_ilo_firmware_version_as_major_minor ( self ) :
"""Gets the ilo firmware version for server capabilities
Parse the get _ host _ health _ data ( ) to retreive the firmware
details .
: param data : the output returned by get _ host _ health _ data ( )
: returns : String with the format " < major > . < ... | data = self . get_host_health_data ( )
firmware_details = self . _get_firmware_embedded_health ( data )
if firmware_details :
ilo_version_str = firmware_details . get ( 'iLO' , None )
return common . get_major_minor ( ilo_version_str ) |
def zeros ( shape , dtype = None , ** kwargs ) :
"""Returns a new symbol of given shape and type , filled with zeros .
Parameters
shape : int or sequence of ints
Shape of the new array .
dtype : str or numpy . dtype , optional
The value type of the inner value , default to ` ` np . float32 ` ` .
Returns... | if dtype is None :
dtype = _numpy . float32
return _internal . _zeros ( shape = shape , dtype = dtype , ** kwargs ) |
def leaves ( self , unique = True ) :
"""Get the leaves of the tree starting at this root .""" | if not self . children :
return [ self ]
else :
res = list ( )
for child in self . children :
for sub_child in child . leaves ( unique = unique ) :
if not unique or sub_child not in res :
res . append ( sub_child )
return res |
def r_division ( onarray , offarray , rarray , mode = 'mean' ) :
"""Apply R division .
Args :
onarray ( decode . array ) : Decode array of on - point observations .
offarray ( decode . array ) : Decode array of off - point observations .
rarray ( decode . array ) : Decode array of R observations .
mode ( ... | logger = getLogger ( 'decode.models.r_division' )
logger . info ( 'mode' )
logger . info ( '{}' . format ( mode ) )
offid = np . unique ( offarray . scanid )
onid = np . unique ( onarray . scanid )
rid = np . unique ( rarray . scanid )
onarray = onarray . copy ( )
# Xarray
onvalues = onarray . values
onscanid = onarray... |
def flake ( self , message ) :
"""Print an error message to stdout .""" | self . stdout . write ( str ( message ) )
self . stdout . write ( '\n' ) |
def continue_worker ( oid , restart_point = "continue_next" , ** kwargs ) :
"""Restart workflow with given id ( uuid ) at given point .
By providing the ` ` restart _ point ` ` you can change the
point of which the workflow will continue from .
* restart _ prev : will restart from the previous task
* contin... | if 'stop_on_halt' not in kwargs :
kwargs [ 'stop_on_halt' ] = False
workflow_object = workflow_object_class . get ( oid )
workflow = Workflow . query . get ( workflow_object . id_workflow )
engine = WorkflowEngine ( workflow , ** kwargs )
engine . save ( )
db . session . commit ( )
engine . continue_object ( workfl... |
def from_sysdisk ( cls , label ) :
"""Retrieve disk id from available system disks""" | disks = cls . safe_call ( 'hosting.disk.list' , { 'name' : label } )
if len ( disks ) :
return disks [ 0 ] [ 'id' ] |
def _tree_line ( self , no_type : bool = False ) -> str :
"""Return the receiver ' s contribution to tree diagram .""" | return self . _tree_line_prefix ( ) + " " + self . iname ( ) |
def _login ( self , username = "" , password = "" ) :
"""Login to the Server using username / password ,
empty parameters means an anonymously login
Returns True if login sucessful , and False if not .""" | self . log . debug ( "----------------" )
self . log . debug ( "Logging in (username: %s)..." % username )
def run_query ( ) :
return self . _xmlrpc_server . LogIn ( username , password , self . language , self . user_agent )
info = self . _safe_exec ( run_query , None )
if info is None :
self . _token = None
... |
def guess_autoescape ( self , template_name ) :
"""Given a template Name I will gues using its
extension if we should autoscape or not .
Default autoscaped extensions : ( ' html ' , ' xhtml ' , ' htm ' , ' xml ' )""" | if template_name is None or '.' not in template_name :
return False
ext = template_name . rsplit ( '.' , 1 ) [ 1 ]
return ext in ( 'html' , 'xhtml' , 'htm' , 'xml' ) |
def get_column_model ( name , model = None ) :
"""get model field according to name""" | if '.' in name :
m , name = name . split ( '.' )
model = get_model ( m )
if model :
return model . c . get ( name ) , model
else :
return None , None |
def AREA ( a , b ) :
"""area : Sort pack by area""" | return cmp ( b [ 0 ] * b [ 1 ] , a [ 0 ] * a [ 1 ] ) or cmp ( b [ 1 ] , a [ 1 ] ) or cmp ( b [ 0 ] , a [ 0 ] ) |
def set_cn_energies ( self , cn_energies ) :
"""Set the coordination number dependent energies for this lattice .
Args :
cn _ energies ( Dict ( Str : Dict ( Int : Float ) ) ) : Dictionary of dictionaries specifying the coordination number dependent energies for each site type . e . g . : :
{ ' A ' : { 0 : 0.0... | for site in self . sites :
site . set_cn_occupation_energies ( cn_energies [ site . label ] )
self . cn_energies = cn_energies |
def add_epoch ( self , epoch_name , start_frame , end_frame ) :
'''This function adds an epoch to your recording extractor that tracks
a certain time period in your recording . It is stored in an internal
dictionary of start and end frame tuples .
Parameters
epoch _ name : str
The name of the epoch to be ... | # Default implementation only allows for frame info . Can override to put more info
if isinstance ( epoch_name , str ) :
self . _epochs [ epoch_name ] = { 'start_frame' : int ( start_frame ) , 'end_frame' : int ( end_frame ) }
else :
raise ValueError ( "epoch_name must be a string" ) |
def save_to_file_object ( self , fd , format = None , ** kwargs ) :
"""Save the object to a given file like object in the given format .""" | format = 'pickle' if format is None else format
save = getattr ( self , "save_%s" % format , None )
if save is None :
raise ValueError ( "Unknown format '%s'." % format )
save ( fd , ** kwargs ) |
def _generate_dockerfile ( base_image , layers ) :
"""Generate the Dockerfile contents
A generated Dockerfile will look like the following :
FROM lambci / lambda : python3.6
ADD - - chown = sbx _ user1051:495 layer1 / opt
ADD - - chown = sbx _ user1051:495 layer2 / opt
Parameters
base _ image str
Base... | dockerfile_content = "FROM {}\n" . format ( base_image )
for layer in layers :
dockerfile_content = dockerfile_content + "ADD --chown=sbx_user1051:495 {} {}\n" . format ( layer . name , LambdaImage . _LAYERS_DIR )
return dockerfile_content |
def dispatch ( self , request , * args , ** kwargs ) :
"""Most views in a CMS require a login , so this is the default setup .
If a login is not required then the requires _ login property
can be set to False to disable this .""" | if self . requires_login :
if settings . LOGIN_URL is None or settings . LOGOUT_URL is None :
raise ImproperlyConfigured ( "LOGIN_URL and LOGOUT_URL " "has to be defined if requires_login is True" )
if not request . user . is_authenticated :
return redirect ( "%s?next=%s" % ( resolve_url ( setti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.