signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def getYadisXRD ( xrd_tree ) :
"""Return the XRD element that should contain the Yadis services""" | xrd = None
# for the side - effect of assigning the last one in the list to the
# xrd variable
for xrd in xrd_tree . findall ( xrd_tag ) :
pass
# There were no elements found , or else xrd would be set to the
# last one
if xrd is None :
raise XRDSError ( 'No XRD present in tree' )
return xrd |
def hist ( self , dimension = None , num_bins = 20 , bin_range = None , adjoin = True , index = 0 , ** kwargs ) :
"""Computes and adjoins histogram along specified dimension ( s ) .
Defaults to first value dimension if present otherwise falls
back to first key dimension .
Args :
dimension : Dimension ( s ) ... | valid_ind = isinstance ( index , int ) and ( 0 <= index < len ( self ) )
valid_label = index in [ el . label for el in self ]
if not any ( [ valid_ind , valid_label ] ) :
raise TypeError ( "Please supply a suitable index or label for the histogram data" )
hists = self . get ( index ) . hist ( adjoin = False , dimen... |
def assert_free ( self , host , port = None ) :
"""Assert that the given addr is free
in that all attempts to connect fail within the timeout
or raise a PortNotFree exception .
> > > free _ port = find _ available _ local _ port ( )
> > > Checker ( ) . assert _ free ( ' localhost ' , free _ port )
> > > C... | if port is None and isinstance ( host , abc . Sequence ) :
host , port = host [ : 2 ]
if platform . system ( ) == 'Windows' :
host = client_host ( host )
info = socket . getaddrinfo ( host , port , socket . AF_UNSPEC , socket . SOCK_STREAM , )
list ( itertools . starmap ( self . _connect , info ) ) |
def anim_to_html ( anim , fps = None , embed_frames = True , default_mode = 'loop' ) :
"""Generate HTML representation of the animation""" | if fps is None and hasattr ( anim , '_interval' ) : # Convert interval in ms to frames per second
fps = 1000. / anim . _interval
plt . close ( anim . _fig )
if hasattr ( anim , "_html_representation" ) :
return anim . _html_representation
else : # tempfile can ' t be used here : we need a filename , and this
# ... |
def create_widget ( self ) :
"""Create the underlying widget .""" | d = self . declaration
if d . orientation == 'vertical' :
self . widget = ScrollView ( self . get_context ( ) , None , d . style )
else :
self . widget = HorizontalScrollView ( self . get_context ( ) , None , d . style ) |
def value ( self ) :
"""Fetch a random weighted choice""" | choice = weighted_choice ( self . _responses )
# If the choice is a tuple , join the elements into a single mapped string
if isinstance ( choice , tuple ) :
return '' . join ( map ( str , choice ) ) . strip ( )
# Otherwise , return the choice itself as a string
return str ( choice ) |
def mt_coherence ( df , xi , xj , tbp , kspec , nf , p , ** kwargs ) :
"""Construct the coherence spectrum from the yk ' s and the
weights of the usual multitaper spectrum estimation .
Note this code uses the real ( 4 ) multitaper code .
INPUT
: param df : float ; sampling rate of time series
: param xi :... | npts = len ( xi )
if len ( xj ) != npts :
raise Exception ( "Inpurt ndarrays have mismatching length" )
mt = _MtspecType ( 'float32' )
# convert type of input arguments if necessary
xi = np . require ( xi , dtype = mt . float , requirements = [ mt . order ] )
xj = np . require ( xj , dtype = mt . float , requiremen... |
def make_sure_path_exists ( path ) :
"""Ensure that a directory exists .
: param path : A directory path .""" | logger . debug ( 'Making sure path exists: {}' . format ( path ) )
try :
os . makedirs ( path )
logger . debug ( 'Created directory at: {}' . format ( path ) )
except OSError as exception :
if exception . errno != errno . EEXIST :
return False
return True |
def _write_consensus_strings ( self , output ) :
'''Writes the taxonomy of each leaf to a file . If the leaf has no
taxonomy , a taxonomy string will be created using the annotations
provided to the ancestor nodes of that leaf ( meaning , it will be
decorated ) .
Parameters
output : string
File to which... | logging . info ( "Writing decorated taxonomy to file: %s" % ( output ) )
with open ( output , 'w' ) as out :
for tip in self . tree . leaf_nodes ( ) :
tax_name = tip . taxon . label . replace ( " " , "_" )
if tip . taxon . label in self . taxonomy :
tax_string = '; ' . join ( self . taxo... |
def get_persons ( self ) :
"""Returns list of strings which represents persons being chated with""" | cs = self . data [ "to" ] [ "data" ]
res = [ ]
for c in cs :
res . append ( c [ "name" ] )
return res |
def main ( self , config_filename , regex ) :
""": param str config _ filename : The config filename .
: param str regex : The regular expression for columns which we want to use .
: rtype : int""" | self . _read_configuration_file ( config_filename )
if self . _constants_filename :
self . _io . title ( 'Constants' )
self . connect ( )
self . _get_old_columns ( )
self . _get_columns ( )
self . _enhance_columns ( )
self . _merge_columns ( )
self . _write_columns ( )
self . _get_labels... |
def _unwrap_result ( action , result ) :
"""Unwrap a request response and return only the response data .
: param str action : The action name
: param result : The result of the action
: type : result : list or dict
: rtype : dict | None""" | if not result :
return
elif action in { 'DeleteItem' , 'PutItem' , 'UpdateItem' } :
return _unwrap_delete_put_update_item ( result )
elif action == 'GetItem' :
return _unwrap_get_item ( result )
elif action == 'Query' or action == 'Scan' :
return _unwrap_query_scan ( result )
elif action == 'CreateTable... |
def search ( self ) :
r"""Call the Bugzilla endpoint that will do the search . It will take
the information used in other methods on the Search object and
build up the query string . If no bugs are found then an empty list
is returned .
> > > bugs = bugzilla . search _ for \
. . . . keywords ( " checkin -... | params = { }
params . update ( self . _time_frame . items ( ) )
if self . _includefields :
params [ 'include_fields' ] = list ( self . _includefields )
if self . _bug_numbers :
bugs = [ ]
for bug in self . _bug_numbers :
result = self . _bugsy . request ( 'bug/%s' % bug , params = params )
b... |
def set_alert_destination ( self , ip = None , acknowledge_required = None , acknowledge_timeout = None , retries = None , destination = 0 , channel = None ) :
"""Configure one or more parameters of an alert destination
If any parameter is ' None ' ( default ) , that parameter is left unchanged .
Otherwise , al... | if channel is None :
channel = self . get_network_channel ( )
if ip is not None :
destdata = bytearray ( ( channel , 19 , destination ) )
try :
parsedip = socket . inet_aton ( ip )
destdata . extend ( ( 0 , 0 ) )
destdata . extend ( parsedip )
destdata . extend ( b'\x00\x00\x... |
def normalize_example ( self , example , hparams ) :
"""Assumes that example contains both inputs and targets .""" | length = self . max_length ( hparams )
def _to_constant_shape ( tensor ) :
tensor = tensor [ : length ]
tensor = tf . pad ( tensor , [ ( 0 , length - tf . shape ( tensor ) [ 0 ] ) ] )
return tf . reshape ( tensor , [ length ] )
if self . has_inputs :
example [ 'inputs' ] = _to_constant_shape ( example [... |
def style ( self , style : _AttrValueType ) -> None :
"""Set style attribute of this node .
If argument ` ` style ` ` is string , it will be parsed to
` ` CSSStyleDeclaration ` ` .""" | if isinstance ( style , str ) :
self . __style . _parse_str ( style )
elif style is None :
self . __style . _parse_str ( '' )
elif isinstance ( style , CSSStyleDeclaration ) :
self . __style . _owner = None
if style . _owner is not None :
new_style = CSSStyleDeclaration ( owner = self )
... |
def extend_hit ( self , hit_id , number , duration_hours = None ) :
"""Extend an existing HIT and return an updated description""" | self . create_additional_assignments_for_hit ( hit_id , number )
if duration_hours is not None :
self . update_expiration_for_hit ( hit_id , duration_hours )
return self . get_hit ( hit_id ) |
def wait_run_in_executor ( func , * args , ** kwargs ) :
"""Run blocking code in a different thread and wait
for the result .
: param func : Run this function in a different thread
: param args : Parameters of the function
: param kwargs : Keyword parameters of the function
: returns : Return the result o... | loop = asyncio . get_event_loop ( )
future = loop . run_in_executor ( None , functools . partial ( func , * args , ** kwargs ) )
yield from asyncio . wait ( [ future ] )
return future . result ( ) |
def _initialize_repo_cache ( ) :
"""Initialize the repository cache used for scraping .
Retrieves a list of repositories with their provider and last scraping time
from Elasticsearch .
This list can be used to check which repos need to be scraped ( e . g . after
a specific amount of time ) .""" | LOGGER . info ( "Initializing repository cache" )
# Initialize Repo Cache
repo_cache = { }
# Get all repos from Elasticsearch
for hit in GitRepo . search ( ) . query ( "match_all" ) . scan ( ) : # TODO ( fschmidt ) : Maybe we can use this list as cache for the whole
# scraper - webhook part .
# This way , we could redu... |
def combinations ( seq , k ) :
"""Return j length subsequences of elements from the input iterable .
This version uses Numpy / Scipy and should be preferred over itertools . It avoids
the creation of all intermediate Python objects .
Examples
> > > import numpy as np
> > > from itertools import combinatio... | from itertools import combinations as _combinations , chain
from scipy . special import comb
count = comb ( len ( seq ) , k , exact = True )
res = np . fromiter ( chain . from_iterable ( _combinations ( seq , k ) ) , int , count = count * k )
return res . reshape ( - 1 , k ) |
def publishApp ( self , app_info , map_info = None , fsInfo = None ) :
"""Publishes apps to AGOL / Portal
Args :
app _ info ( list ) : A list of JSON configuration apps to publish .
map _ info ( list ) : Defaults to ` ` None ` ` .
fsInfo ( list ) : Defaults to ` ` None ` ` .
Returns :
dict : A dictionar... | if self . securityhandler is None :
print ( "Security handler required" )
return
appDet = None
try :
app_results = [ ]
if isinstance ( app_info , list ) :
for appDet in app_info :
app_results . append ( self . _publishAppLogic ( appDet = appDet , map_info = map_info , fsInfo = fsInfo... |
def recent ( category = None , pages = 1 , sort = None , order = None ) :
"""Return most recently added torrents . Can be sorted and categorized
and contain multiple pages .""" | s = Search ( )
s . recent ( category , pages , sort , order )
return s |
def corners ( self , order = 'C' ) :
"""Return the corner points as a single array .
Parameters
order : { ' C ' , ' F ' } , optional
Ordering of the axes in which the corners appear in
the output . ` ` ' C ' ` ` means that the first axis varies slowest
and the last one fastest , vice versa in ` ` ' F ' ` ... | from odl . discr . grid import RectGrid
minmax_vecs = [ 0 ] * self . ndim
for axis in np . where ( ~ self . nondegen_byaxis ) [ 0 ] :
minmax_vecs [ axis ] = self . min_pt [ axis ]
for axis in np . where ( self . nondegen_byaxis ) [ 0 ] :
minmax_vecs [ axis ] = ( self . min_pt [ axis ] , self . max_pt [ axis ] )... |
def _bnd ( self , xloc , left , right , cache ) :
"""Distribution bounds .
Example :
> > > print ( chaospy . Uniform ( ) . range ( [ - 2 , 0 , 2 , 4 ] ) )
[ [ 0 . 0 . 0 . 0 . ]
[1 . 1 . 1 . 1 . ] ]
> > > print ( chaospy . Add ( chaospy . Uniform ( ) , 2 ) . range ( [ - 2 , 0 , 2 , 4 ] ) )
[ [ 2 . 2 . 2 ... | left = evaluation . get_forward_cache ( left , cache )
right = evaluation . get_forward_cache ( right , cache )
if isinstance ( left , Dist ) :
if isinstance ( right , Dist ) :
raise evaluation . DependencyError ( "under-defined distribution {} or {}" . format ( left , right ) )
elif not isinstance ( right ... |
def aDiffCytoscape ( df , aging_genes , target , species = "caenorhabditis elegans" , limit = None , cutoff = 0.4 , taxon = None , host = cytoscape_host , port = cytoscape_port ) :
"""Plots tables from aDiff / cuffdiff into cytoscape using String protein queries .
Uses top changed genes as well as first neighbour... | # # # # # TEMPORARY FIX - STRING APP NOT ACCEPTING QUERIES ABOVE 2000 GENES # # # #
df = df . sort_values ( by = [ "q_value" ] , ascending = True )
df . reset_index ( inplace = True , drop = True )
tmp = df [ : 1999 ]
df = tmp . copy ( )
# # # # # END OF TEMPORARY FIX # # # # #
query_genes = df [ "ensembl_gene_id" ] . ... |
def image_shift ( xshift = 0 , yshift = 0 , axes = "gca" ) :
"""This will shift an image to a new location on x and y .""" | if axes == "gca" :
axes = _pylab . gca ( )
e = axes . images [ 0 ] . get_extent ( )
e [ 0 ] = e [ 0 ] + xshift
e [ 1 ] = e [ 1 ] + xshift
e [ 2 ] = e [ 2 ] + yshift
e [ 3 ] = e [ 3 ] + yshift
axes . images [ 0 ] . set_extent ( e )
_pylab . draw ( ) |
def row_coordinates ( self , X ) :
"""Returns the row principal coordinates .
The row principal coordinates are obtained by projecting ` X ` on the right eigenvectors .""" | utils . validation . check_is_fitted ( self , 's_' )
# Extract index
index = X . index if isinstance ( X , pd . DataFrame ) else None
# Copy data
if self . copy :
X = np . copy ( X )
# Scale data
if hasattr ( self , 'scaler_' ) :
X = self . scaler_ . transform ( X )
return pd . DataFrame ( data = X . dot ( self... |
def hosted_numbers ( self ) :
""": returns : Version hosted _ numbers of preview
: rtype : twilio . rest . preview . hosted _ numbers . HostedNumbers""" | if self . _hosted_numbers is None :
self . _hosted_numbers = HostedNumbers ( self )
return self . _hosted_numbers |
def pesach_dow ( self ) :
"""Return the first day of week for Pesach .""" | jdn = conv . hdate_to_jdn ( HebrewDate ( self . hdate . year , Months . Nisan , 15 ) )
return ( jdn + 1 ) % 7 + 1 |
def run ( self ) :
"""A bit bulky atm . . .""" | self . close_connection = False
try :
while True :
self . started_response = False
self . status = ""
self . outheaders = [ ]
self . sent_headers = False
self . chunked_write = False
self . write_buffer = StringIO . StringIO ( )
self . content_length = None
... |
def run ( self ) :
"""Set up the process environment in preparation for running an Ansible
module . This monkey - patches the Ansible libraries in various places to
prevent it from trying to kill the process on completion , and to
prevent it from reading sys . stdin .
: returns :
Module result dictionary ... | self . setup ( )
if self . detach :
self . econtext . detach ( )
try :
return self . _run ( )
finally :
self . revert ( ) |
def vehicle_registration_code ( self , locale : Optional [ str ] = None ) -> str :
"""Get vehicle registration code of country .
: param locale : Registration code for locale ( country ) .
: return : Vehicle registration code .""" | if locale :
return VRC_BY_LOCALES [ locale ]
return self . random . choice ( VR_CODES ) |
def get_data ( self , href = None ) :
"""Gets data from an insight with data links such as captions .
' href ' the relative href to the data . May not be None .
Returns the content of the data as a string .
If the response status is not 2xx , throws an APIException .""" | # Argument error checking .
assert href is not None
raw_result = self . get ( href )
if raw_result . status < 200 or raw_result . status > 202 :
raise APIException ( raw_result . status , raw_result . json )
return raw_result . json |
def label_peri_signals ( self , time_signals , label_names = [ ] , units = None , data_units = None , copy = True , pre_signal = 100.0 , post_signal = 1000.0 , ** kwargs ) :
"""creates a labeled spike data structure
time _ label _ array is list of lists ( or matrix ) , containing a timestamp in the
first column... | if self . data_format == 'empty' :
return SpikeContainer ( None , units = self . units , copy_from = self )
time_signals [ 0 ] = convert_time ( time_signals [ 0 ] , from_units = data_units , to_units = units )
spike_times = self . spike_times . convert ( 0 , units ) . matrix . copy ( )
# this is read only
new_matri... |
def set_limits ( self , low = None , high = None ) :
"""Adjusts the limits on the rows retrieved . We use low / high to set these ,
as it makes it more Pythonic to read and write . When the API query is
created , they are converted to the appropriate offset and limit values .
Any limits passed in here are app... | if high is not None :
if self . high_mark is not None :
self . high_mark = min ( self . high_mark , self . low_mark + high )
else :
self . high_mark = self . low_mark + high
if low is not None :
if self . high_mark is not None :
self . low_mark = min ( self . high_mark , self . low_m... |
def disable_servicegroup_passive_host_checks ( self , servicegroup ) :
"""Disable passive host checks for a servicegroup
Format of the line that triggers function call : :
DISABLE _ SERVICEGROUP _ PASSIVE _ HOST _ CHECKS ; < servicegroup _ name >
: param servicegroup : servicegroup to disable
: type service... | for service_id in servicegroup . get_services ( ) :
if service_id in self . daemon . services :
host_id = self . daemon . services [ service_id ] . host
self . disable_passive_host_checks ( self . daemon . hosts [ host_id ] ) |
def paintEvent ( self , event ) :
"""Paints the widget based on its values
: param event | < QPaintEvent >""" | with XPainter ( self ) as painter :
count = self . maximum ( ) - self . minimum ( )
value = self . value ( )
w = self . pixmapSize ( ) . width ( )
h = self . pixmapSize ( ) . height ( )
x = 2
y = ( self . height ( ) - h ) / 2
delta_x = ( self . width ( ) - 4 - ( w * count - 1 ) ) / ( count -... |
def instruction_path ( cls , project , instruction ) :
"""Return a fully - qualified instruction string .""" | return google . api_core . path_template . expand ( "projects/{project}/instructions/{instruction}" , project = project , instruction = instruction , ) |
def compare_config ( self , target , init = True , indent_level = 0 ) :
"""This method will return all the necessary commands to get from the config we are in to the target
config .
Args :
* * * target * * ( : class : ` ~ pyFG . forticonfig . FortiConfig ` ) - Target config .
* * * init * * ( bool ) - This ... | if init :
fwd = self . full_path_fwd
bwd = self . full_path_bwd
else :
fwd = self . rel_path_fwd
bwd = self . rel_path_bwd
indent = 4 * indent_level * ' '
if indent_level == 0 and self . vdom is not None :
if self . vdom == 'global' :
pre = 'conf global\n'
else :
pre = 'conf vdom... |
def draw ( self ) :
"""Draws the Text in the window .""" | if not self . visible :
return
# If this input text has focus , draw an outline around the text image
if self . focus :
pygame . draw . rect ( self . window , self . focusColor , self . focusedImageRect , 1 )
# Blit in the image of text ( set earlier in _ updateImage )
self . window . blit ( self . textImage , ... |
def get_bit_series ( self , bits = None ) :
"""Get the ` StateTimeSeries ` for each bit of this ` StateVector ` .
Parameters
bits : ` list ` , optional
a list of bit indices or bit names , defaults to all bits
Returns
bitseries : ` StateTimeSeriesDict `
a ` dict ` of ` StateTimeSeries ` , one for each g... | if bits is None :
bits = [ b for b in self . bits if b not in { None , '' } ]
bindex = [ ]
for bit in bits :
try :
bindex . append ( ( self . bits . index ( bit ) , bit ) )
except ( IndexError , ValueError ) as exc :
exc . args = ( 'Bit %r not found in StateVector' % bit , )
raise
se... |
def mutate ( self , p_mutate ) :
"""Check each element for mutation , swapping " 0 " for " 1 " and vice - versa .""" | new_dna = [ ]
for bit in self . dna :
if random . random ( ) < p_mutate :
bit = '1' if bit == '0' else '0'
new_dna . append ( bit )
self . dna = '' . join ( new_dna ) |
def all_files ( file_or_directory ) :
'return all files under file _ or _ directory .' | if os . path . isdir ( file_or_directory ) :
return [ os . path . join ( dirname , filename ) for dirname , dirnames , filenames in os . walk ( file_or_directory ) for filename in filenames ]
else :
return [ file_or_directory ] |
def main ( ) :
"""main .""" | parser = create_parser ( )
args = parser . parse_args ( )
if hasattr ( args , 'handler' ) :
args . handler ( args )
else :
parser . print_help ( ) |
def cp ( src , dst ) :
"""Copy a file or directory .
If source is a directory , this recursively copies the directory
and its contents . If the destination is a directory , then this
creates a copy of the source in the destination directory with the
same basename .
If the destination already exists , this... | if isdir ( src ) : # Overwrite an existing directory .
if isdir ( dst ) :
rm ( dst )
shutil . copytree ( src , dst )
elif isfile ( src ) :
shutil . copy ( src , dst )
else :
raise IOError ( "Source '{0}' not found" . format ( src ) ) |
def service_changed ( self , event ) :
"""Called by Pelix when an events changes""" | kind = event . get_kind ( )
reference = event . get_service_reference ( )
if kind in ( pelix . ServiceEvent . REGISTERED , pelix . ServiceEvent . MODIFIED ) : # A service matches our filter
self . set_shell ( reference )
else :
with self . _lock : # Service is not matching our filter anymore
self . clea... |
def loss ( logits , labels ) :
"""Calculates the loss from the logits and the labels .
Args :
logits : Logits tensor , float - [ batch _ size , NUM _ CLASSES ] .
labels : Labels tensor , int32 - [ batch _ size ] .
Returns :
loss : Loss tensor of type float .""" | labels = tf . to_int64 ( labels )
cross_entropy = tf . nn . sparse_softmax_cross_entropy_with_logits ( logits = logits , labels = labels , name = 'xentropy' )
return tf . reduce_mean ( cross_entropy , name = 'xentropy_mean' ) |
def calc_qjoints_v1 ( self ) :
"""Apply the routing equation .
Required derived parameters :
| NmbSegments |
| C1 |
| C2 |
| C3 |
Updated state sequence :
| QJoints |
Basic equation :
: math : ` Q _ { space + 1 , time + 1 } =
c1 \\ cdot Q _ { space , time + 1 } +
c2 \\ cdot Q _ { space , time ... | der = self . parameters . derived . fastaccess
new = self . sequences . states . fastaccess_new
old = self . sequences . states . fastaccess_old
for j in range ( der . nmbsegments ) :
new . qjoints [ j + 1 ] = ( der . c1 * new . qjoints [ j ] + der . c2 * old . qjoints [ j ] + der . c3 * old . qjoints [ j + 1 ] ) |
def finalize_sv ( orig_vcf , data , items ) :
"""Finalize structural variants , adding effects and splitting if needed .""" | paired = vcfutils . get_paired ( items )
# For paired / somatic , attach combined calls to tumor sample
if paired :
sample_vcf = orig_vcf if paired . tumor_name == dd . get_sample_name ( data ) else None
else :
sample_vcf = "%s-%s.vcf.gz" % ( utils . splitext_plus ( orig_vcf ) [ 0 ] , dd . get_sample_name ( dat... |
def find_data_files ( self , package , src_dir ) :
"""Return filenames for package ' s data files in ' src _ dir '""" | patterns = self . _get_platform_patterns ( self . package_data , package , src_dir , )
globs_expanded = map ( glob , patterns )
# flatten the expanded globs into an iterable of matches
globs_matches = itertools . chain . from_iterable ( globs_expanded )
glob_files = filter ( os . path . isfile , globs_matches )
files =... |
def _toggle_monitoring ( self , action , no_ssh = False ) :
"""Enable or disable monitoring on a machine
: param action : Can be either " enable " or " disable " """ | payload = { 'action' : action , 'name' : self . name , 'no_ssh' : no_ssh , 'public_ips' : self . info [ 'public_ips' ] , 'dns_name' : self . info [ 'extra' ] . get ( 'dns_name' , 'n/a' ) }
data = json . dumps ( payload )
req = self . request ( self . mist_client . uri + "/clouds/" + self . cloud . id + "/machines/" + s... |
def get_mean_and_stddevs ( self , sites , rup , dists , imt , stddev_types ) :
"""See : meth : ` superclass method
< . base . GroundShakingIntensityModel . get _ mean _ and _ stddevs > `
for spec of input and result values .""" | assert all ( stddev_type in self . DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types )
C = self . COEFFS [ imt ]
mean = ( self . _get_magnitude_scaling ( C , rup . mag ) + self . _get_distance_scaling ( C , rup . mag , dists . rhypo ) )
if imt . name in "SA PGA" :
mean = np . log ( np . exp ( mea... |
def com ( self , center1_x , center1_y , center2_x , center2_y , Fm ) :
""": return : center of mass""" | com_x = ( Fm * center1_x + center2_x ) / ( Fm + 1. )
com_y = ( Fm * center1_y + center2_y ) / ( Fm + 1. )
return com_x , com_y |
def update_comment ( self , comment_id , body ) :
"""Update a specific comment . This can be used to edit the content of an
existing comment .""" | path = '/msg/update_comment'
req = ET . Element ( 'request' )
ET . SubElement ( req , 'comment_id' ) . text = str ( int ( comment_id ) )
comment = ET . SubElement ( req , 'comment' )
ET . SubElement ( comment , 'body' ) . text = str ( body )
return self . _request ( path , req ) |
def get_activation_key ( self , user ) :
"""Generate the activation key which will be emailed to the user .""" | return signing . dumps ( obj = user . get_username ( ) , salt = REGISTRATION_SALT ) |
def fix_location_tag ( dom ) :
"""Repair the < mods : location > tag ( the XSLT template returns things related to
paper books , not electronic documents ) .""" | location = dom . match ( "mods:mods" , "mods:location" , )
# if no location tag found , there is nothing to be fixed
if not location :
return
location = first ( location )
# fix only < mods : location > containing < mods : physicalLocation > tags
if not location . find ( "mods:physicalLocation" ) :
return
url =... |
def valid ( name , maxlength = None ) :
'''Return the lowercase name if this name adheres to requirements , None
otherwise .
The requirements are :
* only alphanumeric characters or dashes
* no number at the start
* no double dashes or dashes at the start or end of the name
* no empty string
* no stri... | if not name :
return None
if maxlength is not None and len ( name ) > maxlength :
return None
name = name . lower ( )
if name . endswith ( '-' ) or name . startswith ( '-' ) or '--' in name :
return None
if name [ 0 ] in string . digits :
return None
for c in name :
if c not in string . digits + str... |
def dict_intersection ( dict1 , dict2 , combine = False , combine_op = op . add ) :
r"""Args :
dict1 ( dict ) :
dict2 ( dict ) :
combine ( bool ) : Combines keys only if the values are equal if False else
values are combined using combine _ op ( default = False )
combine _ op ( func ) : ( default = op . a... | isect_keys = set ( dict1 . keys ( ) ) . intersection ( set ( dict2 . keys ( ) ) )
if combine : # TODO : depricate this
dict_isect = { k : combine_op ( dict1 [ k ] , dict2 [ k ] ) for k in isect_keys }
else : # maintain order if possible
if isinstance ( dict1 , OrderedDict ) :
isect_keys_ = [ k for k in ... |
def get_touch_dict ( self , ind = None , out = bool ) :
"""Get a dictionnary of Cls _ Name struct with indices of Rays touching
Only includes Struct object with compute = True
( as returned by self . lStruct _ _ computeInOut _ computeInOut )
Also return the associated colors
If in is not None , the indices ... | if self . config is None :
msg = "Config must be set in order to get touch dict !"
raise Exception ( msg )
dElt = { }
ind = self . _check_indch ( ind , out = bool )
for ss in self . lStruct_computeInOut :
kn = "%s_%s" % ( ss . __class__ . __name__ , ss . Id . Name )
indtouch = self . select ( touch = kn... |
def build_damage_array ( data , damage_dt ) :
""": param data : an array of shape ( A , L , 1 , D ) or ( A , L , 2 , D )
: param damage _ dt : a damage composite data type loss _ type - > states
: returns : a composite array of length N and dtype damage _ dt""" | A , L , MS , D = data . shape
dmg = numpy . zeros ( A , damage_dt )
for a in range ( A ) :
for l , lt in enumerate ( damage_dt . names ) :
std = any ( f for f in damage_dt [ lt ] . names if f . endswith ( '_stdv' ) )
if MS == 1 or not std : # there is only the mean value
dmg [ lt ] [ a ]... |
def warn ( message , category = None , stacklevel = 1 , emitstacklevel = 1 ) :
"""Issue a warning , or maybe ignore it or raise an exception .
Duplicate of the standard library warn function except it takes the
following argument :
` emitstacklevel ` : default to 1 , number of stackframe to consider when
ma... | # Check if message is already a Warning object
# # # Get category # # #
if isinstance ( message , Warning ) :
category = message . __class__
# Check category argument
if category is None :
category = UserWarning
if not ( isinstance ( category , type ) and issubclass ( category , Warning ) ) :
raise TypeErro... |
def find_file ( path , saltenv = 'base' , ** kwargs ) :
'''Search the environment for the relative path''' | fnd = { 'path' : '' , 'rel' : '' }
for container in __opts__ . get ( 'azurefs' , [ ] ) :
if container . get ( 'saltenv' , 'base' ) != saltenv :
continue
full = os . path . join ( _get_container_path ( container ) , path )
if os . path . isfile ( full ) and not salt . fileserver . is_file_ignored ( _... |
def execute_request ( self , url , http_method , query_params , post_data ) :
"""Makes a request to the specified url endpoint with the
specified http method , params and post data .
Args :
url ( string ) : The url to the API without query params .
Example : " https : / / api . housecanary . com / v2 / prop... | response = requests . request ( http_method , url , params = query_params , auth = self . _auth , json = post_data , headers = { 'User-Agent' : USER_AGENT } )
if isinstance ( self . _output_generator , str ) and self . _output_generator . lower ( ) == "json" : # shortcut for just getting json back
return response .... |
def upload_to_cache_server ( fpath ) :
"""Uploads . torrent file to a cache server .
Returns upload file URL .
: rtype : str""" | url_base = 'http://torrage.info'
url_upload = '%s/autoupload.php' % url_base
url_download = '%s/torrent.php?h=' % url_base
file_field = 'torrent'
try :
import requests
response = requests . post ( url_upload , files = { file_field : open ( fpath , 'rb' ) } , timeout = REMOTE_TIMEOUT )
response . raise_for_s... |
def clear_option_value ( self , opt_name ) :
"""Clear the stored option value ( so the default will be used )
: param opt _ name : option name
: type opt _ name : str""" | if not self . has_option ( opt_name ) :
raise ValueError ( "Unknow option name (%s)" % opt_name )
self . _options [ opt_name ] . clear ( ) |
def fromcols ( selection , n_sessions , eqdata , ** kwargs ) :
"""Generate features from selected columns of a dataframe .
Parameters
selection : list or tuple of str
Columns to be used as features .
n _ sessions : int
Number of sessions over which to create features .
eqdata : DataFrame
Data from whi... | _constfeat = kwargs . get ( 'constfeat' , True )
_outcols = [ 'Constant' ] if _constfeat else [ ]
_n_rows = len ( eqdata . index )
for _col in selection :
_outcols += map ( partial ( _concat , strval = ' ' + _col ) , range ( - n_sessions + 1 , 1 ) )
_features = pd . DataFrame ( index = eqdata . index [ n_sessions -... |
def collect_plugins ( self , modules = None ) :
"""Collects all the plugins from ` modules ` .
If modules is None , collects the plugins from the loaded modules .
All plugins are passed through the module filters , if any are any ,
and returned as a list .""" | if modules is None :
modules = self . get_loaded_modules ( )
else :
modules = util . return_list ( modules )
plugins = [ ]
for module in modules :
module_plugins = [ ( item [ 1 ] , item [ 0 ] ) for item in inspect . getmembers ( module ) if item [ 1 ] and item [ 0 ] != '__builtins__' ]
module_plugins , ... |
def set_ssl_logging ( self , enable = False , func = _ssl_logging_cb ) :
u'''Enable or disable SSL logging
: param True | False enable : Enable or disable SSL logging
: param func : Callback function for logging''' | if enable :
SSL_CTX_set_info_callback ( self . _ctx , func )
else :
SSL_CTX_set_info_callback ( self . _ctx , 0 ) |
def overlay_gateway_access_lists_ipv6_out_ipv6_acl_out_name ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
overlay_gateway = ET . SubElement ( config , "overlay-gateway" , xmlns = "urn:brocade.com:mgmt:brocade-tunnels" )
name_key = ET . SubElement ( overlay_gateway , "name" )
name_key . text = kwargs . pop ( 'name' )
access_lists = ET . SubElement ( overlay_gateway , "access-lists" )
ipv6 ... |
def lookup_hash_prefix ( self , cues ) :
"""Lookup hash prefixes by cue ( first 4 bytes of hash )
Returns a tuple of ( value , negative _ cache _ expired ) .""" | q = '''SELECT value, MAX(negative_expires_at < current_timestamp) AS negative_cache_expired
FROM hash_prefix WHERE cue IN ({}) GROUP BY 1
'''
output = [ ]
with self . get_cursor ( ) as dbc :
dbc . execute ( q . format ( ',' . join ( [ '?' ] * len ( cues ) ) ) , [ sqlite3 . Binary ( cue ) for... |
def required_attributes ( element , * attributes ) :
"""Check element for required attributes . Raise ` ` NotValidXmlException ` ` on error .
: param element : ElementTree element
: param attributes : list of attributes names to check
: raises NotValidXmlException : if some argument is missing""" | if not reduce ( lambda still_valid , param : still_valid and param in element . attrib , attributes , True ) :
raise NotValidXmlException ( msg_err_missing_attributes ( element . tag , * attributes ) ) |
def search ( self ) :
"""Search for a url by returning the value from the first callback that
returns a non - None value""" | for cb in SearchUrl . search_callbacks :
try :
v = cb ( self )
if v is not None :
return v
except Exception as e :
raise |
def create_contact ( self , * args , ** kwargs ) :
"""Creates a contact""" | url = 'contacts'
data = { 'view_all_tickets' : False , 'description' : 'Freshdesk Contact' }
data . update ( kwargs )
return Contact ( ** self . _api . _post ( url , data = json . dumps ( data ) ) ) |
def validate ( self , payload , required = None , strict = None ) :
'''Validates a given JSON payload according to the rules defiined for all
the fields / keys in the sub - class .
: param dict payload : deserialized JSON object .
: param bool required : if every field / key is required and must be
present ... | # replace datatypes . Function . func if not already replaced
self . _replace_string_args ( )
required = required if required is not None else self . required
strict = strict if strict is not None else self . strict
errors = PayloadErrors ( )
fields = copy . deepcopy ( list ( self . _fields ) )
for key , value in iteri... |
def similarity ( w1 , w2 , threshold = 0.5 ) :
"""compare two strings ' words ' , and
return ratio of smiliarity , be it larger than the threshold ,
or 0 otherwise .
NOTE : if the result more like junk , increase the threshold value .""" | ratio = SM ( None , str ( w1 ) . lower ( ) , str ( w2 ) . lower ( ) ) . ratio ( )
return ratio if ratio > threshold else 0 |
def poll ( self , force_rescan = False ) :
"""A generator producing ( path , line ) tuples with lines seen since the last time poll ( ) was called . Will not block . Checks for new / deleted / rotated files every ` interval ` seconds , but will check every time if ` force _ rescan ` is True . ( default False )""" | # Check for new , deleted , and rotated files .
if force_rescan or time . time ( ) > self . _last_scan + self . _interval :
self . _rescan ( skip_to_end = False )
self . _last_scan = time . time ( )
filereaders = { }
for path , tailedfile in self . _tailedfiles . iteritems ( ) :
filereaders [ path ] = taile... |
def collect ( self ) :
"""Yields metrics from the collectors in the registry .""" | collectors = None
with self . _lock :
collectors = copy . copy ( self . _collector_to_names )
for collector in collectors :
for metric in collector . collect ( ) :
yield metric |
def _find_image_bounding_boxes ( filenames , image_to_bboxes ) :
"""Find the bounding boxes for a given image file .
Args :
filenames : list of strings ; each string is a path to an image file .
image _ to _ bboxes : dictionary mapping image file names to a list of
bounding boxes . This list contains 0 + bo... | num_image_bbox = 0
bboxes = [ ]
for f in filenames :
basename = os . path . basename ( f )
if basename in image_to_bboxes :
bboxes . append ( image_to_bboxes [ basename ] )
num_image_bbox += 1
else :
bboxes . append ( [ ] )
print ( 'Found %d images with bboxes out of %d images' % ( n... |
async def parse_get_cred_def_response ( get_cred_def_response : str ) -> ( str , str ) :
"""Parse a GET _ CRED _ DEF response to get Credential Definition in the format compatible with Anoncreds API .
: param get _ cred _ def _ response : response of GET _ CRED _ DEF request .
: return : Credential Definition I... | logger = logging . getLogger ( __name__ )
logger . debug ( "parse_get_cred_def_response: >>> get_cred_def_response: %r" , get_cred_def_response )
if not hasattr ( parse_get_cred_def_response , "cb" ) :
logger . debug ( "parse_get_cred_def_response: Creating callback" )
parse_get_cred_def_response . cb = create_... |
def logsumexp ( tensor : torch . Tensor , dim : int = - 1 , keepdim : bool = False ) -> torch . Tensor :
"""A numerically stable computation of logsumexp . This is mathematically equivalent to
` tensor . exp ( ) . sum ( dim , keep = keepdim ) . log ( ) ` . This function is typically used for summing log
probabi... | max_score , _ = tensor . max ( dim , keepdim = keepdim )
if keepdim :
stable_vec = tensor - max_score
else :
stable_vec = tensor - max_score . unsqueeze ( dim )
return max_score + ( stable_vec . exp ( ) . sum ( dim , keepdim = keepdim ) ) . log ( ) |
def create_from_row ( cls , table_row ) :
"""Build and return a ` FileHandle ` from an ` astropy . table . row . Row `""" | kwargs = { }
for key in table_row . colnames :
kwargs [ key ] = table_row [ key ]
try :
return cls ( ** kwargs )
except KeyError :
print ( kwargs ) |
def _pull_player_data ( self ) :
"""Pull and aggregate all player information .
Pull the player ' s HTML stats page and parse unique properties , such as
the player ' s height , weight , and name . Next , combine all stats for all
seasons plus the player ' s career stats into a single object which can
easil... | player_info = self . _retrieve_html_page ( )
if not player_info :
return
self . _parse_player_information ( player_info )
all_stats = self . _combine_all_stats ( player_info )
setattr ( self , '_season' , list ( all_stats . keys ( ) ) )
return all_stats |
def on ( self , method , path = None , headers = None , text = None , json = None ) :
'''Sends response to matching parameters one time and removes it from list of expectations
: type method : str
: param method : request method : ` ` ' GET ' ` ` , ` ` ' POST ' ` ` , etc . can be some custom string
: type pat... | rule = Rule ( method , path , headers , text , json )
return self . _add_rule_to ( rule , self . _rules ) |
async def input ( dev : Device , input , output ) :
"""Get and change outputs .""" | inputs = await dev . get_inputs ( )
if input :
click . echo ( "Activating %s" % input )
try :
input = next ( ( x for x in inputs if x . title == input ) )
except StopIteration :
click . echo ( "Unable to find input %s" % input )
return
zone = None
if output :
zone = a... |
def move_entry ( self , entry = None , group = None ) :
"""Move an entry to another group .
A v1Group group and a v1Entry entry are needed .""" | if entry is None or group is None or type ( entry ) is not v1Entry or type ( group ) is not v1Group :
raise KPError ( "Need an entry and a group." )
elif entry not in self . entries :
raise KPError ( "No entry found." )
elif group in self . groups :
entry . group . entries . remove ( entry )
group . ent... |
def resource_from_etree ( self , etree , resource_class ) :
"""Construct a Resource from an etree .
Parameters :
etree - the etree to parse
resource _ class - class of Resource object to create
The parsing is properly namespace aware but we search just
for the elements wanted and leave everything else alo... | loc_elements = etree . findall ( '{' + SITEMAP_NS + "}loc" )
if ( len ( loc_elements ) > 1 ) :
raise SitemapParseError ( "Multiple <loc> elements while parsing <url> in sitemap" )
elif ( len ( loc_elements ) == 0 ) :
raise SitemapParseError ( "Missing <loc> element while parsing <url> in sitemap" )
else :
l... |
def get_to_purge_archived_resources ( user , table ) :
"""List the entries to be purged from the database .""" | if user . is_not_super_admin ( ) :
raise dci_exc . Unauthorized ( )
archived_resources = get_archived_resources ( table )
return flask . jsonify ( { table . name : archived_resources , '_meta' : { 'count' : len ( archived_resources ) } } ) |
def verify_from_file ( self , data_path , sig_path = None , keyrings = None , homedir = None ) :
'''` data _ path ` < string > The path to the data to verify .
` sig _ path ` < string > The signature file , if detached from the data .
` keyrings ` < list of string > Additional keyrings to search in .
` homedi... | cmd_line = [ 'gpg' , '--homedir' , homedir or self . homedir ]
cmd_line . extend ( self . _get_keyrings_cl ( keyrings ) )
cmd_line . append ( '--verify' )
if sig_path :
cmd_line . extend ( [ sig_path , data_path ] )
else :
cmd_line . append ( data_path )
p = subprocess . Popen ( cmd_line , stderr = subprocess .... |
def get_child_value ( parent , name , allow_missing = 0 ) :
"""return the value of the child element with name in the parent Element""" | if not parent . HasElement ( name ) :
if allow_missing :
return np . nan
else :
raise Exception ( 'failed to find child element %s in parent' % name )
else :
return XmlHelper . as_value ( parent . GetElement ( name ) ) |
def resolve_from_dictionary ( dictionary , key_list , default_value = None ) :
"""Take value from a given key list from dictionary .
Example : given dictionary d , key _ list = [ ' foo ' , ' bar ' ] ,
it will try to resolve d [ ' foo ' ] [ ' bar ' ] . If not possible ,
return default _ value .
: param dicti... | try :
current_value = dictionary
key_list = key_list if isinstance ( key_list , list ) else [ key_list ]
for key in key_list :
current_value = current_value [ key ]
return current_value
except KeyError :
return default_value |
def _pushdate_urls ( cls , pushdate , branch , target_platform ) :
"""Multiple entries exist per push date . Iterate over all until a working entry is found""" | url_base = cls . URL_BASE + '/namespaces/gecko.v2.mozilla-' + branch + '.pushdate.' + pushdate
try :
base = HTTP_SESSION . post ( url_base , json = { } )
base . raise_for_status ( )
except requests . exceptions . RequestException as exc :
raise FetcherException ( exc )
product = 'mobile' if 'android' in tar... |
def _init_metadata ( self ) :
"""stub""" | TextAnswerFormRecord . _init_metadata ( self )
FilesAnswerFormRecord . _init_metadata ( self )
super ( AnswerTextAndFilesMixin , self ) . _init_metadata ( ) |
def read ( self , ulBuffer , pDst , unBytes ) :
"""reads up to unBytes from buffer into * pDst , returning number of bytes read in * punRead""" | fn = self . function_table . read
punRead = c_uint32 ( )
result = fn ( ulBuffer , pDst , unBytes , byref ( punRead ) )
return result , punRead . value |
def _Parse ( self ) :
"""Extracts attributes and extents from the volume .""" | tsk_vs_part = self . _file_entry . GetTSKVsPart ( )
tsk_addr = getattr ( tsk_vs_part , 'addr' , None )
if tsk_addr is not None :
address = volume_system . VolumeAttribute ( 'address' , tsk_addr )
self . _AddAttribute ( address )
tsk_desc = getattr ( tsk_vs_part , 'desc' , None )
if tsk_desc is not None : # pyts... |
def _use_widgets ( objs ) :
'''Whether a collection of Bokeh objects contains a any Widget
Args :
objs ( seq [ Model or Document ] ) :
Returns :
bool''' | from . . models . widgets import Widget
return _any ( objs , lambda obj : isinstance ( obj , Widget ) ) |
def replace ( self , expression , replacements ) :
"""All purpose method to reduce an expression by applying
successive replacement rules .
` expression ` is either a SymPy expression
or a key in ` scipy _ data _ fitting . Model . expressions ` .
` replacements ` can be any of the following ,
or a list of... | # When expression is a string ,
# get the expressions from self . expressions .
if isinstance ( expression , str ) :
expression = self . expressions [ expression ]
# Allow for replacements to be empty .
if not replacements :
return expression
# Allow replacements to be a string .
if isinstance ( replacements , ... |
def _create_threads ( self ) :
"""This method creates job instances .""" | creator = JobCreator ( self . config , self . observers . jobs , self . logger )
self . jobs = creator . job_factory ( ) |
def intuition ( args ) :
'''Main simulation wrapper
Load the configuration , run the engine and return the analyze .''' | # Use the provided context builder to fill :
# - config : General behavior
# - strategy : Modules properties
# - market : The universe we will trade on
with setup . Context ( args [ 'context' ] ) as context : # Backtest or live engine .
# Registers configuration and setups data client
simulation = Simulation ( )
... |
def start ( self ) :
"""Start the connection to a transport .""" | self . _init_topics ( )
poll_thread = threading . Thread ( target = self . _poll_queue )
poll_thread . start ( ) |
def persistent_object_context_changed ( self ) :
"""Override from PersistentObject .""" | super ( ) . persistent_object_context_changed ( )
def source_registered ( source ) :
self . __source = source
def source_unregistered ( source = None ) :
pass
def reference_registered ( property_name , reference ) :
self . __referenced_objects [ property_name ] = reference
def reference_unregistered ( prope... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.