signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def beforeRender ( self , ctx ) :
"""Implement this hook to initialize the L { initialPerson } and
L { initialState } slots with information from the request url ' s query
args .""" | # see the comment in Organizer . urlForViewState which suggests an
# alternate implementation of this kind of functionality .
request = inevow . IRequest ( ctx )
if not set ( [ 'initial-person' , 'initial-state' ] ) . issubset ( set ( request . args ) ) :
return
initialPersonName = request . args [ 'initial-person'... |
def dereference_recursive ( cls , repo , ref_path ) :
""": return : hexsha stored in the reference at the given ref _ path , recursively dereferencing all
intermediate references as required
: param repo : the repository containing the reference at ref _ path""" | while True :
hexsha , ref_path = cls . _get_ref_info ( repo , ref_path )
if hexsha is not None :
return hexsha |
def find_all_matches ( text_log_error , matchers ) :
"""Find matches for the given error using the given matcher classes
Returns * unsaved * TextLogErrorMatch instances .""" | for matcher_func in matchers :
matches = matcher_func ( text_log_error )
# matches : iterator of ( score , ClassifiedFailure . id )
if not matches :
continue
for score , classified_failure_id in matches :
yield TextLogErrorMatch ( score = score , matcher_name = matcher_func . __name__ , ... |
def plate_exchanger_identifier ( self ) :
'''Method to create an identifying string in format ' L ' + wavelength +
' A ' + amplitude + ' B ' + chevron angle - chevron angle . Wavelength and
amplitude are specified in units of mm and rounded to two decimal places .''' | s = ( 'L' + str ( round ( self . wavelength * 1000 , 2 ) ) + 'A' + str ( round ( self . amplitude * 1000 , 2 ) ) + 'B' + '-' . join ( [ str ( i ) for i in self . chevron_angles ] ) )
return s |
def handle ( self , dict ) :
'''Processes a vaild stats request
@ param dict : a valid dictionary object''' | # format key
key = "statsrequest:{stats}:{appid}" . format ( stats = dict [ 'stats' ] , appid = dict [ 'appid' ] )
self . redis_conn . set ( key , dict [ 'uuid' ] )
dict [ 'parsed' ] = True
dict [ 'valid' ] = True
self . logger . info ( 'Added stat request to Redis' , extra = dict ) |
def _kernel ( kernel_spec ) :
"""Expands the kernel spec into a length 2 list .
Args :
kernel _ spec : An integer or a length 1 or 2 sequence that is expanded to a
list .
Returns :
A length 2 list .""" | if isinstance ( kernel_spec , tf . compat . integral_types ) :
return [ kernel_spec , kernel_spec ]
elif len ( kernel_spec ) == 1 :
return [ kernel_spec [ 0 ] , kernel_spec [ 0 ] ]
else :
assert len ( kernel_spec ) == 2
return kernel_spec |
def actor2ImageData ( actor , spacing = ( 1 , 1 , 1 ) ) :
"""Convert a mesh it into volume representation as ` ` vtkImageData ` `
where the foreground ( exterior ) voxels are 1 and the background
( interior ) voxels are 0.
Internally the ` ` vtkPolyDataToImageStencil ` ` class is used .
. . hint : : | mesh2... | # https : / / vtk . org / Wiki / VTK / Examples / Cxx / PolyData / PolyDataToImageData
pd = actor . polydata ( )
whiteImage = vtk . vtkImageData ( )
bounds = pd . GetBounds ( )
whiteImage . SetSpacing ( spacing )
# compute dimensions
dim = [ 0 , 0 , 0 ]
for i in [ 0 , 1 , 2 ] :
dim [ i ] = int ( np . ceil ( ( bound... |
def setns ( fd , nstype ) :
"""Reassociate thread with a namespace
: param fd int : The file descriptor referreing to one of the namespace
entries in a : directory : : ` / proc / < pid > / ns / ` directory .
: param nstype int : The type of namespace the calling thread should be
reasscoiated with .""" | res = lib . setns ( fd , nstype )
if res != 0 :
_check_error ( ffi . errno ) |
def _load ( self , scale = 0.001 ) :
"""Load the Sentinel - 2 MSI relative spectral responses""" | with open_workbook ( self . path ) as wb_ :
for sheet in wb_ . sheets ( ) :
if sheet . name not in SHEET_HEADERS . keys ( ) :
continue
plt_short_name = PLATFORM_SHORT_NAME . get ( self . platform_name )
if plt_short_name != SHEET_HEADERS . get ( sheet . name ) :
conti... |
def flatten ( in_list ) :
"""given a list of values in _ list , flatten returns the list obtained by
flattening the top - level elements of in _ list .""" | out_list = [ ]
for val in in_list :
if isinstance ( val , list ) :
out_list . extend ( val )
else :
out_list . append ( val )
return out_list |
def static_absolute_tag ( context , path ) :
"""Return the absolute URL of a static file .
Usage : ` ` { % % } ` `""" | request = context . get ( "request" )
return urljoin ( request . ABSOLUTE_ROOT , static_url ( path ) ) |
def contract_hash_to_address ( self , contract_hash ) :
"""Returns address of the corresponding hash by searching the leveldb
: param contract _ hash : Hash to be searched""" | if not re . match ( r"0x[a-fA-F0-9]{64}" , contract_hash ) :
raise CriticalError ( "Invalid address hash. Expected format is '0x...'." )
print ( self . leveldb . contract_hash_to_address ( contract_hash ) ) |
def _select ( self , pointer ) :
"""Get a YAMLChunk referenced by a pointer .""" | return YAMLChunk ( self . _ruamelparsed , pointer = pointer , label = self . _label , strictparsed = self . _strictparsed , key_association = copy ( self . _key_association ) , ) |
def listen ( self ) :
"""Self - host using ' bind ' and ' port ' from the WSGI config group .""" | msgtmpl = ( u'Serving on host %(host)s:%(port)s' )
host = CONF . wsgi . wsgi_host
port = CONF . wsgi . wsgi_port
LOG . info ( msgtmpl , { 'host' : host , 'port' : port } )
server_cls = self . _get_server_cls ( host )
httpd = simple_server . make_server ( host , port , self . app , server_cls )
httpd . serve_forever ( ) |
def handle_token ( cls , parser , token ) :
"""Class method to parse get _ comment _ list / count / form and return a Node .""" | tokens = token . contents . split ( )
if tokens [ 1 ] != 'for' :
raise template . TemplateSyntaxError ( "Second argument in %r tag must be 'for'" % tokens [ 0 ] )
# { % get _ whatever for obj as varname % }
if len ( tokens ) == 5 :
if tokens [ 3 ] != 'as' :
raise template . TemplateSyntaxError ( "Third ... |
def record ( self , record = True , tag = None ) :
"""Enable / disable recording .
Return a coroutine .""" | path = '/startvideo?force=1' if record else '/stopvideo?force=1'
if record and tag is not None :
path = '/startvideo?force=1&tag={}' . format ( URL ( tag ) . raw_path )
return self . _request ( path ) |
def K_chol ( self ) :
"""Cholesky of the prior covariance K""" | if self . _K_chol is None :
self . _K_chol = jitchol ( self . _K )
return self . _K_chol |
def check_required_params ( self ) :
"""Check if all required parameters are set""" | for param in self . REQUIRED_FIELDS :
if param not in self . params :
raise ValidationError ( "Missing parameter: {} for {}" . format ( param , self . __class__ . path ) )
for child in self . TASKS :
for param in child . REQUIRED_FIELDS :
if param not in self . params :
raise Validat... |
def check ( state_engine , nameop , block_id , checked_ops ) :
"""Given a NAME _ IMPORT nameop , see if we can import it .
* the name must be well - formed
* the namespace must be revealed , but not ready
* the name cannot have been imported yet
* the sender must be the same as the namespace ' s sender
Se... | from . . nameset import BlockstackDB
name = str ( nameop [ 'name' ] )
sender = str ( nameop [ 'sender' ] )
sender_pubkey = None
recipient = str ( nameop [ 'recipient' ] )
recipient_address = str ( nameop [ 'recipient_address' ] )
preorder_hash = hash_name ( nameop [ 'name' ] , sender , recipient_address )
log . debug (... |
def _rnaseq_checkpoints ( samples ) :
"""Check sample configuration to identify required steps in analysis .""" | checkpoints = { }
checkpoints [ "rnaseq" ] = True
checkpoints [ "vc" ] = any ( [ dd . get_variantcaller ( d ) for d in samples ] )
return checkpoints |
def _to_ctfile_bond_block ( self , key ) :
"""Create bond block in ` CTfile ` format .
: param str key : Ctab atom block key .
: return : Ctab bond block .
: rtype : : py : class : ` str `""" | counter = OrderedCounter ( Bond . bond_block_format )
ctab_bond_block = '\n' . join ( [ '' . join ( [ str ( value ) . rjust ( spacing ) for value , spacing in zip ( bond . _ctab_data . values ( ) , counter . values ( ) ) ] ) for bond in self [ key ] ] )
return '{}\n' . format ( ctab_bond_block ) |
def unique ( _list ) :
"""Makes the list have unique items only and maintains the order
list ( set ( ) ) won ' t provide that
: type _ list list
: rtype : list""" | ret = [ ]
for item in _list :
if item not in ret :
ret . append ( item )
return ret |
def valid_remainder ( cntxt : Context , n : Node , matchables : RDFGraph , S : ShExJ . Shape ) -> bool :
"""Let * * outs * * be the arcsOut in remainder : ` outs = remainder ∩ arcsOut ( G , n ) ` .
Let * * matchables * * be the triples in outs whose predicate appears in a TripleConstraint in ` expression ` . If
... | # TODO : Update this and satisfies to address the new algorithm
# Let * * outs * * be the arcsOut in remainder : ` outs = remainder ∩ arcsOut ( G , n ) ` .
outs = arcsOut ( cntxt . graph , n ) . intersection ( matchables )
# predicates that in a TripleConstraint in ` expression `
predicates = predicates_in_expression (... |
def make_bigint_autoincrement_column ( column_name : str , dialect : Dialect ) -> Column :
"""Returns an instance of : class : ` Column ` representing a : class : ` BigInteger `
` ` AUTOINCREMENT ` ` column in the specified : class : ` Dialect ` .""" | # noinspection PyUnresolvedReferences
if dialect . name == SqlaDialectName . MSSQL :
return Column ( column_name , BigInteger , Sequence ( 'dummy_name' , start = 1 , increment = 1 ) )
else : # return Column ( column _ name , BigInteger , autoincrement = True )
# noinspection PyUnresolvedReferences
raise Asserti... |
def run_spider ( spider_cls , ** kwargs ) :
"""Runs a spider and returns the scraped items ( by default ) .
Parameters
spider _ cls : scrapy . Spider
A spider class to run .
capture _ items : bool ( default : True )
If enabled , the scraped items are captured and returned .
return _ crawler : bool ( def... | timeout = kwargs . pop ( 'timeout' , DEFAULT_TIMEOUT )
return wait_for ( timeout , _run_spider_in_reactor , spider_cls , ** kwargs ) |
def context_factory ( apply_globally = False , api = None ) :
"""A decorator that registers a single hug context factory""" | def decorator ( context_factory_ ) :
if apply_globally :
hug . defaults . context_factory = context_factory_
else :
apply_to_api = hug . API ( api ) if api else hug . api . from_object ( context_factory_ )
apply_to_api . context_factory = context_factory_
return context_factory_
retu... |
def read ( self , module_name ) :
"""Read a particular config file
Parameters
module _ name : String
The analysis _ path of the module for which a config is to be read ( priors relate one to one with configs ) .""" | self . parser . read ( "{}/{}.ini" . format ( self . path , module_name . split ( "." ) [ - 1 ] ) ) |
def sample ( self , data , interval ) :
'''Sample a patch from the data object
Parameters
data : dict
A data dict as produced by pumpp . Pump . transform
interval : slice
The time interval to sample
Returns
data _ slice : dict
` data ` restricted to ` interval ` .''' | data_slice = dict ( )
for key in data :
if '_valid' in key :
continue
index = [ slice ( None ) ] * data [ key ] . ndim
# if we have multiple observations for this key , pick one
index [ 0 ] = self . rng . randint ( 0 , data [ key ] . shape [ 0 ] )
index [ 0 ] = slice ( index [ 0 ] , index [ ... |
def get_all_groups ( self , names = None , max_records = None , next_token = None ) :
"""Returns a full description of each Auto Scaling group in the given
list . This includes all Amazon EC2 instances that are members of the
group . If a list of names is not provided , the service returns the full
details of... | params = { }
if max_records :
params [ 'MaxRecords' ] = max_records
if next_token :
params [ 'NextToken' ] = next_token
if names :
self . build_list_params ( params , names , 'AutoScalingGroupNames' )
return self . get_list ( 'DescribeAutoScalingGroups' , params , [ ( 'member' , AutoScalingGroup ) ] ) |
def _get_error_message ( response ) :
"""Attempt to extract an error message from response body""" | try :
data = response . json ( )
if "error_description" in data :
return data [ 'error_description' ]
if "error" in data :
return data [ 'error' ]
except Exception :
pass
return "Unknown error" |
def netconf_confirmed_commit_timeout ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
netconf_confirmed_commit = ET . SubElement ( config , "netconf-confirmed-commit" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-notifications" )
timeout = ET . SubElement ( netconf_confirmed_commit , "timeout" )
timeout . text = kwargs . pop ( 'timeout' )
callback = kwargs . pop ... |
def path ( self , path ) :
"""Setter method ; for a description see the getter method .""" | # pylint : disable = attribute - defined - outside - init
self . _path = copy_ . copy ( path )
# The provided path is shallow copied ; it does not have any attributes
# with mutable types .
# We perform this check after the initialization to avoid errors
# in test tools that show the object with repr ( ) .
assert isins... |
def glymur_config ( ) :
"""Try to ascertain locations of openjp2 , openjpeg libraries .
Returns
tuple
tuple of library handles""" | handles = ( load_openjpeg_library ( x ) for x in [ 'openjp2' , 'openjpeg' ] )
handles = tuple ( handles )
if all ( handle is None for handle in handles ) :
msg = "Neither the openjp2 nor the openjpeg library could be loaded. "
warnings . warn ( msg )
return handles |
def _local_decode ( self ) :
"""Finds the index of the maximum values for all the single node dual objectives .
Reference :
code presented by Sontag in 2012 here : http : / / cs . nyu . edu / ~ dsontag / code / README _ v2 . html""" | # The current assignment of the single node factors is stored in the form of a dictionary
decoded_result_assignment = { node : np . argmax ( self . objective [ node ] . values ) for node in self . objective if len ( node ) == 1 }
# Use the original cluster _ potentials of each factor to find the primal integral value .... |
def plus_replacement ( random , population , parents , offspring , args ) :
"""Performs " plus " replacement .
This function performs " plus " replacement , which means that
the entire existing population is replaced by the best
population - many elements from the combined set of parents and
offspring .
.... | pool = list ( offspring )
pool . extend ( parents )
pool . sort ( reverse = True )
survivors = pool [ : len ( population ) ]
return survivors |
def all_up ( self ) :
"""Get the root object of this comparison .
( This is a convenient wrapper for following the up attribute as often as you can . )
: rtype : DiffLevel""" | level = self
while level . up :
level = level . up
return level |
def dump ( self , obj , fp ) :
"""Serializes obj as an avro - format byte stream to the provided
fp file - like object stream .""" | if not validate ( obj , self . _raw_schema ) :
raise AvroTypeException ( self . _avro_schema , obj )
fastavro_write_data ( fp , obj , self . _raw_schema ) |
def safe_makedirs ( path , uid = - 1 , gid = - 1 ) :
"""create path recursively if it doesn ' t exist""" | try :
os . makedirs ( path )
except OSError as e :
if e . errno == errno . EEXIST :
pass
else :
raise
else :
os . chown ( path , uid , gid ) |
def _construct_control_flow_slice ( self , simruns ) :
"""Build a slice of the program without considering the effect of data dependencies .
This is an incorrect hack , but it should work fine with small programs .
: param simruns : A list of SimRun targets . You probably wanna get it from the CFG somehow . It ... | # TODO : Support context - sensitivity !
if self . _cfg is None :
l . error ( 'Please build CFG first.' )
cfg = self . _cfg . graph
for simrun in simruns :
if simrun not in cfg :
l . error ( 'SimRun instance %s is not in the CFG.' , simrun )
stack = [ ]
for simrun in simruns :
stack . append ( simru... |
def filter ( filter_creator ) :
"""Creates a decorator that can be used as a filter .
. . warning : :
This is currently not compatible with most other decorators , if
you are using a decorator that isn ' t part of ` hurler ` you should
take caution .""" | filter_func = [ None ]
def function_getter ( function ) :
if isinstance ( function , Filter ) :
function . add_filter ( filter )
return function
else :
return Filter ( filter = filter_func [ 0 ] , callback = function , )
def filter_decorator ( * args , ** kwargs ) :
filter_function =... |
def to_type ( value , ptype ) :
"""Convert value to ptype""" | if ptype == 'str' :
return str ( value )
elif ptype == 'int' :
return int ( value )
elif ptype == 'float' :
return float ( value )
elif ptype == 'bool' :
if value . lower ( ) == 'true' :
return True
elif value . lower ( ) == 'false' :
return False
raise ValueError ( 'Bad bool val... |
def _extract_bitstrings ( ro_sources : List [ Optional [ Tuple [ int , int ] ] ] , buffers : Dict [ str , np . ndarray ] ) -> np . ndarray :
"""De - mux qubit readout results and assemble them into the ro - bitstrings in the correct order .
: param ro _ sources : Specification of the ro _ sources , cf
: py : fu... | # hack to extract num _ shots indirectly from the shape of the returned data
first , * rest = buffers . values ( )
num_shots = first . shape [ 0 ]
bitstrings = np . zeros ( ( num_shots , len ( ro_sources ) ) , dtype = np . int64 )
for col_idx , src in enumerate ( ro_sources ) :
if src :
qubit , meas_idx = s... |
def json_qry ( dataset , qry_str , params = { } ) :
"""Takes a json query string and returns the results
args :
dataset : RdfDataset to query against
qry _ str : query string
params : dictionary of params""" | # if qry _ str . startswith ( " $ . bf _ itemOf [ rdf _ type = bf _ Print ] . = ' print ' , \ n " ) :
# pdb . set _ trace ( )
if not '$' in qry_str :
qry_str = "." . join ( [ '$' , qry_str . strip ( ) ] )
dallor_val = params . get ( "$" , dataset )
if isinstance ( dallor_val , rdflib . URIRef ) :
dallor_val = U... |
def setXr ( self , Xr ) :
"""set genotype data of the set component""" | self . Xr = Xr
self . gp_block . covar . G = Xr |
def unset_stack_address_mapping ( self , absolute_address ) :
"""Remove a stack mapping .
: param absolute _ address : An absolute memory address , which is the base address of the stack frame to destroy .""" | if self . _stack_region_map is None :
raise SimMemoryError ( 'Stack region map is not initialized.' )
self . _stack_region_map . unmap_by_address ( absolute_address ) |
def hardware_version ( self ) :
"""Return the embedded hardware version string for this tile .
The hardware version is an up to 10 byte user readable string that is
meant to encode any necessary information about the specific hardware
that this tile is running on . For example , if you have multiple
assembl... | res = self . rpc ( 0x00 , 0x02 , result_type = ( 0 , True ) )
# Result is a string but with zero appended to the end to make it a fixed 10 byte size
binary_version = res [ 'buffer' ]
ver = ""
for x in binary_version :
if x != 0 :
ver += chr ( x )
return ver |
def _find_volumes ( self , volume_system , vstype = 'detect' ) :
"""Finds all volumes based on the pytsk3 library .""" | try : # noinspection PyUnresolvedReferences
import pytsk3
except ImportError :
logger . error ( "pytsk3 not installed, could not detect volumes" )
raise ModuleNotFoundError ( "pytsk3" )
baseimage = None
try : # ewf raw image is now available on base mountpoint
# either as ewf1 file or as . dd file
raw_p... |
def write_version_file ( self , version_file_path , tstamp , svnpath , svnrev , version ) :
"""Args :
version _ file _ path : tstamp : svnpath : svnrev : version :""" | txt = """# This file is automatically generated. Manual edits will be erased.
# When this file was generated
TIMESTAMP="{}"
# Path of the schema used in the repository
SVNPATH="{1}"
# SVN revision of the schema that was used
SVNREVISION="{2}"
# The version tag of the schema
VERSION="{3}"
""" . format ( tsta... |
def _login ( self , username , password , client_id , client_secret ) :
"""Performs login with the provided credentials""" | url = self . api_url + self . auth_token_url
auth_string = '%s:%s' % ( client_id , client_secret )
authorization = base64 . b64encode ( auth_string . encode ( ) ) . decode ( )
headers = { 'Authorization' : "Basic " + authorization , 'Content-Type' : "application/x-www-form-urlencoded" }
params = { 'username' : str ( us... |
def jac ( x , a ) :
"""Jacobian matrix given Christophe ' s suggestion of f""" | return ( x - a ) / np . sqrt ( ( ( x - a ) ** 2 ) . sum ( 1 ) ) [ : , np . newaxis ] |
def cmd_dropobject ( self , obj ) :
'''drop an object on the map''' | latlon = self . module ( 'map' ) . click_position
if self . last_click is not None and self . last_click == latlon :
return
self . last_click = latlon
if latlon is not None :
obj . setpos ( latlon [ 0 ] , latlon [ 1 ] )
self . aircraft . append ( obj ) |
def _serialize ( self , value , attr , obj ) :
"""Convert the Arrow object into a string .""" | if isinstance ( value , arrow . arrow . Arrow ) :
value = value . datetime
return super ( ArrowField , self ) . _serialize ( value , attr , obj ) |
def attach_video ( self , video : typing . Union [ InputMediaVideo , base . InputFile ] , thumb : typing . Union [ base . InputFile , base . String ] = None , caption : base . String = None , width : base . Integer = None , height : base . Integer = None , duration : base . Integer = None ) :
"""Attach video
: pa... | if not isinstance ( video , InputMedia ) :
video = InputMediaVideo ( media = video , thumb = thumb , caption = caption , width = width , height = height , duration = duration )
self . attach ( video ) |
def rollback ( self ) :
"""It will rollback all changes and go to the * original _ config *""" | logger . info ( 'Rolling back changes' )
config_text = self . compare_config ( other = self . original_config )
if len ( config_text ) > 0 :
return self . _commit ( config_text , force = True , reload_original_config = False ) |
def timing ( self , stat , time , sample_rate = 1 ) :
"""Log timing information for a single stat
> > > statsd _ client . timing ( ' some . time ' , 500)""" | stats = { stat : "%f|ms" % time }
self . send ( stats , sample_rate ) |
def fetch_events ( cursor , config , account_name ) :
"""Generator that returns the events""" | query = config [ 'indexer' ] . get ( 'query' , 'select * from events where user_agent glob \'*CloudCustodian*\'' )
for event in cursor . execute ( query ) :
event [ 'account' ] = account_name
event [ '_index' ] = config [ 'indexer' ] [ 'idx_name' ]
event [ '_type' ] = config [ 'indexer' ] . get ( 'idx_type'... |
def browse ( parent , filename = '' ) :
"""Creates a new XdkWidnow for browsing an XDK file .
: param parent | < QWidget >
filename | < str >""" | dlg = XdkWindow ( parent )
dlg . show ( )
if ( filename ) :
dlg . loadFilename ( filename ) |
def authenticate_db ( self , db , dbname , retry = True ) :
"""Returns True if we manage to auth to the given db , else False .""" | log_verbose ( "Server '%s' attempting to authenticate to db '%s'" % ( self . id , dbname ) )
login_user = self . get_login_user ( dbname )
username = None
password = None
auth_success = False
if login_user :
username = login_user [ "username" ]
if "password" in login_user :
password = login_user [ "pass... |
def _delta_time ( self , date_time ) :
"""Returns in a dict the number of days / hours / minutes and total minutes
until date _ time .""" | now = datetime . datetime . now ( tzlocal ( ) )
diff = date_time - now
days = int ( diff . days )
hours = int ( diff . seconds / 3600 )
minutes = int ( ( diff . seconds / 60 ) - ( hours * 60 ) ) + 1
total_minutes = int ( ( diff . seconds / 60 ) + ( days * 24 * 60 ) ) + 1
return { "days" : days , "hours" : hours , "minu... |
def from_sequence ( cls , seq ) :
"""Create and return a new ` ` Point ` ` instance from any iterable with 0 to
3 elements . The elements , if present , must be latitude , longitude ,
and altitude , respectively .""" | args = tuple ( islice ( seq , 4 ) )
if len ( args ) > 3 :
raise ValueError ( 'When creating a Point from sequence, it ' 'must not have more than 3 items.' )
return cls ( * args ) |
def parse_headers ( self , req , name , field ) :
"""Pull a header value from the request .""" | # Use req . get _ headers rather than req . headers for performance
return req . get_header ( name , required = False ) or core . missing |
def write_classdesc ( self , obj , parent = None ) :
"""Writes a class description
: param obj : Class description to write
: param parent :""" | if obj not in self . references : # Add reference
self . references . append ( obj )
logging . debug ( "*** Adding ref 0x%X for classdesc %s" , len ( self . references ) - 1 + self . BASE_REFERENCE_IDX , obj . name , )
self . _writeStruct ( ">B" , 1 , ( self . TC_CLASSDESC , ) )
self . _writeString ( ob... |
def query_topology_db ( self , dict_convert = False , ** req ) :
"""Query an entry to the topology DB .""" | session = db . get_session ( )
with session . begin ( subtransactions = True ) :
try : # Check if entry exists .
topo_disc = session . query ( DfaTopologyDb ) . filter_by ( ** req ) . all ( )
except orm_exc . NoResultFound :
LOG . info ( "No Topology results found for %s" , req )
return ... |
def tail ( collection , filter = None , projection = None , limit = 0 , timeout = None , aggregate = False ) :
"""A generator which will block and yield entries as they are added to a capped collection .
Only use this on capped collections ; behaviour is undefined against non - tailable cursors . Accepts a timeou... | if not collection . options ( ) . get ( 'capped' , False ) :
raise TypeError ( "Can only tail capped collections." )
# Similarly , verify that the collection isn ' t empty . Empty is bad . ( Busy loop . )
if not collection . count ( ) :
raise ValueError ( "Cowardly refusing to tail an empty collection." )
curso... |
def make_inst2 ( ) :
"""creates example data set 2""" | I , d = multidict ( { 1 : 45 , 2 : 20 , 3 : 30 , 4 : 30 } )
# demand
J , M = multidict ( { 1 : 35 , 2 : 50 , 3 : 40 } )
# capacity
c = { ( 1 , 1 ) : 8 , ( 1 , 2 ) : 9 , ( 1 , 3 ) : 14 , # { ( customer , factory ) : cost < float > }
( 2 , 1 ) : 6 , ( 2 , 2 ) : 12 , ( 2 , 3 ) : 9 , ( 3 , 1 ) : 10 , ( 3 , 2 ) : 13 , ( 3 ,... |
def _configure_app ( app_ ) :
"""Configure the Flask WSGI app .""" | app_ . url_map . strict_slashes = False
app_ . config . from_object ( default_settings )
app_ . config . from_envvar ( 'JOB_CONFIG' , silent = True )
db_url = app_ . config . get ( 'SQLALCHEMY_DATABASE_URI' )
if not db_url :
raise Exception ( 'No db_url in config' )
app_ . wsgi_app = ProxyFix ( app_ . wsgi_app )
gl... |
def _indices ( self ) :
"""Find the path _ index and node _ index that identify the given node .""" | path = self . parent
layer = path . parent
for path_index in range ( len ( layer . paths ) ) :
if path == layer . paths [ path_index ] :
for node_index in range ( len ( path . nodes ) ) :
if self == path . nodes [ node_index ] :
return Point ( path_index , node_index )
return Non... |
def petl ( self , * args , ** kwargs ) :
"""Return a PETL source object""" | import petl
t = self . resolved_url . get_resource ( ) . get_target ( )
if t . target_format == 'txt' :
return petl . fromtext ( str ( t . fspath ) , * args , ** kwargs )
elif t . target_format == 'csv' :
return petl . fromcsv ( str ( t . fspath ) , * args , ** kwargs )
else :
raise Exception ( "Can't handl... |
def remove_entry_listener ( self , registration_id ) :
"""Removes the specified entry listener . Returns silently if there is no such listener added before .
: param registration _ id : ( str ) , id of registered listener .
: return : ( bool ) , ` ` true ` ` if registration is removed , ` ` false ` ` otherwise ... | return self . _stop_listening ( registration_id , lambda i : replicated_map_remove_entry_listener_codec . encode_request ( self . name , i ) ) |
def get_enabled_hook_plugins ( self , hook , args , ** kwargs ) :
"""Get enabled plugins for specified hook name .""" | manager = self . hook_managers [ hook ]
if len ( list ( manager ) ) == 0 :
return [ ]
return [ plugin for plugin in manager . map ( self . _create_hook_plugin , args , ** kwargs ) if plugin is not None ] |
def clean_text ( self , number , countries = None , country = None , ** kwargs ) :
"""Parse a phone number and return in international format .
If no valid phone number can be detected , None is returned . If
a country code is supplied , this will be used to infer the
prefix .
https : / / github . com / dav... | for code in self . _clean_countries ( countries , country ) :
try :
num = parse_number ( number , code )
if is_possible_number ( num ) :
if is_valid_number ( num ) :
return format_number ( num , PhoneNumberFormat . E164 )
except NumberParseException :
pass |
def get ( self , url , store_on_error = False , xpath = None , rate_limit = None , log_hits = True , log_misses = True ) :
"""Get a URL via the cache .
If the URL exists in the cache , return the cached value . Otherwise perform the request ,
store the resulting content in the cache and return it .
Throws a :... | try : # get cached request - if none is found , this throws a NoResultFound exception
cached = self . _query ( url , xpath ) . one ( )
if log_hits :
config . logger . info ( "Request cache hit: " + url )
# if the cached value is from a request that resulted in an error , throw an exception
if ca... |
def clone ( self , screen , scene ) :
"""Create a clone of this Dialog into a new Screen .
: param screen : The new Screen object to clone into .
: param scene : The new Scene object to clone into .""" | # Only clone the object if the function is safe to do so .
if self . _on_close is None or isfunction ( self . _on_close ) :
scene . add_effect ( PopUpDialog ( screen , self . _text , self . _buttons , self . _on_close ) ) |
def reserve_position ( fp , fmt = 'I' ) :
"""Reserves the current position for write .
Use with ` write _ position ` .
: param fp : file - like object
: param fmt : format of the reserved position
: return : the position""" | position = fp . tell ( )
fp . seek ( struct . calcsize ( str ( '>' + fmt ) ) , 1 )
return position |
def filter_mc_sharemem ( filename , step_size , box_size , cores , shape , nslice = None , domask = True ) :
"""Calculate the background and noise images corresponding to the input file .
The calculation is done via a box - car approach and uses multiple cores and shared memory .
Parameters
filename : str
F... | if cores is None :
cores = multiprocessing . cpu_count ( )
if ( nslice is None ) or ( cores == 1 ) :
nslice = cores
img_y , img_x = shape
# initialise some shared memory
global ibkg
# bkg = np . ctypeslib . as _ ctypes ( np . empty ( shape , dtype = np . float32 ) )
# ibkg = multiprocessing . sharedctypes . Arr... |
def pick_input_v1 ( self ) :
"""Updates | Input | based on | Total | .""" | flu = self . sequences . fluxes . fastaccess
inl = self . sequences . inlets . fastaccess
flu . input = 0.
for idx in range ( inl . len_total ) :
flu . input += inl . total [ idx ] [ 0 ] |
def CryptUnprotectData ( data , optional_entropy = None , prompt_struct = None , flags = 0 ) :
"""Returns a tuple of ( description , data ) where description is the
the description that was passed to the CryptProtectData call and
data is the decrypted result .""" | data_in = DATA_BLOB ( data )
entropy = DATA_BLOB ( optional_entropy ) if optional_entropy else None
data_out = DATA_BLOB ( )
ptr_description = wintypes . LPWSTR ( )
res = _CryptUnprotectData ( data_in , ctypes . byref ( ptr_description ) , entropy , None , # reserved
prompt_struct , flags | CRYPTPROTECT_UI_FORBIDDEN , ... |
def trim_core ( self ) :
"""This method trims a previously extracted unsatisfiable
core at most a given number of times . If a fixed point is
reached before that , the method returns .""" | for i in range ( self . trim ) : # call solver with core assumption only
# it must return ' unsatisfiable '
self . oracle . solve ( assumptions = self . core )
# extract a new core
new_core = self . oracle . get_core ( )
if len ( new_core ) == len ( self . core ) : # stop if new core is not better than ... |
def load_data_file ( fname , directory = None , force_download = False ) :
"""Get a standard vispy demo data file
Parameters
fname : str
The filename on the remote ` ` demo - data ` ` repository to download ,
e . g . ` ` ' molecular _ viewer / micelle . npy ' ` ` . These correspond to paths
on ` ` https :... | _url_root = 'http://github.com/vispy/demo-data/raw/master/'
url = _url_root + fname
if directory is None :
directory = config [ 'data_path' ]
if directory is None :
raise ValueError ( 'config["data_path"] is not defined, ' 'so directory must be supplied' )
fname = op . join ( directory , op . normcase (... |
def placeholder ( type_ ) :
"""Returns the EmptyVal instance for the given type""" | typetuple = type_ if isinstance ( type_ , tuple ) else ( type_ , )
if any in typetuple :
typetuple = any
if typetuple not in EMPTY_VALS :
EMPTY_VALS [ typetuple ] = EmptyVal ( typetuple )
return EMPTY_VALS [ typetuple ] |
def _set_folium_map ( self ) :
"""A map containing only the feature .""" | m = Map ( features = [ self ] , width = self . _width , height = self . _height )
self . _folium_map = m . draw ( ) |
def _get_xml_version ( element ) :
"""Extracts a list of versions that an xml element references . Returns
a [ 1 ] list if there isn ' t a versions attribute .""" | if "versions" in element . attrib :
result = [ int ( v ) for v in re . split ( ",\s*" , element . attrib [ "versions" ] ) ]
else :
result = [ 1 ]
return result |
def encode_exception ( exception ) :
"""Encode exception to a form that can be passed around and serialized .
This will grab the stack , then strip off the last two calls which are
encode _ exception and the function that called it .""" | import sys
return AsyncException ( unicode ( exception ) , exception . args , sys . exc_info ( ) , exception ) |
def is_full ( cm , nodes1 , nodes2 ) :
"""Test connectivity of one set of nodes to another .
Args :
cm ( ` ` np . ndarrray ` ` ) : The connectivity matrix
nodes1 ( tuple [ int ] ) : The nodes whose outputs to ` ` nodes2 ` ` will be
tested .
nodes2 ( tuple [ int ] ) : The nodes whose inputs from ` ` nodes1... | if not nodes1 or not nodes2 :
return True
cm = cm [ np . ix_ ( nodes1 , nodes2 ) ]
# Do all nodes have at least one connection ?
return cm . sum ( 0 ) . all ( ) and cm . sum ( 1 ) . all ( ) |
def start ( self , stages = None ) :
"""Makes the ` ` Piper ` ` ready to return results . This involves starting the
the provided ` ` NuMap ` ` instance . If multiple ` ` Pipers ` ` share a
` ` NuMap ` ` instance the order in which these ` ` Pipers ` ` are started is
important . The valid order is upstream be... | # defaults differ linear vs . parallel
stages = stages or ( ( 0 , ) if self . imap is imap else ( 0 , 1 , 2 ) )
if not self . connected :
self . log . error ( 'Piper %s is not connected.' % self )
raise PiperError ( 'Piper %s is not connected.' % self )
if not self . started :
if 0 in stages :
self ... |
def _choose_dialect ( dialects ) :
"""Given a list of dialects , choose the one to use as the " canonical " version .
If ` dialects ` is an empty list , then use the default GFF3 dialect
Parameters
dialects : iterable
iterable of dialect dictionaries
Returns
dict""" | # NOTE : can use helpers . dialect _ compare if you need to make this more
# complex . . . .
# For now , this function favors the first dialect , and then appends the
# order of additional fields seen in the attributes of other lines giving
# priority to dialects that come first in the iterable .
if len ( dialects ) ==... |
def by_col ( cls , df , e , b , inplace = False , ** kwargs ) :
"""Compute smoothing by columns in a dataframe .
Parameters
df : pandas . DataFrame
a dataframe containing the data to be smoothed
e : string or list of strings
the name or names of columns containing event variables to be
smoothed
b : st... | if not inplace :
new = df . copy ( )
cls . by_col ( new , e , b , inplace = True , ** kwargs )
return new
if isinstance ( e , str ) :
e = [ e ]
if isinstance ( b , str ) :
b = [ b ]
if len ( b ) == 1 and len ( e ) > 1 :
b = b * len ( e )
try :
assert len ( e ) == len ( b )
except AssertionEr... |
def query_orders ( self , accounts , status = 'filled' ) :
"""查询订单
Arguments :
accounts { [ type ] } - - [ description ]
Keyword Arguments :
status { str } - - ' open ' 待成交 ' filled ' 成交 ( default : { ' filled ' } )
Returns :
[ type ] - - [ description ]""" | try :
data = self . call ( "orders" , { 'client' : accounts , 'status' : status } )
if data is not None :
orders = data . get ( 'dataTable' , False )
order_headers = orders [ 'columns' ]
if ( '成交状态' in order_headers or '状态说明' in order_headers ) and ( '备注' in order_headers ) :
... |
def dragMoveEvent ( self , event ) :
"""Processes the drag drop event using the filter set by the \
setDragDropFilter
: param event | < QDragEvent >""" | filt = self . dragDropFilter ( )
if ( not filt ) :
super ( XCalendarWidget , self ) . dragMoveEvent ( event )
return
filt ( self , event ) |
def run_evolution ( path , name , E0 , laser_frequencies , N_iter , dt , N_states , spectrum_of_laser = None , N_delta = None , frequency_step = None , frequency_end = None , rho0 = None , print_steps = False , integrate = False , save_systems = False , save_eigenvalues = False , rk4 = False , use_netcdf = True ) :
... | def py2f_bool ( bool_var ) :
if bool_var :
return ".true.\n"
else :
return ".false.\n"
if rk4 :
return run_rk4 ( path , name , E0 , laser_frequencies , N_iter , dt , N_states , spectrum_of_laser = spectrum_of_laser , N_delta = N_delta , frequency_step = frequency_step , frequency_end = frequ... |
def mul ( self , x , axis ) :
"""Function to multiply 3D View with vector or 2D array ( type = numpy . ndarray or 2D Field or 2D View ) or 2D View with vector ( type = numpy . ndarray )
: param x : array ( 1D , 2D ) or field ( 2D ) or View ( 2D )
: param axis : specifies axis , eg . axis = ( 1,2 ) plane lies in... | return self . __array_op ( operator . mul , x , axis ) |
def maybe_rate_limit ( client , headers , atexit = False ) :
"""Optionally pause the process based on suggested rate interval .""" | # pylint : disable = fixme
# pylint : disable = global - statement
# FIXME : Yes , I know this is not great . We ' ll fix it later . : - )
global LAST_CLIENT , LAST_HEADERS
if LAST_CLIENT and LAST_HEADERS : # Wait based on previous client / headers
rate_limit ( LAST_CLIENT , LAST_HEADERS , atexit = atexit )
LAST_CL... |
def crop ( self , lat , lon , var ) :
"""Crop a subset of the dataset for each var
Given doy , depth , lat and lon , it returns the smallest subset
that still contains the requested coordinates inside it .
It handels special cases like a region around greenwich and
the international date line .
Accepts 0 ... | dims , idx = cropIndices ( self . dims , lat , lon )
subset = { }
for v in var :
subset = { v : self . ncs [ 0 ] [ v ] [ idx [ 'yn' ] , idx [ 'xn' ] ] }
return subset , dims |
def get ( self , name ) :
"""Retrieve a plugin by name .""" | try :
return self . plugins [ name ]
except KeyError :
raise RuntimeError ( "plugin {} does not exist" . format ( name ) ) |
def build_from_paths ( paths : List [ str ] , num_words : Optional [ int ] = None , min_count : int = 1 , pad_to_multiple_of : Optional [ int ] = None ) -> Vocab :
"""Creates vocabulary from paths to a file in sentence - per - line format . A sentence is just a whitespace delimited
list of tokens . Note that spec... | with ExitStack ( ) as stack :
logger . info ( "Building vocabulary from dataset(s): %s" , paths )
files = ( stack . enter_context ( utils . smart_open ( path ) ) for path in paths )
return build_vocab ( chain ( * files ) , num_words , min_count , pad_to_multiple_of ) |
def traverse ( fn , expr , type = ir . Expr , container = Stack ) :
"""Utility for generic expression tree traversal
Parameters
fn : Callable [ [ ir . Expr ] , Tuple [ Union [ Boolean , Iterable ] , Any ] ]
This function will be applied on each expressions , it must
return a tuple . The first element of the... | args = expr if isinstance ( expr , collections . abc . Iterable ) else [ expr ]
todo = container ( arg for arg in args if isinstance ( arg , type ) )
seen = set ( )
while todo :
expr = todo . get ( )
op = expr . op ( )
if op in seen :
continue
else :
seen . add ( op )
control , resul... |
def remove ( self , fact ) :
"""Create an INVALID token and send it to all children .""" | token = Token . invalid ( fact )
MATCHER . debug ( "<BusNode> added %r" , token )
for child in self . children :
child . callback ( token ) |
def get_total_size_of_queued_replicas ( ) :
"""Return the total number of bytes of requested , unprocessed replicas .""" | return ( d1_gmn . app . models . ReplicationQueue . objects . filter ( local_replica__info__status__status = 'queued' ) . aggregate ( Sum ( 'size' ) ) [ 'size__sum' ] or 0 ) |
def get_by_request_id ( env , request_id ) :
"""Search for event logs by request id""" | mgr = SoftLayer . NetworkManager ( env . client )
logs = mgr . get_event_logs_by_request_id ( request_id )
table = formatting . Table ( COLUMNS )
table . align [ 'metadata' ] = "l"
for log in logs :
metadata = json . dumps ( json . loads ( log [ 'metaData' ] ) , indent = 4 , sort_keys = True )
table . add_row (... |
def logline_timestamp_comparator ( t1 , t2 ) :
"""Comparator for timestamps in logline format .
Args :
t1 : Timestamp in logline format .
t2 : Timestamp in logline format .
Returns :
-1 if t1 < t2 ; 1 if t1 > t2 ; 0 if t1 = = t2.""" | dt1 = _parse_logline_timestamp ( t1 )
dt2 = _parse_logline_timestamp ( t2 )
for u1 , u2 in zip ( dt1 , dt2 ) :
if u1 < u2 :
return - 1
elif u1 > u2 :
return 1
return 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.