signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def measure_each ( * qubits : raw_types . Qid , key_func : Callable [ [ raw_types . Qid ] , str ] = str ) -> List [ gate_operation . GateOperation ] :
"""Returns a list of operations individually measuring the given qubits .
The qubits are measured in the computational basis .
Args :
* qubits : The qubits to ... | return [ MeasurementGate ( 1 , key_func ( q ) ) . on ( q ) for q in qubits ] |
def on_post_save ( sender , ** kwargs ) :
"""Expire ultracache cache keys affected by this object""" | if not invalidate :
return
if kwargs . get ( "raw" , False ) :
return
if sender is MigrationRecorder . Migration :
return
if issubclass ( sender , Model ) :
obj = kwargs [ "instance" ]
if isinstance ( obj , Model ) : # get _ for _ model itself is cached
try :
ct = ContentType . o... |
def detect_Martin2013 ( dat_orig , s_freq , time , opts ) :
"""Spindle detection based on Martin et al . 2013
Parameters
dat _ orig : ndarray ( dtype = ' float ' )
vector with the data for one channel
s _ freq : float
sampling frequency
time : ndarray ( dtype = ' float ' )
vector with the time points ... | dat_filt = transform_signal ( dat_orig , s_freq , 'remez' , opts . det_remez )
dat_det = transform_signal ( dat_filt , s_freq , 'moving_rms' , opts . moving_rms )
# downsampled
det_value = percentile ( dat_det , opts . det_thresh )
events = detect_events ( dat_det , 'above_thresh' , det_value )
if events is not None :
... |
def load ( self , filename , fv_extern = None ) :
"""Read model stored in the file .
: param filename : Path to file with model
: param fv _ extern : external feature vector function is passed here
: return :""" | self . modelparams [ "mdl_stored_file" ] = filename
if fv_extern is not None :
self . modelparams [ "fv_extern" ] = fv_extern
# segparams [ ' modelparams ' ] = {
# ' mdl _ stored _ file ' : mdl _ stored _ file ,
# # ' fv _ extern ' : fv _ function
self . mdl = Model ( modelparams = self . modelparams ) |
def save_attribute ( elements , module_path ) :
"""Recursively save attributes with module name and signature .""" | for elem , signature in elements . items ( ) :
if isinstance ( signature , dict ) : # Submodule case
save_attribute ( signature , module_path + ( elem , ) )
elif signature . isattribute ( ) :
assert elem not in attributes
# we need unicity
attributes [ elem ] = ( module_path , si... |
def CutAtClosestPoint ( self , p ) :
"""Let x be the point on the polyline closest to p . Then
CutAtClosestPoint returns two new polylines , one representing
the polyline from the beginning up to x , and one representing
x onwards to the end of the polyline . x is the first point
returned in the second poly... | ( closest , i ) = self . GetClosestPoint ( p )
tmp = [ closest ]
tmp . extend ( self . _points [ i + 1 : ] )
return ( Poly ( self . _points [ 0 : i + 1 ] ) , Poly ( tmp ) ) |
def rasterToWKB ( cls , rasterPath , srid , noData , raster2pgsql ) :
"""Accepts a raster file and converts it to Well Known Binary text using the raster2pgsql
executable that comes with PostGIS . This is the format that rasters are stored in a
PostGIS database .""" | raster2pgsqlProcess = subprocess . Popen ( [ raster2pgsql , '-s' , srid , '-N' , noData , rasterPath , 'n_a' ] , stdout = subprocess . PIPE )
# This commandline tool generates the SQL to load the raster into the database
# However , we want to use SQLAlchemy to load the values into the database .
# We do this by extrac... |
def pretty_str ( self , indent = 0 ) :
"""Return a human - readable string representation of this object .
Kwargs :
indent ( int ) : The amount of spaces to use as indentation .""" | if self . body :
return '\n' . join ( stmt . pretty_str ( indent ) for stmt in self . body )
else :
return ( ' ' * indent ) + '[empty]' |
def __is_outside_of_builddir ( project , path_to_check ) :
"""Check if a project lies outside of its expected directory .""" | bdir = project . builddir
cprefix = os . path . commonprefix ( [ path_to_check , bdir ] )
return cprefix != bdir |
def get_field_analysis ( self , field ) :
"""Get the FieldAnalysis for a given fieldname
: param field : TODO
: return : : class : ` FieldClassAnalysis `""" | class_analysis = self . get_class_analysis ( field . get_class_name ( ) )
if class_analysis :
return class_analysis . get_field_analysis ( field )
return None |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( VMStatCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'vmstat' } )
return config |
def get_authorization_url ( self , acr_values = None , prompt = None , scope = None , custom_params = None ) :
"""Function to get the authorization url that can be opened in the
browser for the user to provide authorization and authentication
Parameters :
* * * acr _ values ( list , optional ) : * * acr value... | params = { "oxd_id" : self . oxd_id }
if scope and isinstance ( scope , list ) :
params [ "scope" ] = scope
if acr_values and isinstance ( acr_values , list ) :
params [ "acr_values" ] = acr_values
if prompt and isinstance ( prompt , str ) :
params [ "prompt" ] = prompt
if custom_params :
params [ "cust... |
def _check_geo_param ( self , arg_list ) :
r"""Checks each function call to make sure that the user has provided at least one of the following geographic
parameters : ' stid ' , ' state ' , ' country ' , ' county ' , ' radius ' , ' bbox ' , ' cwa ' , ' nwsfirezone ' , ' gacc ' , or ' subgacc ' .
Arguments :
a... | geo_func = lambda a , b : any ( i in b for i in a )
check = geo_func ( self . geo_criteria , arg_list )
if check is False :
raise MesoPyError ( 'No stations or geographic search criteria specified. Please provide one of the ' 'following: stid, state, county, country, radius, bbox, cwa, nwsfirezone, gacc, subgacc' ) |
def int_0_inf ( cls , string ) :
'''Convert string to int .
If ` ` inf ` ` is supplied , it returns ` ` 0 ` ` .''' | if string == 'inf' :
return 0
try :
value = int ( string )
except ValueError as error :
raise argparse . ArgumentTypeError ( error )
if value < 0 :
raise argparse . ArgumentTypeError ( _ ( 'Value must not be negative.' ) )
else :
return value |
def _parse_response_for_all_events ( self , response ) :
"""This function will retrieve * most * of the event data , excluding Organizer & Attendee details""" | items = response . xpath ( u'//m:FindItemResponseMessage/m:RootFolder/t:Items/t:CalendarItem' , namespaces = soap_request . NAMESPACES )
if not items :
items = response . xpath ( u'//m:GetItemResponseMessage/m:Items/t:CalendarItem' , namespaces = soap_request . NAMESPACES )
if items :
self . count = len ( items... |
def get_lldp_neighbor_detail_output_lldp_neighbor_detail_remote_chassis_id ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
get_lldp_neighbor_detail = ET . Element ( "get_lldp_neighbor_detail" )
config = get_lldp_neighbor_detail
output = ET . SubElement ( get_lldp_neighbor_detail , "output" )
lldp_neighbor_detail = ET . SubElement ( output , "lldp-neighbor-detail" )
local_interface_name_key = ET . SubEleme... |
def multipart_content ( * files ) :
"""Returns a mutlipart content .
Note :
This script was clearly inspired by write - mime - multipart .""" | outer = MIMEMultipart ( )
for fname in files :
mtype = get_type ( fname )
maintype , subtype = mtype . split ( '/' , 1 )
with open ( fname ) as f :
msg = MIMEText ( f . read ( ) , _subtype = subtype )
msg . add_header ( 'Content-Disposition' , 'attachment' , filename = os . path . basename ( fna... |
def z ( self , what ) :
"""Change redshift .""" | if not isinstance ( what , numbers . Real ) :
raise exceptions . SynphotError ( 'Redshift must be a real scalar number.' )
self . _z = float ( what )
self . _redshift_model = RedshiftScaleFactor ( self . _z )
if self . z_type == 'wavelength_only' :
self . _redshift_flux_model = None
else : # conserve _ flux
... |
def removeDerivedMSCal ( msname ) :
"""Remove the derived columns like HA from an MS or CalTable .
It removes the columns using the data manager DerivedMSCal .
Such columns are HA , HA1 , HA2 , PA1 , PA2 , LAST , LAST1 , LAST2 , AZEL1,
AZEL2 , and UVW _ J2000.
It fails if one of the columns already exists .... | # Open the MS
t = table ( msname , readonly = False , ack = False )
# Remove the columns stored as DerivedMSCal .
dmi = t . getdminfo ( )
for x in dmi . values ( ) :
if x [ 'TYPE' ] == 'DerivedMSCal' :
t . removecols ( x [ 'COLUMNS' ] )
t . flush ( ) |
def reactToAMQPMessage ( message , send_back ) :
"""React to given ( AMQP ) message . ` message ` is expected to be
: py : func : ` collections . namedtuple ` structure from : mod : ` . structures ` filled
with all necessary data .
Args :
message ( object ) : One of the request objects defined in
: mod : ... | if _instanceof ( message , ExportRequest ) :
tmp_folder = ltp . create_ltp_package ( aleph_record = message . aleph_record , book_id = message . book_uuid , urn_nbn = message . urn_nbn , ebook_fn = message . filename , url = message . url , data = base64 . b64decode ( message . b64_data ) )
# remove directory f... |
def printTPRegionParams ( tpregion ) :
"""Note : assumes we are using TemporalMemory / TPShim in the TPRegion""" | tm = tpregion . getSelf ( ) . _tfdr
print "------------PY TemporalMemory Parameters ------------------"
print "numberOfCols =" , tm . columnDimensions
print "cellsPerColumn =" , tm . cellsPerColumn
print "minThreshold =" , tm . minThreshold
print "activationThreshold =" , tm . ac... |
def save_data ( self ) :
"""Store data as a JSON dump .""" | filename = os . path . join ( self . _get_prefix ( ) , self . model . site )
self . store . store_json ( filename , self . model . get_dict ( ) ) |
def is_internet_on ( host = "8.8.8.8" , port = 53 , timeout = 3 ) :
"""Checks if machine has internet connection
: param host : hostname to test
: param port : port of hostname
: param timeout : seconds before discarding connection
: return : True iff machine has internet connection""" | socket . setdefaulttimeout ( timeout )
socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) . connect ( ( host , port ) ) |
def _set_mult_grid_attr ( self ) :
"""Set multiple attrs from grid file given their names in the grid file .""" | grid_objs = self . _get_grid_files ( )
if self . grid_attrs is None :
self . grid_attrs = { }
# Override GRID _ ATTRS with entries in grid _ attrs
attrs = internal_names . GRID_ATTRS . copy ( )
for k , v in self . grid_attrs . items ( ) :
if k not in attrs :
raise ValueError ( 'Unrecognized internal nam... |
def composite ( df , sameGenderMZ , sameGenderDZ , size = ( 16 , 24 ) ) :
"""Embed both absdiff figures and heritability figures .""" | fig = plt . figure ( 1 , size )
ax1a = plt . subplot2grid ( ( 6 , 4 ) , ( 0 , 0 ) , rowspan = 2 , colspan = 1 )
ax2a = plt . subplot2grid ( ( 6 , 4 ) , ( 0 , 1 ) , rowspan = 2 , colspan = 1 )
ax3a = plt . subplot2grid ( ( 6 , 4 ) , ( 0 , 2 ) , rowspan = 2 , colspan = 1 )
ax4a = plt . subplot2grid ( ( 6 , 4 ) , ( 0 , 3 ... |
def elcm_session_list ( irmc_info ) :
"""send an eLCM request to list all sessions
: param irmc _ info : node info
: returns : dict object of sessions if succeed
' SessionList ' :
' Contains ' :
{ ' Id ' : id1 , ' Name ' : name1 } ,
{ ' Id ' : id2 , ' Name ' : name2 } ,
{ ' Id ' : idN , ' Name ' : nam... | # Send GET request to the server
resp = elcm_request ( irmc_info , method = 'GET' , path = '/sessionInformation/' )
if resp . status_code == 200 :
return _parse_elcm_response_body_as_json ( resp )
else :
raise scci . SCCIClientError ( ( 'Failed to list sessions with ' 'error code %s' % resp . status_code ) ) |
def n_exec_stmt ( self , node ) :
"""exec _ stmt : : = expr exprlist DUP _ TOP EXEC _ STMT
exec _ stmt : : = expr exprlist EXEC _ STMT""" | self . write ( self . indent , 'exec ' )
self . preorder ( node [ 0 ] )
if not node [ 1 ] [ 0 ] . isNone ( ) :
sep = ' in '
for subnode in node [ 1 ] :
self . write ( sep ) ;
sep = ", "
self . preorder ( subnode )
self . println ( )
self . prune ( ) |
def refweights ( self ) :
"""A | numpy | | numpy . ndarray | with equal weights for all segment
junctions . .
> > > from hydpy . models . hstream import *
> > > parameterstep ( ' 1d ' )
> > > states . qjoints . shape = 5
> > > states . qjoints . refweights
array ( [ 0.2 , 0.2 , 0.2 , 0.2 , 0.2 ] )""" | # pylint : disable = unsubscriptable - object
# due to a pylint bug ( see https : / / github . com / PyCQA / pylint / issues / 870)
return numpy . full ( self . shape , 1. / self . shape [ 0 ] , dtype = float ) |
def _compiled ( self ) :
"""Return a string of the self . block compiled to a block of
code that can be execed to get a function to execute""" | # Dev Notes :
# Because of fast locals in functions in both CPython and PyPy , getting a
# function to execute makes the code a few times faster than
# just executing it in the global exec scope .
prog = [ self . _prog_start ]
simple_func = { # OPS
'w' : lambda x : x , 'r' : lambda x : x , '~' : lambda x : '(~' + x + '... |
def line_oriented ( cls , line_oriented_options , console ) :
"""Given Goal . Options and a Console , yields functions for writing to stdout and stderr , respectively .
The passed options instance will generally be the ` Goal . Options ` of a ` LineOriented ` ` Goal ` .""" | if type ( line_oriented_options ) != cls . Options :
raise AssertionError ( 'Expected Options for `{}`, got: {}' . format ( cls . __name__ , line_oriented_options ) )
output_file = line_oriented_options . values . output_file
sep = line_oriented_options . values . sep . encode ( 'utf-8' ) . decode ( 'unicode_escape... |
def read_spec ( filename , verbose = False ) :
"""Read an SBP specification .
Parameters
filename : str
Local filename for specification .
verbose : bool
Print out some debugging info
Returns
Raises
Exception
On empty file .
yaml . YAMLError
On Yaml parsing error
voluptuous . Invalid
On in... | contents = None
with open ( filename , 'r' ) as f :
contents = yaml . load ( f )
if contents is None :
raise Exception ( "Empty yaml file: %s." % filename )
try :
s . package_schema ( contents )
except Exception as e :
sys . stderr . write ( "Invalid SBP YAML specification: %s.\n... |
def mvir ( self , H = 70. , Om = 0.3 , overdens = 200. , wrtcrit = False , forceint = False , ro = None , vo = None , use_physical = False ) : # use _ physical necessary bc of pop = False , does nothing inside
"""NAME :
mvir
PURPOSE :
calculate the virial mass
INPUT :
H = ( default : 70 ) Hubble constant ... | if ro is None :
ro = self . _ro
if vo is None :
vo = self . _vo
# Evaluate the virial radius
try :
rvir = self . rvir ( H = H , Om = Om , overdens = overdens , wrtcrit = wrtcrit , use_physical = False , ro = ro , vo = vo )
except AttributeError :
raise AttributeError ( "This potential does not have a '_... |
def _create_group_tree ( self , levels ) :
"""This method creates a group tree""" | if levels [ 0 ] != 0 :
raise KPError ( "Invalid group tree" )
for i in range ( len ( self . groups ) ) :
if ( levels [ i ] == 0 ) :
self . groups [ i ] . parent = self . root_group
self . groups [ i ] . index = len ( self . root_group . children )
self . root_group . children . append ( ... |
def update_url_params ( url , replace_all = False , ** url_params ) :
""": return : url with its query updated from url _ query ( non - matching params are retained )""" | # Ensure ' replace _ all ' can be sent as a url param
if not ( replace_all is True or replace_all is False ) :
url_params [ 'replace_all' ] = replace_all
if not url or not url_params :
return url or None
scheme , netloc , url_path , url_query , fragment = _urlsplit ( url )
if replace_all is True :
url_query... |
def add_event ( self , name , time , chan ) :
"""Action : add a single event .""" | self . annot . add_event ( name , time , chan = chan )
self . update_annotations ( ) |
def from_tuple ( tup ) :
"""Convert a tuple into a range with error handling .
Parameters
tup : tuple ( len 2 or 3)
The tuple to turn into a range .
Returns
range : range
The range from the tuple .
Raises
ValueError
Raised when the tuple length is not 2 or 3.""" | if len ( tup ) not in ( 2 , 3 ) :
raise ValueError ( 'tuple must contain 2 or 3 elements, not: %d (%r' % ( len ( tup ) , tup , ) , )
return range ( * tup ) |
def isfile ( self , path = None , client_kwargs = None , assume_exists = None ) :
"""Return True if path is an existing regular file .
Args :
path ( str ) : Path or URL .
client _ kwargs ( dict ) : Client arguments .
assume _ exists ( bool or None ) : This value define the value to return
in the case ther... | relative = self . relpath ( path )
if not relative : # Root always exists and is a directory
return False
if path [ - 1 ] != '/' and not self . is_locator ( path , relative = True ) :
return self . exists ( path = path , client_kwargs = client_kwargs , assume_exists = assume_exists )
return False |
def isvector_or_scalar ( a ) :
"""one - dimensional arrays having shape [ N ] ,
row and column matrices having shape [ 1 N ] and
[ N 1 ] correspondingly , and their generalizations
having shape [ 1 1 . . . N . . . 1 1 1 ] .
Scalars have shape [ 1 1 . . . 1 ] .
Empty arrays dont count""" | try :
return a . size and a . ndim - a . shape . count ( 1 ) <= 1
except :
return False |
def token ( self , value ) :
"""Set the Token of the message .
: type value : String
: param value : the Token
: raise AttributeError : if value is longer than 256""" | if value is None :
self . _token = value
return
if not isinstance ( value , str ) :
value = str ( value )
if len ( value ) > 256 :
raise AttributeError
self . _token = value |
def get_proxy_ticket ( self , pgt ) :
"""Returns proxy ticket given the proxy granting ticket""" | response = requests . get ( self . get_proxy_url ( pgt ) )
if response . status_code == 200 :
from lxml import etree
root = etree . fromstring ( response . content )
tickets = root . xpath ( "//cas:proxyTicket" , namespaces = { "cas" : "http://www.yale.edu/tp/cas" } )
if len ( tickets ) == 1 :
r... |
def save_assets ( self , dest_path ) :
"""Save plot assets alongside dest _ path .
Some plots may have assets , like bitmap files , which need to be
saved alongside the rendered plot file .
: param dest _ path : path of the main output file .""" | for idx , subplot in enumerate ( self . subplots ) :
subplot . save_assets ( dest_path , suffix = '_%d' % idx ) |
def visit_Call ( self , node ) :
"""Function calls are not handled for now .
> > > import gast as ast
> > > from pythran import passmanager , backend
> > > node = ast . parse ( ' ' '
. . . def foo ( ) :
. . . a = _ _ builtin _ _ . range ( 10 ) ' ' ' )
> > > pm = passmanager . PassManager ( " test " )
... | for alias in self . aliases [ node . func ] :
if alias is MODULES [ '__builtin__' ] [ 'getattr' ] :
attr_name = node . args [ - 1 ] . s
attribute = attributes [ attr_name ] [ - 1 ]
self . add ( node , attribute . return_range ( None ) )
elif isinstance ( alias , Intrinsic ) :
ali... |
def buscar_rules ( self , id_ambiente_vip , id_vip = '' ) :
"""Search rules by environmentvip _ id
: return : Dictionary with the following structure :
{ ' name _ rule _ opt ' : [ { ' name _ rule _ opt ' : < name > , ' id ' : < id > } , . . . ] }
: raise InvalidParameterError : Environment VIP identifier is n... | url = 'environment-vip/get/rules/' + str ( id_ambiente_vip ) + '/' + str ( id_vip )
code , xml = self . submit ( None , 'GET' , url )
return self . response ( code , xml ) |
def lock_key ( group_id , item_id , group_width = 8 ) :
"""Creates a lock ID where the lower bits are the group ID and the upper bits
are the item ID . This allows the use of a bigint namespace for items , with a
limited space for grouping .
: group _ id : an integer identifying the group . Must be less than ... | if group_id >= ( 1 << group_width ) :
raise Exception ( "Group ID is too big" )
if item_id >= ( 1 << ( 63 - group_width ) ) - 1 :
raise Exception ( "Item ID is too big" )
return ( item_id << group_width ) | group_id |
def enable_passive_svc_checks ( self , service ) :
"""Enable passive checks for a service
Format of the line that triggers function call : :
ENABLE _ PASSIVE _ SVC _ CHECKS ; < host _ name > ; < service _ description >
: param service : service to edit
: type service : alignak . objects . service . Service ... | if not service . passive_checks_enabled :
service . modified_attributes |= DICT_MODATTR [ "MODATTR_PASSIVE_CHECKS_ENABLED" ] . value
service . passive_checks_enabled = True
self . send_an_element ( service . get_update_status_brok ( ) ) |
def stripHtml ( html , joiner = '' ) :
"""Strips out the HTML tags from the inputted text , returning the basic
text . This algorightm was found on
[ http : / / stackoverflow . com / questions / 753052 / strip - html - from - strings - in - python StackOverflow ] .
: param html | < str >
: return < str >""" | stripper = HTMLStripper ( )
stripper . feed ( html . replace ( '<br>' , '\n' ) . replace ( '<br/>' , '\n' ) )
return stripper . text ( joiner ) |
def layers ( ) :
"""Get the layers module good for TF 1 and TF 2 work for now .""" | global _cached_layers
if _cached_layers is not None :
return _cached_layers
layers_module = tf . layers
try :
from tensorflow . python import tf2
# pylint : disable = g - direct - tensorflow - import , g - import - not - at - top
if tf2 . enabled ( ) :
tf . logging . info ( "Running in V2 mode, ... |
def register_bse_task ( self , * args , ** kwargs ) :
"""Register a Bethe - Salpeter task .""" | kwargs [ "task_class" ] = BseTask
return self . register_task ( * args , ** kwargs ) |
def knowledge_base_path ( cls , project , knowledge_base ) :
"""Return a fully - qualified knowledge _ base string .""" | return google . api_core . path_template . expand ( 'projects/{project}/knowledgeBases/{knowledge_base}' , project = project , knowledge_base = knowledge_base , ) |
def find_best_rsquared ( list_of_fits ) :
"""Return the best fit , based on rsquared""" | res = sorted ( list_of_fits , key = lambda x : x . rsquared )
return res [ - 1 ] |
async def handle_agent_job_done ( self , agent_addr , message : AgentJobDone ) :
"""Handle an AgentJobDone message . Send the data back to the client , and start new job if needed""" | if agent_addr in self . _registered_agents :
self . _logger . info ( "Job %s %s finished on agent %s" , message . job_id [ 0 ] , message . job_id [ 1 ] , agent_addr )
# Remove the job from the list of running jobs
del self . _job_running [ message . job_id ]
# Sent the data back to the client
await ... |
def provider_factory ( factory = _sentinel , scope = NoneScope ) :
'''Decorator to create a provider using the given factory , and scope .
Can also be used in a non - decorator manner .
: param scope : Scope key , factory , or instance
: type scope : object or callable
: return : decorator
: rtype : decor... | if factory is _sentinel :
return functools . partial ( provider_factory , scope = scope )
provider = Provider ( factory , scope )
return provider |
def unflat_take ( items_list , unflat_index_list ) :
r"""Returns nested subset of items _ list
Args :
items _ list ( list ) :
unflat _ index _ list ( list ) : nested list of indices
CommandLine :
python - m utool . util _ list - - exec - unflat _ take
SeeAlso :
ut . take
Example :
> > > # DISABLE ... | return [ unflat_take ( items_list , xs ) if isinstance ( xs , list ) else take ( items_list , xs ) for xs in unflat_index_list ] |
def code ( ctx , show_hidden , query , single ) :
"""Generate codes .
Generate codes from credentials stored on your YubiKey .
Provide a query string to match one or more specific credentials .
Touch and HOTP credentials require a single match to be triggered .""" | ensure_validated ( ctx )
controller = ctx . obj [ 'controller' ]
creds = [ ( cr , c ) for ( cr , c ) in controller . calculate_all ( ) if show_hidden or not cr . is_hidden ]
creds = _search ( creds , query )
if len ( creds ) == 1 :
cred , code = creds [ 0 ]
if cred . touch :
prompt_for_touch ( )
try... |
def usergroups_list ( self , ** kwargs ) -> SlackResponse :
"""List all User Groups for a team""" | self . _validate_xoxp_token ( )
return self . api_call ( "usergroups.list" , http_verb = "GET" , params = kwargs ) |
def _create_cd_drives ( cd_drives , controllers = None , parent_ref = None ) :
'''Returns a list of vim . vm . device . VirtualDeviceSpec objects representing the
CD / DVD drives to be created for a virtual machine
cd _ drives
CD / DVD drive properties
controllers
CD / DVD drive controllers ( IDE , SATA )... | cd_drive_specs = [ ]
keys = range ( - 3000 , - 3050 , - 1 )
if cd_drives :
devs = [ dvd [ 'adapter' ] for dvd in cd_drives ]
log . trace ( 'Creating cd/dvd drives %s' , devs )
for drive , key in zip ( cd_drives , keys ) : # if a controller is not available / cannot be created we should use the
# one whi... |
def calculate_nonagonal_number ( nth_order : int ) -> int :
"""Computes the nth nonagonal number
A nonagonal number is a figurate number that extends the concept of triangular and square numbers to the
n - gon ( 9 - sided polygon ) i . e . , nonagon . The nth nonagonal number is calculated using the formula :
... | return int ( ( ( nth_order * ( ( 7 * nth_order ) - 5 ) ) / 2 ) ) |
def _create_storage_folder ( self ) :
'''Creates a storage folder using the query name by replacing
spaces in the query with ' _ ' ( underscore )''' | try :
print ( colored ( '\nCreating Storage Folder...' , 'yellow' ) )
self . _storageFolder = os . path . join ( self . _destinationFolder , self . _imageQuery . replace ( ' ' , '_' ) )
os . makedirs ( self . _storageFolder )
print ( colored ( 'Storage Folder - ' + self . _storageFolder + ' created.' , ... |
def _str_dotted_getattr ( obj , name ) :
"""Expands extends getattr to allow dots in x to indicate nested objects .
Args :
obj ( object ) : an object .
name ( str ) : a name for a field in the object .
Returns :
Any : the value of named attribute .
Raises :
AttributeError : if the named attribute does... | for part in name . split ( '.' ) :
obj = getattr ( obj , part )
return str ( obj ) if obj else None |
def readline ( self ) :
"""Read and return a line of text .
: rtype : str
: return : the next line of text in the file , including the
newline character""" | _complain_ifclosed ( self . closed )
line = self . f . readline ( )
if self . __encoding :
return line . decode ( self . __encoding , self . __errors )
else :
return line |
def close_room ( self , room , namespace = None ) :
"""Close a room .""" | return self . socketio . close_room ( room = room , namespace = namespace or self . namespace ) |
def _activation_summary ( x ) :
"""Helper to create summaries for activations .
Creates a summary that provides a histogram of activations .
Creates a summary that measures the sparsity of activations .
Args :
x : Tensor
Returns :
nothing""" | # Remove ' tower _ [ 0-9 ] / ' from the name in case this is a multi - GPU training
# session . This helps the clarity of presentation on tensorboard .
tensor_name = re . sub ( '%s_[0-9]*/' % TOWER_NAME , '' , x . op . name )
tf . summary . histogram ( tensor_name + '/activations' , x )
tf . summary . scalar ( tensor_n... |
def sort ( self , callback = None ) :
"""Sort through each item with a callback .
: param callback : The callback
: type callback : callable or None
: rtype : Collection""" | items = self . items
if callback :
return self . __class__ ( sorted ( items , key = callback ) )
else :
return self . __class__ ( sorted ( items ) ) |
def _images ( self , sys_output ) :
'''a helper method for parsing docker image output''' | import re
gap_pattern = re . compile ( '\t|\s{2,}' )
image_list = [ ]
output_lines = sys_output . split ( '\n' )
column_headers = gap_pattern . split ( output_lines [ 0 ] )
for i in range ( 1 , len ( output_lines ) ) :
columns = gap_pattern . split ( output_lines [ i ] )
if len ( columns ) == len ( column_heade... |
def set_option ( self , option , value ) :
"""Set a plugin option in configuration file .
Note : Use sig _ option _ changed to call it from widgets of the
same or another plugin .""" | CONF . set ( self . CONF_SECTION , str ( option ) , value ) |
def Reset ( self ) :
"""Reset the lexer to process a new data feed .""" | # The first state
self . state = "INITIAL"
self . state_stack = [ ]
# The buffer we are parsing now
self . buffer = ""
self . error = 0
self . verbose = 0
# The index into the buffer where we are currently pointing
self . processed = 0
self . processed_buffer = "" |
def cross_product ( p1 , p2 , o = ( 0 , 0 ) ) :
"""Returns cross product
Args :
p1 , p2 : point ( x , y )
o : origin""" | v1 = vector ( o , p1 )
v2 = vector ( o , p2 )
return v1 [ 0 ] * v2 [ 1 ] - v1 [ 1 ] * v2 [ 0 ] |
def chunks_generator ( iterable , count_items_in_chunk ) :
"""Очень внимательно ! Не дает обходить дважды
: param iterable :
: param count _ items _ in _ chunk :
: return :""" | iterator = iter ( iterable )
for first in iterator : # stops when iterator is depleted
def chunk ( ) : # construct generator for next chunk
yield first
# yield element from for loop
for more in islice ( iterator , count_items_in_chunk - 1 ) :
yield more
# yield more elements ... |
def _combine_variant_collections ( cls , combine_fn , variant_collections , kwargs ) :
"""Create a single VariantCollection from multiple different collections .
Parameters
cls : class
Should be VariantCollection
combine _ fn : function
Function which takes any number of sets of variants and returns
som... | kwargs [ "variants" ] = combine_fn ( * [ set ( vc ) for vc in variant_collections ] )
kwargs [ "source_to_metadata_dict" ] = cls . _merge_metadata_dictionaries ( [ vc . source_to_metadata_dict for vc in variant_collections ] )
kwargs [ "sources" ] = set . union ( * ( [ vc . sources for vc in variant_collections ] ) )
f... |
def recv_exit_status ( self ) :
"""Return the exit status from the process on the server . This is
mostly useful for retrieving the reults of an L { exec _ command } .
If the command hasn ' t finished yet , this method will wait until
it does , or until the channel is closed . If no exit status is
provided ... | self . status_event . wait ( )
assert self . status_event . isSet ( )
return self . exit_status |
def visit_Slice ( self , node : ast . Slice ) -> slice :
"""Visit ` ` lower ` ` , ` ` upper ` ` and ` ` step ` ` and recompute the node as a ` ` slice ` ` .""" | lower = None
# type : Optional [ int ]
if node . lower is not None :
lower = self . visit ( node = node . lower )
upper = None
# type : Optional [ int ]
if node . upper is not None :
upper = self . visit ( node = node . upper )
step = None
# type : Optional [ int ]
if node . step is not None :
step = self .... |
def create_job_queue ( self , queue_name , priority , state , compute_env_order ) :
"""Create a job queue
: param queue _ name : Queue name
: type queue _ name : str
: param priority : Queue priority
: type priority : int
: param state : Queue state
: type state : string
: param compute _ env _ order ... | for variable , var_name in ( ( queue_name , 'jobQueueName' ) , ( priority , 'priority' ) , ( state , 'state' ) , ( compute_env_order , 'computeEnvironmentOrder' ) ) :
if variable is None :
raise ClientException ( '{0} must be provided' . format ( var_name ) )
if state not in ( 'ENABLED' , 'DISABLED' ) :
... |
def crawl_links ( self , seed_url = None ) :
"""Find new links given a seed URL and follow them breadth - first .
Save page responses as PART . html files .
Return the PART . html filenames created during crawling .""" | if seed_url is not None :
self . seed_url = seed_url
if self . seed_url is None :
sys . stderr . write ( 'Crawling requires a seed URL.\n' )
return [ ]
prev_part_num = utils . get_num_part_files ( )
crawled_links = set ( )
uncrawled_links = OrderedSet ( )
uncrawled_links . add ( self . seed_url )
try :
... |
def get_ptr ( data , offset = None , ptr_type = ctypes . c_void_p ) :
"""Returns a void pointer to the data""" | ptr = ctypes . cast ( ctypes . pointer ( data ) , ctypes . c_void_p )
if offset :
ptr = ctypes . c_void_p ( ptr . value + offset )
if ptr_type != ctypes . c_void_p :
ptr = ctypes . cast ( ptr , ptr_type )
return ptr |
def get_lang_class ( lang ) :
"""Import and load a Language class .
lang ( unicode ) : Two - letter language code , e . g . ' en ' .
RETURNS ( Language ) : Language class .""" | global LANGUAGES
# Check if an entry point is exposed for the language code
entry_point = get_entry_point ( "spacy_languages" , lang )
if entry_point is not None :
LANGUAGES [ lang ] = entry_point
return entry_point
if lang not in LANGUAGES :
try :
module = importlib . import_module ( ".lang.%s" % l... |
def varea_stack ( self , stackers , ** kw ) :
'''Generate multiple ` ` VArea ` ` renderers for levels stacked bottom
to top .
Args :
stackers ( seq [ str ] ) : a list of data source field names to stack
successively for ` ` y1 ` ` and ` ` y1 ` ` varea coordinates .
Additionally , the ` ` name ` ` of the r... | result = [ ]
for kw in _double_stack ( stackers , "y1" , "y2" , ** kw ) :
result . append ( self . varea ( ** kw ) )
return result |
def update_keys ( self ) :
"""Updates the Google API key with the text value""" | from . . . main import add_api_key
add_api_key ( "reddit_api_user_agent" , self . reddit_api_user_agent . get ( ) )
add_api_key ( "reddit_api_client_id" , self . reddit_api_client_id . get ( ) )
add_api_key ( "reddit_api_client_secret" , self . reddit_api_client_secret . get ( ) ) |
def _collect_data_references ( self , irsb , irsb_addr ) :
"""Unoptimises IRSB and _ add _ data _ reference ' s for individual statements or
for parts of statements ( e . g . Store )
: param pyvex . IRSB irsb : Block to scan for data references
: param int irsb _ addr : Address of block
: return : None""" | if irsb . data_refs :
self . _process_irsb_data_refs ( irsb )
elif irsb . statements :
irsb = self . _unoptimize_irsb ( irsb )
# for each statement , collect all constants that are referenced or used .
self . _collect_data_references_by_scanning_stmts ( irsb , irsb_addr ) |
def score_genes ( adata , gene_list , ctrl_size = 50 , gene_pool = None , n_bins = 25 , score_name = 'score' , random_state = 0 , copy = False , use_raw = False ) : # we use the scikit - learn convention of calling the seed " random _ state "
"""Score a set of genes [ Satija15 ] _ .
The score is the average expre... | logg . info ( 'computing score \'{}\'' . format ( score_name ) , r = True )
adata = adata . copy ( ) if copy else adata
if random_state :
np . random . seed ( random_state )
gene_list_in_var = [ ]
var_names = adata . raw . var_names if use_raw else adata . var_names
for gene in gene_list :
if gene in var_names ... |
def rlmb_base_stochastic_discrete_noresize ( ) :
"""Base setting with stochastic discrete model .""" | hparams = rlmb_base ( )
hparams . generative_model = "next_frame_basic_stochastic_discrete"
hparams . generative_model_params = "next_frame_basic_stochastic_discrete"
hparams . resize_height_factor = 1
hparams . resize_width_factor = 1
return hparams |
async def restrictChatMember ( self , chat_id , user_id , until_date = None , can_send_messages = None , can_send_media_messages = None , can_send_other_messages = None , can_add_web_page_previews = None ) :
"""See : https : / / core . telegram . org / bots / api # restrictchatmember""" | p = _strip ( locals ( ) )
return await self . _api_request ( 'restrictChatMember' , _rectify ( p ) ) |
def _log ( self , s ) :
r"""Log a string . It flushes but doesn ' t append \ n , so do that yourself .""" | # TODO ( tewalds ) : Should this be using logging . info instead ? How to see them
# outside of google infrastructure ?
sys . stderr . write ( s )
sys . stderr . flush ( ) |
def parseTopDepth ( self , descendants = ( ) ) :
"""Parse tex for highest tag in hierarchy
> > > TOC . fromLatex ( ' \\ section { Hah } \\ subsection { No } ' ) . parseTopDepth ( )
> > > s = ' \\ subsubsubsection { Yo } \\ subsubsection { Hah } '
> > > TOC . fromLatex ( s ) . parseTopDepth ( )
> > > h = ( '... | descendants = list ( descendants ) or list ( getattr ( self . source , 'descendants' , descendants ) )
if not descendants :
return - 1
return min ( TOC . getHeadingLevel ( e , self . hierarchy ) for e in descendants ) |
def compute_acf ( cls , filename , start_index = None , end_index = None , per_walker = False , walkers = None , parameters = None ) :
"""Computes the autocorrleation function of the model params in the
given file .
By default , parameter values are averaged over all walkers at each
iteration . The ACF is the... | acfs = { }
with cls . _io ( filename , 'r' ) as fp :
if parameters is None :
parameters = fp . variable_params
if isinstance ( parameters , str ) or isinstance ( parameters , unicode ) :
parameters = [ parameters ]
for param in parameters :
if per_walker : # just call myself with a s... |
def get_published_topics ( self ) :
"""Get a list of published topics for this instance .
Streams applications publish streams to a a topic that can be subscribed to by other
applications . This allows a microservice approach where publishers
and subscribers are independent of each other .
A published strea... | published_topics = [ ]
# A topic can be published multiple times
# ( typically with the same schema ) but the
# returned list only wants to contain a topic , schema
# pair once . I . e . the list of topics being published is
# being returned , not the list of streams .
seen_topics = { }
for es in self . get_exported_st... |
def render_summary ( self , include_title = True , request = None ) :
"""Render the traceback for the interactive console .""" | title = ''
frames = [ ]
classes = [ 'traceback' ]
if not self . frames :
classes . append ( 'noframe-traceback' )
if include_title :
if self . is_syntax_error :
title = text_ ( 'Syntax Error' )
else :
title = text_ ( 'Traceback <small>(most recent call last)' '</small>' )
for frame in self .... |
def project_geometry ( geometry , crs , to_latlong = False ) :
"""Project a shapely Polygon or MultiPolygon from WGS84 to UTM , or vice - versa
Parameters
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : int
the starting coordinate reference system of the passed - in geometry
to ... | gdf = gpd . GeoDataFrame ( )
gdf . crs = crs
gdf . name = 'geometry to project'
gdf [ 'geometry' ] = None
gdf . loc [ 0 , 'geometry' ] = geometry
gdf_proj = project_gdf ( gdf , to_latlong = to_latlong )
geometry_proj = gdf_proj [ 'geometry' ] . iloc [ 0 ]
return geometry_proj , gdf_proj . crs |
def sorted_for_ner ( crf_classes ) :
"""Return labels sorted in a default order suitable for NER tasks :
> > > sorted _ for _ ner ( [ ' B - ORG ' , ' B - PER ' , ' O ' , ' I - PER ' ] )
[ ' O ' , ' B - ORG ' , ' B - PER ' , ' I - PER ' ]""" | def key ( cls ) :
if len ( cls ) > 2 and cls [ 1 ] == '-' : # group names like B - ORG and I - ORG together
return cls . split ( '-' , 1 ) [ 1 ] , cls
return '' , cls
return sorted ( crf_classes , key = key ) |
def swf2png ( swf_path , png_path , swfrender_path = "swfrender" ) :
"""Convert SWF slides into a PNG image
Raises :
OSError is raised if swfrender is not available .
ConversionError is raised if image cannot be created .""" | # Currently rely on swftools
# Would be great to have a native python dependency to convert swf into png or jpg .
# However it seems that pyswf isn ' t flawless . Some graphical elements ( like the text ! ) are lost during
# the export .
try :
cmd = [ swfrender_path , swf_path , '-o' , png_path ]
subprocess . c... |
def _lowest_rowids ( self , table , limit ) :
"""Gets the lowest available row ids for table insertion . Keeps things tidy !
Parameters
table : str
The name of the table being modified
limit : int
The number of row ids needed
Returns
available : sequence
An array of all available row ids""" | try :
t = self . query ( "SELECT id FROM {}" . format ( table ) , unpack = True , fmt = 'table' )
ids = t [ 'id' ]
all_ids = np . array ( range ( 1 , max ( ids ) ) )
except TypeError :
ids = None
all_ids = np . array ( range ( 1 , limit + 1 ) )
available = all_ids [ np . in1d ( all_ids , ids , assum... |
def inferred_var_seqs_plus_flanks ( self , ref_seq , flank_length ) :
'''Returns start position of first flank sequence , plus a list of sequences -
the REF , plus one for each ALT . sequence . Order same as in ALT column''' | flank_start = max ( 0 , self . POS - flank_length )
flank_end = min ( len ( ref_seq ) - 1 , self . ref_end_pos ( ) + flank_length )
seqs = [ ref_seq [ flank_start : self . POS ] + self . REF + ref_seq [ self . ref_end_pos ( ) + 1 : flank_end + 1 ] ]
for alt in self . ALT :
seqs . append ( ref_seq [ flank_start : se... |
def save_files ( self , nodes ) :
"""Saves user defined files using give nodes .
: param nodes : Nodes .
: type nodes : list
: return : Method success .
: rtype : bool""" | metrics = { "Opened" : 0 , "Cached" : 0 }
for node in nodes :
file = node . file
if self . __container . get_editor ( file ) :
if self . __container . save_file ( file ) :
metrics [ "Opened" ] += 1
self . __uncache ( file )
else :
cache_data = self . __files_cache . g... |
def __cutRaw ( self , oiraw , maxLength ) :
'''现将句子按句子完结符号切分 , 如果切分完后一个句子长度超过限定值
, 再对该句子进行切分''' | vec = [ ]
m = re . findall ( u".*?[。?!;;!?]" , oiraw )
num , l , last = 0 , 0 , 0
for i in range ( len ( m ) ) :
if ( num + len ( m [ i ] ) >= maxLength ) :
vec . append ( "" . join ( m [ last : i ] ) )
last = i
num = len ( m [ i ] )
else :
num += len ( m [ i ] )
l += len ( m... |
def image ( self , img ) :
"""Set buffer to value of Python Imaging Library image . The image should
be in 1 bit mode and a size equal to the display size .""" | if img . mode != '1' :
raise ValueError ( 'Image must be in mode 1.' )
imwidth , imheight = img . size
if imwidth != self . width or imheight != self . height :
raise ValueError ( 'Image must be same dimensions as display ({0}x{1}).' . format ( self . width , self . height ) )
# Grab all the pixels from the ima... |
def _get_slack_array_construct ( self ) :
"""Returns a construct for an array of slack bus data .""" | bus_no = integer . setResultsName ( "bus_no" )
s_rating = real . setResultsName ( "s_rating" )
# MVA
v_rating = real . setResultsName ( "v_rating" )
# kV
v_magnitude = real . setResultsName ( "v_magnitude" )
# p . u .
ref_angle = real . setResultsName ( "ref_angle" )
# p . u .
q_max = Optional ( real ) . setResultsName... |
def send_cmd ( self , command , connId = 'default' ) :
"""Sends any command to FTP server . Returns server output .
Parameters :
- command - any valid command to be sent ( invalid will result in exception ) .
- connId ( optional ) - connection identifier . By default equals ' default '
Example :
| send cm... | thisConn = self . __getConnection ( connId )
outputMsg = ""
try :
outputMsg += str ( thisConn . sendcmd ( command ) )
except ftplib . all_errors as e :
raise FtpLibraryError ( str ( e ) )
if self . printOutput :
logger . info ( outputMsg )
return outputMsg |
def _kvmatrix2d ( km , vm ) :
'''km = [ [ [ 1 ] , [ 3 ] ] , [ [ 1 , 2 ] , [ 3 , ' a ' ] ] , [ [ 1 , 2 , 22 ] ] ]
show _ kmatrix ( km )
vm = [ [ [ 222 ] ] , [ ' b ' ] ]
show _ vmatrix ( vm )
d = _ kvmatrix2d ( km , vm )''' | d = { }
kmwfs = get_kmwfs ( km )
vmwfs = elel . get_wfs ( vm )
lngth = vmwfs . __len__ ( )
for i in range ( 0 , lngth ) :
value = elel . getitem_via_pathlist ( vm , vmwfs [ i ] )
cond = elel . is_leaf ( value )
if ( cond ) :
_setitem_via_pathlist ( d , kmwfs [ i ] , value )
else :
_setde... |
def _rlmb_tiny_overrides ( ) :
"""Parameters to override for tiny setting excluding agent - related hparams .""" | return dict ( epochs = 1 , num_real_env_frames = 128 , model_train_steps = 2 , max_num_noops = 1 , eval_max_num_noops = 1 , generative_model_params = "next_frame_tiny" , stop_loop_early = True , resize_height_factor = 2 , resize_width_factor = 2 , wm_eval_rollout_ratios = [ 1 ] , rl_env_max_episode_steps = 7 , eval_rl_... |
def from_struct ( klass , struct , timezone = pytz . UTC ) :
"""Returns MayaDT instance from a 9 - tuple struct
It ' s assumed to be from gmtime ( ) .""" | struct_time = time . mktime ( struct ) - utc_offset ( struct )
dt = Datetime . fromtimestamp ( struct_time , timezone )
return klass ( klass . __dt_to_epoch ( dt ) ) |
def search_maintenance_window_entities ( self , ** kwargs ) : # noqa : E501
"""Search over a customer ' s maintenance windows # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . searc... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . search_maintenance_window_entities_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . search_maintenance_window_entities_with_http_info ( ** kwargs )
# noqa : E501
return data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.