signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def list_plugins ( ) :
"""Return list of all plugin classes registered as a list of tuples :
[ ( name , plugin _ class ) ]""" | plugin_eps = pkg_resources . iter_entry_points ( 'ofxstatement' )
return sorted ( ( ep . name , ep . load ( ) ) for ep in plugin_eps ) |
def output ( self , _filename ) :
"""_ filename is not used
Args :
_ filename ( string )""" | for contract in self . slither . contracts_derived :
txt = "\nContract %s" % contract . name
table = PrettyTable ( [ "Function" , "Modifiers" ] )
for function in contract . functions :
modifiers = function . modifiers
for call in function . all_internal_calls ( ) :
if isinstance ... |
def move ( self , direction = 0 ) :
"""direction = int range ( 0 , 4)
0 = Down
1 = Left
2 = Up
3 = Right""" | direction = int ( direction )
self . position = list ( self . position )
if direction == 0 :
self . position [ 1 ] += 1
elif direction == 1 :
self . position [ 0 ] -= 1
elif direction == 2 :
self . position [ 1 ] -= 1
elif direction == 3 :
self . position [ 0 ] += 1 |
def start ( self ) :
"""Connect websocket to SPC Web Gateway .""" | self . _websocket = AIOWSClient ( loop = self . _loop , session = self . _session , url = self . _ws_url , async_callback = self . _async_ws_handler )
self . _websocket . start ( ) |
def Get_Page ( self ) :
'''Fetches raw HTML data from the site for a given tracking _ no''' | # Simply encode the correct url as a string
url = 'https://www.aramex.com/express/track-results-multiple.aspx?ShipmentNumber='
url += self . tracking_no
driver = webdriver . PhantomJS ( )
# create a selenium webdriver
driver . get ( url )
# make it send a request with the above url
self . wait_till_page_load ( driver ,... |
def make_rule ( filter , * symbolizers ) :
"""Given a Filter and some symbolizers , return a Rule prepopulated
with applicable min / max scale denominator and filter .""" | scale_tests = [ test for test in filter . tests if test . isMapScaled ( ) ]
other_tests = [ test for test in filter . tests if not test . isMapScaled ( ) ]
# these will be replaced with values as necessary
minscale , maxscale , filter = None , None , None
for scale_test in scale_tests :
if scale_test . op in ( '>' ... |
def get_server_premaster_secret ( self , password_verifier , server_private , client_public , common_secret ) :
"""S = ( A * v ^ u ) ^ b % N
: param int password _ verifier :
: param int server _ private :
: param int client _ public :
: param int common _ secret :
: rtype : int""" | return pow ( ( client_public * pow ( password_verifier , common_secret , self . _prime ) ) , server_private , self . _prime ) |
def referenced_tables ( self ) :
"""Return referenced tables from job statistics , if present .
See :
https : / / cloud . google . com / bigquery / docs / reference / rest / v2 / jobs # statistics . query . referencedTables
: rtype : list of dict
: returns : mappings describing the query plan , or an empty ... | tables = [ ]
datasets_by_project_name = { }
for table in self . _job_statistics ( ) . get ( "referencedTables" , ( ) ) :
t_project = table [ "projectId" ]
ds_id = table [ "datasetId" ]
t_dataset = datasets_by_project_name . get ( ( t_project , ds_id ) )
if t_dataset is None :
t_dataset = Dataset... |
def get_context ( self , template ) :
"""Get the context for a template .
If no matching value is found , an empty context is returned .
Otherwise , this returns either the matching value if the value is
dictionary - like or the dictionary returned by calling it with
* template * if the value is a function ... | context = { }
for regex , context_generator in self . contexts :
if re . match ( regex , template . name ) :
if inspect . isfunction ( context_generator ) :
if _has_argument ( context_generator ) :
context . update ( context_generator ( template ) )
else :
... |
def has_edge ( self , edge ) :
"""Return whether an edge exists .
@ type edge : tuple
@ param edge : Edge .
@ rtype : boolean
@ return : Truth - value for edge existence .""" | u , v = edge
return ( u , v ) in self . edge_properties |
def organismsKEGG ( ) :
"""Lists all organisms present in the KEGG database .
: returns : a dataframe containing one organism per row .""" | organisms = urlopen ( "http://rest.kegg.jp/list/organism" ) . read ( )
organisms = organisms . split ( "\n" )
# for o in organisms :
# print o
# sys . stdout . flush ( )
organisms = [ s . split ( "\t" ) for s in organisms ]
organisms = pd . DataFrame ( organisms )
return organisms |
def terminal_flicker_unix ( code , field_width = 3 , space_width = 3 , height = 1 , clear = False , wait = 0.05 ) :
"""Re - encodes a flicker code and prints it on a unix terminal .
: param code : Challenge value
: param field _ width : Width of fields in characters ( default : 3 ) .
: param space _ width : W... | # Inspired by Andreas Schiermeier
# https : / / git . ccc - ffm . de / ? p = smartkram . git ; a = blob _ plain ; f = chiptan / flicker / flicker . sh ; h
# = 7066293b4e790c2c4c1f6cbdab703ed9976ffe1f ; hb = refs / heads / master
code = parse ( code ) . render ( )
data = swap_bytes ( code )
high = '\033[48;05;15m'
low =... |
def color_palette ( palette = None , n_colors = None ) :
"""Return a color palette object with color definition and handling .
Calling this function with ` ` palette = None ` ` will return the current
matplotlib color cycle .
This function can also be used in a ` ` with ` ` statement to temporarily
set the ... | if palette is None :
palette = get_color_cycle ( )
if n_colors is None :
n_colors = len ( palette )
elif not isinstance ( palette , str ) :
if n_colors is None :
n_colors = len ( palette )
else :
if palette . lower ( ) not in PALETTES :
raise YellowbrickValueError ( "'{}' is not ... |
def extract_geometry ( dataset ) :
"""Extract the outer surface of a volume or structured grid dataset as
PolyData . This will extract all 0D , 1D , and 2D cells producing the
boundary faces of the dataset .""" | alg = vtk . vtkGeometryFilter ( )
alg . SetInputDataObject ( dataset )
alg . Update ( )
return _get_output ( alg ) |
def time_slice ( self , t_from , t_to = None ) :
"""Return an new graph containing nodes and interactions present in [ t _ from , t _ to ] .
Parameters
t _ from : snapshot id , mandatory
t _ to : snapshot id , optional ( default = None )
If None t _ to will be set equal to t _ from
Returns
H : a DynGrap... | # create new graph and copy subgraph into it
H = self . __class__ ( )
if t_to is not None :
if t_to < t_from :
raise ValueError ( "Invalid range: t_to must be grater that t_from" )
else :
t_to = t_from
for u , v , ts in self . interactions_iter ( ) :
I = t_to
F = t_from
for a , b in ts [ 't'... |
def redundancy_output_rd_status ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
redundancy = ET . Element ( "redundancy" )
config = redundancy
output = ET . SubElement ( redundancy , "output" )
rd_status = ET . SubElement ( output , "rd_status" )
rd_status . text = kwargs . pop ( 'rd_status' )
callback = kwargs . pop ( 'callback' , self . _callback )
return callb... |
def enter_state ( self , request , application ) :
"""This is becoming the new current state .""" | authorised_persons = self . get_email_persons ( application )
link , is_secret = self . get_request_email_link ( application )
emails . send_request_email ( self . authorised_text , self . authorised_role , authorised_persons , application , link , is_secret ) |
def this ( func , cache_obj = CACHE_OBJ , key = None , ttl = None , * args , ** kwargs ) :
"""Store the output from the decorated function in the cache and pull it
from the cache on future invocations without rerunning .
Normally , the value will be stored under a key which takes into account
all of the param... | key = key or ( func . __name__ + str ( args ) + str ( kwargs ) )
if cache_obj . has ( key ) :
return cache_obj . get ( key )
value = func ( * args , ** kwargs )
cache_obj . upsert ( key , value , ttl )
return value |
def get_formatter ( name ) :
"""Return the named formatter function . See the function
" set _ formatter " for details .""" | if name in ( 'self' , 'instance' , 'this' ) :
return af_self
elif name == 'class' :
return af_class
elif name in ( 'named' , 'param' , 'parameter' ) :
return af_named
elif name in ( 'default' , 'optional' ) :
return af_default
# elif name in ( ' anonymous ' , ' arbitrary ' , ' unnamed ' ) :
# return af ... |
def add_interrupt_callback ( gpio_id , callback , edge = 'both' , pull_up_down = PUD_OFF , threaded_callback = False , debounce_timeout_ms = None ) :
"""Add a callback to be executed when the value on ' gpio _ id ' changes to
the edge specified via the ' edge ' parameter ( default = ' both ' ) .
` pull _ up _ d... | _rpio . add_interrupt_callback ( gpio_id , callback , edge , pull_up_down , threaded_callback , debounce_timeout_ms ) |
def list ( self , filter_args = None ) :
"""List the faked resources of this manager .
Parameters :
filter _ args ( dict ) :
Filter arguments . ` None ` causes no filtering to happen . See
: meth : ` ~ zhmcclient . BaseManager . list ( ) ` for details .
Returns :
list of FakedBaseResource : The faked re... | res = list ( )
for oid in self . _resources :
resource = self . _resources [ oid ]
if self . _matches_filters ( resource , filter_args ) :
res . append ( resource )
return res |
def write ( self , oprot ) :
'''Write this object to the given output protocol and return self .
: type oprot : thryft . protocol . _ output _ protocol . _ OutputProtocol
: rtype : pastpy . gen . database . database _ configuration . DatabaseConfiguration''' | oprot . write_struct_begin ( 'DatabaseConfiguration' )
if self . dbf is not None :
oprot . write_field_begin ( name = 'dbf' , type = 12 , id = None )
self . dbf . write ( oprot )
oprot . write_field_end ( )
if self . dummy is not None :
oprot . write_field_begin ( name = 'dummy' , type = 12 , id = None ... |
def atexit ( self ) :
"""Whether finalizer should be called at exit""" | info = self . _registry . get ( self )
return bool ( info ) and info . atexit |
def is_valid ( self ) :
"""Runs the SAM Translator to determine if the template provided is valid . This is similar to running a
ChangeSet in CloudFormation for a SAM Template
Raises
InvalidSamDocumentException
If the template is not valid , an InvalidSamDocumentException is raised""" | managed_policy_map = self . managed_policy_loader . load ( )
sam_translator = Translator ( managed_policy_map = managed_policy_map , sam_parser = self . sam_parser , plugins = [ ] )
self . _replace_local_codeuri ( )
try :
template = sam_translator . translate ( sam_template = self . sam_template , parameter_values ... |
def end_entry ( self ) :
"""Finish a previously started config database entry .
This commits the currently in progress entry . The expected flow is
that start _ entry ( ) is called followed by 1 or more calls to add _ data ( )
followed by a single call to end _ entry ( ) .
Returns :
int : An error code""" | # Matching current firmware behavior
if self . in_progress is None :
return Error . NO_ERROR
# Make sure there was actually data stored
if self . in_progress . data_space ( ) == 2 :
return Error . INPUT_BUFFER_WRONG_SIZE
# Invalidate all previous copies of this config variable so we
# can properly compact .
for... |
async def list_keys ( request : web . Request ) -> web . Response :
"""List keys in the authorized _ keys file .
GET / server / ssh _ keys
- > 200 OK { " public _ keys " : [ { " key _ md5 " : md5 hex digest , " key " : key string } ] }
( or 403 if not from the link - local connection )""" | return web . json_response ( { 'public_keys' : [ { 'key_md5' : details [ 0 ] , 'key' : details [ 1 ] } for details in get_keys ( ) ] } , status = 200 ) |
def match_tokens ( expected_tokens ) :
"""Generate a grammar function that will match ' expected _ tokens ' only .""" | if isinstance ( expected_tokens , Token ) : # Match a single token .
def _grammar_func ( tokens ) :
try :
next_token = next ( iter ( tokens ) )
except StopIteration :
return
if next_token == expected_tokens :
return TokenMatch ( None , next_token . value ,... |
def _launch_instance ( self ) :
"""Launch an instance of the given image .""" | metadata = { 'key' : 'ssh-keys' , 'value' : self . ssh_public_key }
self . running_instance_id = ipa_utils . generate_instance_name ( 'gce-ipa-test' )
self . logger . debug ( 'ID of instance: %s' % self . running_instance_id )
kwargs = { 'location' : self . region , 'ex_metadata' : metadata , 'ex_service_accounts' : [ ... |
def getfile ( self , section , option , raw = False , vars = None , fallback = "" , validate = False ) :
"""A convenience method which coerces the option in the specified section to a file .""" | v = self . get ( section , option , raw = raw , vars = vars , fallback = fallback )
v = self . _convert_to_path ( v )
return v if not validate or os . path . isfile ( v ) else fallback |
def _gather_keys_by_type ( self , type ) :
"""Gather all of the foreign keys for a given type .
: param type : The type
: type type : str
: rtype : BaseCollection""" | foreign = self . _foreign_key
keys = ( BaseCollection . make ( list ( self . _dictionary [ type ] . values ( ) ) ) . map ( lambda models : getattr ( models [ 0 ] , foreign ) ) . unique ( ) )
return keys |
def error_map ( func ) :
"""Wrap exceptions raised by requests .
. . py : decorator : : error _ map""" | @ six . wraps ( func )
def wrapper ( * args , ** kwargs ) :
try :
return func ( * args , ** kwargs )
except exceptions . RequestException as err :
raise TVDBRequestException ( err , response = getattr ( err , 'response' , None ) , request = getattr ( err , 'request' , None ) )
return wrapper |
def read_file ( filename ) :
"""Read package file as text to get name and version""" | # intentionally * not * adding an encoding option to open
# see here :
# https : / / github . com / pypa / virtualenv / issues / 201 # issuecomment - 3145690
here = os . path . abspath ( os . path . dirname ( __file__ ) )
with codecs . open ( os . path . join ( here , 'graphql_compiler' , filename ) , 'r' ) as f :
... |
def _compute_line ( source_code , start , length ) :
"""Compute line ( s ) numbers and starting / ending columns
from a start / end offset . All numbers start from 1.
Not done in an efficient way""" | total_length = len ( source_code )
source_code = source_code . splitlines ( True )
counter = 0
i = 0
lines = [ ]
starting_column = None
ending_column = None
while counter < total_length : # Determine the length of the line , and advance the line number
lineLength = len ( source_code [ i ] )
i = i + 1
# Dete... |
def parse_esmtp_extensions ( message ) :
"""Parses the response given by an ESMTP server after a * EHLO * command .
The response is parsed to build :
- A dict of supported ESMTP extensions ( with parameters , if any ) .
- A list of supported authentication methods .
Returns :
( dict , list ) : A ( extensi... | extns = { }
auths = [ ]
oldstyle_auth_regex = re . compile ( r"auth=(?P<auth>.*)" , re . IGNORECASE )
extension_regex = re . compile ( r"(?P<feature>[a-z0-9][a-z0-9\-]*) ?" , re . IGNORECASE )
lines = message . splitlines ( )
for line in lines [ 1 : ] : # To be able to communicate with as many SMTP servers as possible ... |
def check_error ( response , expect_status = 200 ) :
"""Youku error should return in json form , like :
HTTP 400
" error " : {
" code " : 120010223,
" type " : " UploadsException " ,
" description " : " Expired upload token "
But error also maybe in response url params or response booy .
Content - Typ... | json = None
try :
json = response . json ( )
except :
pass
if ( response . status_code != expect_status or response . status_code == 400 or 'error' in json ) :
if json :
error = json [ 'error' ]
raise YoukuError ( error [ 'code' ] , error [ 'type' ] , error [ 'description' ] , response . sta... |
def download_article ( id_val , id_type = 'doi' , on_retry = False ) :
"""Low level function to get an XML article for a particular id .
Parameters
id _ val : str
The value of the id .
id _ type : str
The type of id , such as pmid ( a . k . a . pubmed _ id ) , doi , or eid .
on _ retry : bool
This fun... | if id_type == 'pmid' :
id_type = 'pubmed_id'
url = '%s/%s' % ( elsevier_article_url_fmt % id_type , id_val )
params = { 'httpAccept' : 'text/xml' }
res = requests . get ( url , params , headers = ELSEVIER_KEYS )
if res . status_code == 404 :
logger . info ( "Resource for %s not available on elsevier." % url )
... |
def add_edge ( self , edgelist ) :
"""Adds an edge from network .
Parameters
edgelist : list
a list ( or list of lists ) containing the i , j and t indicies to be added . For weighted networks list should also contain a ' weight ' key .
Returns
Updates TenetoBIDS . network dataframe with new edge""" | if not isinstance ( edgelist [ 0 ] , list ) :
edgelist = [ edgelist ]
teneto . utils . check_TemporalNetwork_input ( edgelist , 'edgelist' )
if len ( edgelist [ 0 ] ) == 4 :
colnames = [ 'i' , 'j' , 't' , 'weight' ]
elif len ( edgelist [ 0 ] ) == 3 :
colnames = [ 'i' , 'j' , 't' ]
if self . hdf5 :
with ... |
def get_activity_search_session_for_objective_bank ( self , objective_bank_id = None ) :
"""Gets the OsidSession associated with the activity search service
for the given objective bank .
arg : objectiveBankId ( osid . id . Id ) : the Id of the objective
bank
return : ( osid . learning . ActivitySearchSessi... | if not objective_bank_id :
raise NullArgument
if not self . supports_activity_search ( ) :
raise Unimplemented ( )
try :
from . import sessions
except ImportError :
raise OperationFailed ( )
try :
session = sessions . ActivitySearchSession ( objective_bank_id , runtime = self . _runtime )
except Att... |
def atlas_get_all_neighbors ( peer_table = None ) :
"""Get * all * neighbor information .
USED ONLY FOR TESTING""" | if os . environ . get ( "BLOCKSTACK_ATLAS_NETWORK_SIMULATION" ) != "1" :
raise Exception ( "This method is only available when testing with the Atlas network simulator" )
ret = { }
with AtlasPeerTableLocked ( peer_table ) as ptbl :
ret = copy . deepcopy ( ptbl )
# make zonefile inventories printable
for peer_ho... |
def author ( self , value ) :
"""Setter for * * self . _ _ author * * 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 ( "author" , value )
self . __author = value |
def get_members_by_source ( base_url = BASE_URL_API ) :
"""Function returns which members have joined each activity .
: param base _ url : It is URL : ` https : / / www . openhumans . org / api / public - data ` .""" | url = '{}members-by-source/' . format ( base_url )
response = get_page ( url )
return response |
def get_blank_img ( self ) :
"""Return fake ` ` FormatedPhoto ` ` object to be used in templates when an error
occurs in image generation .""" | if photos_settings . DEBUG :
return self . get_placeholder_img ( )
out = { 'blank' : True , 'width' : self . max_width , 'height' : self . max_height , 'url' : photos_settings . EMPTY_IMAGE_SITE_PREFIX + 'img/empty/%s.png' % ( self . name ) , }
return out |
def ls ( self , multihash , ** kwargs ) :
"""Returns a list of objects linked to by the given hash .
. . code - block : : python
> > > c . ls ( ' QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D ' )
{ ' Objects ' : [
{ ' Hash ' : ' QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D ' ,
' Links ' : [
{ ' Hash ... | args = ( multihash , )
return self . _client . request ( '/ls' , args , decoder = 'json' , ** kwargs ) |
def read_seg ( self , parc_type = 'aparc' ) :
"""Read the MRI segmentation .
Parameters
parc _ type : str
' aparc ' or ' aparc . a2009s '
Returns
numpy . ndarray
3d matrix with values
numpy . ndarray
4x4 affine matrix""" | seg_file = self . dir / 'mri' / ( parc_type + '+aseg.mgz' )
seg_mri = load ( seg_file )
seg_aff = seg_mri . affine
seg_dat = seg_mri . get_data ( )
return seg_dat , seg_aff |
def interpolate_linear ( self , lons , lats , data ) :
"""Interpolate using linear approximation
Returns the same as interpolate ( lons , lats , data , order = 1)""" | return self . interpolate ( lons , lats , data , order = 1 ) |
def positions ( self ) :
"""TimeSeries of positions .""" | # if accessing and stale - update first
if self . _needupdate :
self . update ( self . root . now )
if self . root . stale :
self . root . update ( self . root . now , None )
return self . _positions . loc [ : self . now ] |
def get ( self , measurementId ) :
"""Analyses the measurement with the given parameters
: param measurementId :
: return :""" | logger . info ( 'Analysing ' + measurementId )
measurement = self . _measurementController . getMeasurement ( measurementId , MeasurementStatus . COMPLETE )
if measurement is not None :
if measurement . inflate ( ) :
data = { name : { 'spectrum' : { 'x' : self . _jsonify ( data . spectrum ( 'x' ) ) , 'y' : ... |
def GeneralGuinier ( q , G , Rg , s ) :
"""Generalized Guinier scattering
Inputs :
` ` q ` ` : independent variable
` ` G ` ` : factor
` ` Rg ` ` : radius of gyration
` ` s ` ` : dimensionality parameter ( can be 1 , 2 , 3)
Formula :
` ` G / q * * ( 3 - s ) * exp ( - ( q ^ 2 * Rg ^ 2 ) / s ) ` `""" | return G / q ** ( 3 - s ) * np . exp ( - ( q * Rg ) ** 2 / s ) |
def set_references ( self , references ) :
"""Sets references to dependent components .
: param references : references to locate the component dependencies .""" | super ( CompositeLogger , self ) . set_references ( references )
# descriptor = Descriptor ( None , " logger " , None , None , None )
loggers = references . get_optional ( Descriptor ( None , "logger" , None , None , None ) )
for logger in loggers :
if isinstance ( logger , ILogger ) :
self . _loggers . app... |
def write_rtt ( jlink ) :
"""Writes kayboard input to JLink RTT buffer # 0.
This method is a loop that blocks waiting on stdin . When enter is pressed ,
LF and NUL bytes are added to the input and transmitted as a byte list .
If the JLink is disconnected , it will exit gracefully . If any other
exceptions a... | try :
while jlink . connected ( ) :
bytes = list ( bytearray ( input ( ) , "utf-8" ) + b"\x0A\x00" )
bytes_written = jlink . rtt_write ( 0 , bytes )
except Exception :
print ( "IO write thread exception, exiting..." )
thread . interrupt_main ( )
raise |
def dots ( it , label = "" , hide = None , every = 1 ) :
"""Progress iterator . Prints a dot for each item being iterated""" | count = 0
if not hide :
STREAM . write ( label )
for i , item in enumerate ( it ) :
if not hide :
if i % every == 0 : # True every " every " updates
STREAM . write ( DOTS_CHAR )
sys . stderr . flush ( )
count += 1
yield item
STREAM . write ( "\n" )
STREAM . flush ( ) |
def get_apps ( self ) :
"""Returns a flat list of the names for the apps in
the organization .""" | apps = [ ]
for resource in self . _get_apps ( ) [ 'resources' ] :
apps . append ( resource [ 'entity' ] [ 'name' ] )
return apps |
def date_in_range ( date1 , date2 , range ) :
"""Check if two date objects are within a specific range""" | date_obj1 = convert_date ( date1 )
date_obj2 = convert_date ( date2 )
return ( date_obj2 - date_obj1 ) . days <= range |
def sort_by ( self , ordering ) :
'''Sort the query by the given field
: parameter ordering : a string indicating the class : ` Field ` name to sort by .
If prefixed with ` ` - ` ` , the sorting will be in descending order , otherwise
in ascending order .
: return type : a new : class : ` Query ` instance .... | if ordering :
ordering = self . _meta . get_sorting ( ordering , QuerySetError )
q = self . _clone ( )
q . data [ 'ordering' ] = ordering
return q |
def interval_cover ( I ) :
"""Minimum interval cover
: param I : list of closed intervals
: returns : minimum list of points covering all intervals
: complexity : O ( n log n )""" | S = [ ]
for start , end in sorted ( I , key = lambda v : v [ 1 ] ) :
if not S or S [ - 1 ] < start :
S . append ( end )
return S |
def extent_to_array ( extent , source_crs , dest_crs = None ) :
"""Convert the supplied extent to geographic and return as an array .
: param extent : Rectangle defining a spatial extent in any CRS .
: type extent : QgsRectangle
: param source _ crs : Coordinate system used for input extent .
: type source ... | if dest_crs is None :
geo_crs = QgsCoordinateReferenceSystem ( )
geo_crs . createFromSrid ( 4326 )
else :
geo_crs = dest_crs
transform = QgsCoordinateTransform ( source_crs , geo_crs , QgsProject . instance ( ) )
# Get the clip area in the layer ' s crs
transformed_extent = transform . transformBoundingBox ... |
def attr_matches ( self , text ) :
"""Compute matches when text contains a dot .
Assuming the text is of the form NAME . NAME . . . . [ NAME ] , and is
evaluatable in self . namespace or self . global _ namespace , it will be
evaluated and its attributes ( as revealed by dir ( ) ) are used as
possible compl... | import re
# Another option , seems to work great . Catches things like ' ' . < tab >
m = re . match ( r"(\S+(\.\w+)*)\.(\w*)$" , text )
# @ UndefinedVariable
if not m :
return [ ]
expr , attr = m . group ( 1 , 3 )
try :
obj = eval ( expr , self . namespace )
except :
try :
obj = eval ( expr , self .... |
def calling_convention ( self ) :
"""function calling convention . See
: class : CALLING _ CONVENTION _ TYPES class for possible values""" | if self . _calling_convention is None :
self . _calling_convention = calldef_types . CALLING_CONVENTION_TYPES . extract ( self . attributes )
if not self . _calling_convention :
self . _calling_convention = self . guess_calling_convention ( )
return self . _calling_convention |
def check ( self ) :
"""Checks the files for misspellings .
Returns :
( errors , results )
errors : List of system errors , usually file access errors .
results : List of spelling errors - each tuple is filename ,
line number and misspelled word .""" | errors = [ ]
results = [ ]
for fn in self . _files :
if not os . path . isdir ( fn ) :
try :
with open ( fn , 'r' ) as f :
line_ct = 1
for line in f :
for word in split_words ( line ) :
if ( word in self . _misspelling_d... |
def validate_dtype ( termname , dtype , missing_value ) :
"""Validate a ` dtype ` and ` missing _ value ` passed to Term . _ _ new _ _ .
Ensures that we know how to represent ` ` dtype ` ` , and that missing _ value
is specified for types without default missing values .
Returns
validated _ dtype , validate... | if dtype is NotSpecified :
raise DTypeNotSpecified ( termname = termname )
try :
dtype = dtype_class ( dtype )
except TypeError :
raise NotDType ( dtype = dtype , termname = termname )
if not can_represent_dtype ( dtype ) :
raise UnsupportedDType ( dtype = dtype , termname = termname )
if missing_value ... |
def add_object ( self , name , mesh , transform = None ) :
"""Add an object to the collision manager .
If an object with the given name is already in the manager ,
replace it .
Parameters
name : str
An identifier for the object
mesh : Trimesh object
The geometry of the collision object
transform : (... | # if no transform passed , assume identity transform
if transform is None :
transform = np . eye ( 4 )
transform = np . asanyarray ( transform , dtype = np . float32 )
if transform . shape != ( 4 , 4 ) :
raise ValueError ( 'transform must be (4,4)!' )
# create or recall from cache BVH
bvh = self . _get_BVH ( me... |
def _diff_violations ( self ) :
"""Returns a dictionary of the form :
{ SRC _ PATH : DiffViolations ( SRC _ PATH ) }
where ` SRC _ PATH ` is the path to the source file .
To make this efficient , we cache and reuse the result .""" | if not self . _diff_violations_dict :
self . _diff_violations_dict = { src_path : DiffViolations ( self . _violations . violations ( src_path ) , self . _violations . measured_lines ( src_path ) , self . _diff . lines_changed ( src_path ) , ) for src_path in self . _diff . src_paths_changed ( ) }
return self . _dif... |
def to_vobject ( self , project = None , uid = None ) :
"""Return vObject object of Taskwarrior tasks
If filename and UID are specified , the vObject only contains that task .
If only a filename is specified , the vObject contains all events in the project .
Otherwise the vObject contains all all objects of a... | self . _update ( )
vtodos = iCalendar ( )
if uid :
uid = uid . split ( '@' ) [ 0 ]
if not project :
for p in self . _tasks :
if uid in self . _tasks [ p ] :
project = p
break
self . _gen_vtodo ( self . _tasks [ basename ( project ) ] [ uid ] , vtodos . add... |
def recursive_mean ( self , mean , length , chain ) :
r"""Compute the chain mean recursively .
Instead of computing the mean : math : ` \ bar { x _ n } ` of the entire chain ,
use the last computed mean : math : ` bar { x _ j } ` and the tail of the chain
to recursively estimate the mean .
. . math : :
\ ... | n = length + len ( chain )
return length * mean / n + chain . sum ( 0 ) / n |
def set_parameter_value ( self , parameter , value ) :
"""Sets the value of the specified parameter .
: param str parameter : Either a fully - qualified XTCE name or an alias in the
format ` ` NAMESPACE / NAME ` ` .
: param value : The value to set""" | parameter = adapt_name_for_rest ( parameter )
url = '/processors/{}/{}/parameters{}' . format ( self . _instance , self . _processor , parameter )
req = _build_value_proto ( value )
self . _client . put_proto ( url , data = req . SerializeToString ( ) ) |
def _growth_curve_pooling_group ( self , distr = 'glo' , as_rural = False ) :
"""Return flood growth curve function based on ` amax _ records ` from a pooling group .
: return : Inverse cumulative distribution function with one parameter ` aep ` ( annual exceedance probability )
: type : : class : ` . GrowthCur... | if not self . donor_catchments :
self . find_donor_catchments ( )
gc = GrowthCurve ( distr , * self . _var_and_skew ( self . donor_catchments ) )
# Record intermediate results
self . results_log [ 'distr_name' ] = distr . upper ( )
self . results_log [ 'distr_params' ] = gc . params
return gc |
def _get_decoratables ( self , atype ) :
"""Returns a list of the objects that need to be decorated in the
current user namespace based on their type .
Args :
atype ( str ) : one of the values in : attr : ` atypes ` . Specifies the type of
object to search .""" | result = [ ]
defmsg = "Skipping {}; not decoratable or already decorated."
for varname in self . shell . run_line_magic ( "who_ls" , atype ) :
varobj = self . shell . user_ns . get ( varname , None )
decorate = False
if varobj is None : # Nothing useful can be done .
continue
if atype in [ "clas... |
def put_metadata ( self , key , value , namespace = 'default' ) :
"""Add metadata to segment or subsegment . Metadata is not indexed
but can be later retrieved by BatchGetTraces API .
: param str namespace : optional . Default namespace is ` default ` .
It must be a string and prefix ` AWS . ` is reserved .
... | self . _check_ended ( )
if not isinstance ( namespace , string_types ) :
log . warning ( "ignoring non string type metadata namespace" )
return
if namespace . startswith ( 'AWS.' ) :
log . warning ( "Prefix 'AWS.' is reserved, drop metadata with namespace %s" , namespace )
return
if self . metadata . ge... |
def get_principal_dictionary ( graph_client , object_ids , raise_on_graph_call_error = False ) :
"""Retrieves Azure AD Objects for corresponding object ids passed .
: param graph _ client : A client for Microsoft Graph .
: param object _ ids : The object ids to retrieve Azure AD objects for .
: param raise _ ... | if not object_ids :
return { }
object_params = GetObjectsParameters ( include_directory_object_references = True , object_ids = object_ids )
principal_dics = { object_id : DirectoryObject ( ) for object_id in object_ids }
aad_objects = graph_client . objects . get_objects_by_object_ids ( object_params )
try :
f... |
def decode ( self , bytes , raw = False ) :
"""decode ( bytearray , raw = False ) - > value
Decodes the given bytearray containing the elapsed time in
seconds since the GPS epoch and returns the corresponding
Python : class : ` datetime ` .
If the optional parameter ` ` raw ` ` is ` ` True ` ` , the integra... | sec = super ( Time32Type , self ) . decode ( bytes )
return sec if raw else dmc . toLocalTime ( sec ) |
def get_print_bbox ( x , y , zoom , width , height , dpi ) :
"""Calculate the tile bounding box based on position , map size and resolution .
The function returns the next larger tile - box , that covers the specified
page size in mm .
Args :
x ( float ) : map center x - coordinate in Mercator projection ( ... | tiles_h = width * dpi_to_dpmm ( dpi ) / TILE_SIZE
tiles_v = height * dpi_to_dpmm ( dpi ) / TILE_SIZE
mercator_coords = MercatorCoordinate ( x , y )
tile_coords = mercator_coords . to_tile ( zoom )
tile_bb = GridBB ( zoom , min_x = tile_coords . x - math . ceil ( tiles_h / 2 ) , max_x = tile_coords . x + math . ceil ( t... |
def reset_completion_defaults ( self ) -> None :
"""Resets tab completion settings
Needs to be called each time readline runs tab completion""" | self . allow_appended_space = True
self . allow_closing_quote = True
self . completion_header = ''
self . display_matches = [ ]
self . matches_delimited = False
self . matches_sorted = False
if rl_type == RlType . GNU :
readline . set_completion_display_matches_hook ( self . _display_matches_gnu_readline )
elif rl_... |
def list_records_previous_page ( self ) :
"""When paging through record results , this will return the previous page ,
using the same limit . If there are no more results , a NoMoreResults
exception will be raised .""" | uri = self . _paging . get ( "record" , { } ) . get ( "prev_uri" )
if uri is None :
raise exc . NoMoreResults ( "There are no previous pages of records " "to list." )
return self . _list_records ( uri ) |
def insert ( self , fields , typecast = False ) :
"""Inserts a record
> > > record = { ' Name ' : ' John ' }
> > > airtable . insert ( record )
Args :
fields ( ` ` dict ` ` ) : Fields to insert .
Must be dictionary with Column names as Key .
typecast ( ` ` boolean ` ` ) : Automatic data conversion from ... | return self . _post ( self . url_table , json_data = { "fields" : fields , "typecast" : typecast } ) |
def _software_params_to_argparse ( parameters ) :
"""Converts a SoftwareParameterCollection into an ArgumentParser object .
Parameters
parameters : SoftwareParameterCollection
The software parameters
Returns
argparse : ArgumentParser
An initialized argument parser""" | # Check software parameters
argparse = ArgumentParser ( )
boolean_defaults = { }
for parameter in parameters :
arg_desc = { "dest" : parameter . name , "required" : parameter . required , "help" : "" }
# TODO add help
if parameter . type == "Boolean" :
default = _to_bool ( parameter . defaultParamVa... |
def close ( self ) :
"""Close TCP connection
: returns : close status ( True for close / None if already close )
: rtype : bool or None""" | if self . __sock :
self . __sock . close ( )
self . __sock = None
return True
else :
return None |
def ask_confirmation ( ) :
"""Ask for confirmation to the user . Return true if the user confirmed
the execution , false otherwise .
: returns : bool""" | while True :
print ( "Do you want to restart these brokers? " , end = "" )
choice = input ( ) . lower ( )
if choice in [ 'yes' , 'y' ] :
return True
elif choice in [ 'no' , 'n' ] :
return False
else :
print ( "Please respond with 'yes' or 'no'" ) |
def _sorted_results ( self , results_dicts ) :
"""Sorts dict of results based on log start _ time .
Sorts the results and returns an array with only the values but sorted
by oldest value first . value
Args :
results _ dicts : List of result dicts
Returns :
List of only the time but sorted oldest first .... | print ( 'results dicts:' , results_dicts )
sorted_dict = sorted ( results_dicts , key = lambda k : k [ 'start_time' ] )
results = [ ]
for entry in sorted_dict :
results . append ( entry [ 'dt' ] )
return results |
def implicitly_wait ( self , time_to_wait ) :
"""Sets a sticky timeout to implicitly wait for an element to be found ,
or a command to complete . This method only needs to be called one
time per session . To set the timeout for calls to
execute _ async _ script , see set _ script _ timeout .
: Args :
- ti... | if self . w3c :
self . execute ( Command . SET_TIMEOUTS , { 'implicit' : int ( float ( time_to_wait ) * 1000 ) } )
else :
self . execute ( Command . IMPLICIT_WAIT , { 'ms' : float ( time_to_wait ) * 1000 } ) |
def exec_event ( event , webhooks , payload ) :
"""Execute event .
Merge webhooks run set to do some stats after all
of the webhooks been responded successfully .
| webhook - 1 + - - - - - +
| webhook - 2 + - - - - - + |
| merge runset + - - - - - >
| webhook - 3 + - - - - - + |
Error webhook will be ... | calls = ( call_webhook . s ( event , webhook , payload ) for webhook in webhooks )
callback = merge_webhooks_runset . s ( )
call_promise = chord ( calls )
promise = call_promise ( callback )
return promise |
def map_logging_verbosity ( verbosity ) :
'''Parameters
verbosity : int
logging verbosity level ( 0-4)
Returns
A logging level as exported by ` logging ` module .
By default returns logging . NOTSET
Raises
TypeError
when ` verbosity ` doesn ' t have type int
ValueError
when ` verbosity ` is nega... | if not isinstance ( verbosity , int ) :
raise TypeError ( 'Argument "verbosity" must have type int.' )
if not verbosity >= 0 :
raise ValueError ( 'Argument "verbosity" must be a positive number.' )
if verbosity >= len ( VERBOSITY_TO_LEVELS ) :
verbosity = len ( VERBOSITY_TO_LEVELS ) - 1
return VERBOSITY_TO_... |
def prepare_zoho_headers ( token , headers = None ) :
"""Add a ` Zoho Token ` _ to the request URI .
Recommended method of passing bearer tokens .
Authorization : Zoho - oauthtoken h480djs93hd8
. . _ ` Zoho - oauthtoken Token ` : custom zoho token""" | headers = headers or { }
headers [ "Authorization" ] = "{token_header} {token}" . format ( token_header = ZOHO_TOKEN_HEADER , token = token )
return headers |
def addFeature ( self , features , gdbVersion = None , rollbackOnFailure = True ) :
"""Adds a single feature to the service
Inputs :
feature - list of common . Feature object or a single
common . Feature Object , a FeatureSet object , or a
list of dictionary objects
gdbVersion - Geodatabase version to app... | url = self . _url + "/addFeatures"
params = { "f" : "json" }
if gdbVersion is not None :
params [ 'gdbVersion' ] = gdbVersion
if isinstance ( rollbackOnFailure , bool ) :
params [ 'rollbackOnFailure' ] = rollbackOnFailure
if isinstance ( features , list ) and len ( features ) > 0 :
if isinstance ( features ... |
import re
def substitute_max_n_special_chars ( input_str : str , n : int ) -> str :
"""Function to substitute the first n instances of space , comma , or dot characters with a colon ' : ' .
The substitutions are made in the order that the special characters appear in the text .
Example :
substitute _ max _ n ... | return re . sub ( '[ ,.]' , ':' , input_str , n ) |
def refetch_fields ( self , missing_fields ) :
"""Refetches a list of fields from the DB""" | db_fields = self . mongokat_collection . find_one ( { "_id" : self [ "_id" ] } , fields = { k : 1 for k in missing_fields } )
self . _fetched_fields += tuple ( missing_fields )
if not db_fields :
return
for k , v in db_fields . items ( ) :
self [ k ] = v |
def varattsget ( self , variable = None , expand = False , to_np = True ) :
"""Gets all variable attributes .
Unlike attget , which returns a single attribute entry value ,
this function returns all of the variable attribute entries ,
in a dictionary ( in the form of ' attribute ' : value pair ) for
a varia... | if ( isinstance ( variable , int ) and self . _num_zvariable > 0 and self . _num_rvariable > 0 ) :
print ( 'This CDF has both r and z variables. Use variable name' )
return None
if isinstance ( variable , str ) :
position = self . _first_zvariable
num_variables = self . _num_zvariable
for zVar in [ ... |
def process_query ( self ) :
"""Q . process _ query ( ) - - processes the user query ,
by tokenizing and stemming words .""" | self . query = wt ( self . query )
self . processed_query = [ ]
for word in self . query :
if word not in self . stop_words and word not in self . punctuation :
self . processed_query . append ( self . stemmer . stem ( word ) ) |
def make_config_data ( * , guided ) :
"""Makes the data necessary to construct a functional config file""" | config_data = { }
config_data [ INCLUDE_DIRS_KEY ] = _make_include_dirs ( guided = guided )
config_data [ RUNTIME_DIRS_KEY ] = _make_runtime_dirs ( guided = guided )
config_data [ RUNTIME_KEY ] = _make_runtime ( )
return config_data |
def converter_pm_log10 ( data ) :
"""Convert the given data to :
log10 ( subdata ) for subdata > 0
log10 ( - subdata ' ) for subdata ' < 0
0 for subdata ' ' = = 0
Parameters
data : array
input data
Returns
array _ converted : array
converted data""" | # indices _ zero = np . where ( data = = 0)
indices_gt_zero = np . where ( data > 0 )
indices_lt_zero = np . where ( data < 0 )
data_converted = np . zeros ( data . shape )
data_converted [ indices_gt_zero ] = np . log10 ( data [ indices_gt_zero ] )
data_converted [ indices_lt_zero ] = - np . log10 ( - data [ indices_l... |
def _subthread_handle_accepted ( self , client ) :
"""Gets accepted clients from the queue object and sets up the client socket .
The client can then be found in the clients dictionary with the socket object
as the key .""" | conn , addr = client
if self . handle_incoming ( conn , addr ) :
logging . info ( 'Accepted connection from client: {}' . format ( addr ) )
conn . setblocking ( False )
self . clients [ conn ] = addr
self . register ( conn )
else :
logging . info ( 'Refused connection from client: {}' . format ( add... |
def firmware_updates ( self , firmware_updates ) :
"""Sets the firmware _ updates of this ReportBillingData .
: param firmware _ updates : The firmware _ updates of this ReportBillingData .
: type : int""" | if firmware_updates is None :
raise ValueError ( "Invalid value for `firmware_updates`, must not be `None`" )
if firmware_updates is not None and firmware_updates < 0 :
raise ValueError ( "Invalid value for `firmware_updates`, must be a value greater than or equal to `0`" )
self . _firmware_updates = firmware_u... |
def mpr ( truth , recommend ) :
"""Mean Percentile Rank ( MPR ) .
Args :
truth ( numpy 1d array ) : Set of truth samples .
recommend ( numpy 1d array ) : Ordered set of recommended samples .
Returns :
float : MPR .""" | if len ( recommend ) == 0 and len ( truth ) == 0 :
return 0.
# best
elif len ( truth ) == 0 or len ( truth ) == 0 :
return 100.
# worst
accum = 0.
n_recommend = recommend . size
for t in truth :
r = np . where ( recommend == t ) [ 0 ] [ 0 ] / float ( n_recommend )
accum += r
return accum * 100. / tr... |
def get_height ( self , points , edge = True , attach = False , extra_height = 0 ) :
"""Launch ` ` pyny . Place . get _ height ( points ) ` ` recursively for all
the ` ` pyny . Place ` ` .
The points outside the object will have a NaN value in the
z column . These point will not be stored but it will be
ret... | for place in self :
points = place . get_height ( points , edge , attach , extra_height )
if not attach :
return points |
def iter_locals ( self ) :
'''Yield a sequence of ( name , value ) pairs of PyObjectPtr instances , for
the local variables of this frame''' | if self . is_optimized_out ( ) :
return
f_localsplus = self . field ( 'f_localsplus' )
for i in safe_range ( self . co_nlocals ) :
pyop_value = PyObjectPtr . from_pyobject_ptr ( f_localsplus [ i ] )
if not pyop_value . is_null ( ) :
pyop_name = PyObjectPtr . from_pyobject_ptr ( self . co_varnames [ ... |
def is_built_coherence ( self , graph = None ) :
"""Checks that node was build using input ` graph ` .
: return : ` Build ` status .
: raises GPflowError : Valid passed TensorFlow graph is different from
used graph in node .""" | graph = self . enquire_graph ( graph = graph )
is_built = self . is_built ( graph )
if is_built is Build . NOT_COMPATIBLE_GRAPH :
raise GPflowError ( 'Tensor "{}" uses different graph.' . format ( self . pathname ) )
return is_built |
def split ( self , s ) :
"""Splits a string into a list of ( start _ column , substring ) tuples .""" | normalized = "" . join ( map ( lambda c : " " if c . isspace ( ) else c , s ) )
string = False
quote = False
v = [ ]
for col , char in enumerate ( normalized . rstrip ( ) , 1 ) :
if char == '\\' :
quote = True
if char == '"' and not quote :
if string :
v [ - 1 ] = ( v [ - 1 ] [ 0 ] ,... |
def create_masked_lm_predictions ( tokens , masked_lm_prob , max_predictions_per_seq , vocab_words , rng ) :
"""Creates the predictions for the masked LM objective .""" | cand_indexes = [ ]
for ( i , token ) in enumerate ( tokens ) :
if token in [ '[CLS]' , '[SEP]' ] :
continue
cand_indexes . append ( i )
rng . shuffle ( cand_indexes )
output_tokens = list ( tokens )
num_to_predict = min ( max_predictions_per_seq , max ( 1 , int ( round ( len ( tokens ) * masked_lm_prob ... |
def OnNodeSelected ( self , event ) :
"""We have selected a node with the list control , tell the world""" | try :
node = self . sorted [ event . GetIndex ( ) ]
except IndexError , err :
log . warn ( _ ( 'Invalid index in node selected: %(index)s' ) , index = event . GetIndex ( ) )
else :
if node is not self . selected_node :
wx . PostEvent ( self , squaremap . SquareSelectionEvent ( node = node , point = ... |
def mulpyplex ( self , * stashes ) :
"""Mulpyplex across several stashes .
: param stashes : the stashes to mulpyplex
: return : a mulpyplexed list of states from the stashes in question , in the specified order""" | return mulpyplexer . MP ( list ( itertools . chain . from_iterable ( self . _stashes [ s ] for s in stashes ) ) ) |
def rm_automaster ( name , device , config = '/etc/auto_salt' ) :
'''Remove the mount point from the auto _ master
CLI Example :
. . code - block : : bash
salt ' * ' mount . rm _ automaster / mnt / foo / dev / sdg''' | contents = automaster ( config )
if name not in contents :
return True
# The entry is present , get rid of it
lines = [ ]
try :
with salt . utils . files . fopen ( config , 'r' ) as ifile :
for line in ifile :
line = salt . utils . stringutils . to_unicode ( line )
if line . star... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.