signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def list ( self ) :
"""Retrieve list of all apps
Returns :
: class : ` list ` of : class : ` ~ swimlane . core . resources . app . App ` : List of all retrieved apps""" | response = self . _swimlane . request ( 'get' , 'app' )
return [ App ( self . _swimlane , item ) for item in response . json ( ) ] |
def read_sources ( sdmname ) :
"""Use sdmpy to get all sources and ra , dec per scan as dict""" | sdm = getsdm ( sdmname )
sourcedict = { }
for row in sdm [ 'Field' ] :
src = str ( row . fieldName )
sourcenum = int ( row . sourceId )
direction = str ( row . referenceDir )
( ra , dec ) = [ float ( val ) for val in direction . split ( ' ' ) [ 3 : ] ]
# skip first two values in string
sourcedic... |
def AvgPool ( a , k , strides , padding , data_format ) :
"""Average pooling op .""" | if data_format . decode ( "ascii" ) == "NCHW" :
a = np . rollaxis ( a , 1 , - 1 ) ,
patches = _pool_patches ( a , k , strides , padding . decode ( "ascii" ) )
pool = np . average ( patches , axis = tuple ( range ( - len ( k ) , 0 ) ) )
if data_format . decode ( "ascii" ) == "NCHW" :
pool = np . rollaxis ( pool ... |
def write_string ( self , s , codec ) :
"""Write string encoding it with codec into stream""" | for i in range ( 0 , len ( s ) , self . bufsize ) :
chunk = s [ i : i + self . bufsize ]
buf , consumed = codec . encode ( chunk )
assert consumed == len ( chunk )
self . write ( buf ) |
def get_api_versions ( call = None , kwargs = None ) : # pylint : disable = unused - argument
'''Get a resource type api versions''' | if kwargs is None :
kwargs = { }
if 'resource_provider' not in kwargs :
raise SaltCloudSystemExit ( 'A resource_provider must be specified' )
if 'resource_type' not in kwargs :
raise SaltCloudSystemExit ( 'A resource_type must be specified' )
api_versions = [ ]
try :
resconn = get_conn ( client_type = '... |
def construct_mail ( recipients = None , context = None , template_base = 'emailit/email' , subject = None , message = None , site = None , subject_templates = None , body_templates = None , html_templates = None , from_email = None , language = None , ** kwargs ) :
"""usage :
construct _ mail ( [ ' my @ email . ... | language = language or translation . get_language ( )
with force_language ( language ) :
recipients = recipients or [ ]
if isinstance ( recipients , basestring ) :
recipients = [ recipients ]
from_email = from_email or settings . DEFAULT_FROM_EMAIL
subject_templates = subject_templates or get_te... |
def ip_rtm_config_route_static_route_nh_vrf_static_route_next_vrf_dest ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ip = ET . SubElement ( config , "ip" , xmlns = "urn:brocade.com:mgmt:brocade-common-def" )
rtm_config = ET . SubElement ( ip , "rtm-config" , xmlns = "urn:brocade.com:mgmt:brocade-rtm" )
route = ET . SubElement ( rtm_config , "route" )
static_route_nh_vrf = ET . SubElement ( route , "... |
def _add_data_reference ( self , irsb_addr , stmt_idx , insn_addr , data_addr , # pylint : disable = unused - argument
data_size = None , data_type = None ) :
"""Checks addresses are in the correct segments and creates or updates
MemoryData in _ memory _ data as appropriate , labelling as segment
boundaries or ... | # Make sure data _ addr is within a valid memory range
if not self . project . loader . find_segment_containing ( data_addr ) : # data might be at the end of some section or segment . . .
# let ' s take a look
for segment in self . project . loader . main_object . segments :
if segment . vaddr + segment . m... |
def deriv1 ( x , y , i , n ) :
"""alternative way to smooth the derivative of a noisy signal
using least square fit .
x = array of x axis
y = array of y axis
n = smoothing factor
i = position
in this method the slope in position i is calculated by least square fit of n points
before and after position... | m_ , x_ , y_ , xy_ , x_2 = 0. , 0. , 0. , 0. , 0.
for ix in range ( i , i + n , 1 ) :
x_ = x_ + x [ ix ]
y_ = y_ + y [ ix ]
xy_ = xy_ + x [ ix ] * y [ ix ]
x_2 = x_2 + x [ ix ] ** 2
m = old_div ( ( ( n * xy_ ) - ( x_ * y_ ) ) , ( n * x_2 - ( x_ ) ** 2 ) )
return ( m ) |
def get_events ( self , user_id , start_date = None ) :
"""Gets the event log for a specific user , default start _ date is 30 days ago
: param int id : User id to view
: param string start _ date : " % Y - % m - % dT % H : % M : % s . 0000-06:00 " is the full formatted string .
The Timezone part has to be HH... | if start_date is None :
date_object = datetime . datetime . today ( ) - datetime . timedelta ( days = 30 )
start_date = date_object . strftime ( "%Y-%m-%dT00:00:00" )
object_filter = { 'userId' : { 'operation' : user_id } , 'eventCreateDate' : { 'operation' : 'greaterThanDate' , 'options' : [ { 'name' : 'date' ... |
def spectrogram2 ( self , fftlength , overlap = None , window = 'hann' , ** kwargs ) :
"""Calculate the non - averaged power ` Spectrogram ` of this ` TimeSeries `
Parameters
fftlength : ` float `
number of seconds in single FFT .
overlap : ` float ` , optional
number of seconds of overlap between FFTs , ... | # set kwargs for periodogram ( )
kwargs . setdefault ( 'fs' , self . sample_rate . to ( 'Hz' ) . value )
# run
return spectral . spectrogram ( self , signal . periodogram , fftlength = fftlength , overlap = overlap , window = window , ** kwargs ) |
def delete_model ( self , model_name ) :
"""Delete an Amazon SageMaker Model .
Args :
model _ name ( str ) : Name of the Amazon SageMaker model to delete .""" | LOGGER . info ( 'Deleting model with name: {}' . format ( model_name ) )
self . sagemaker_client . delete_model ( ModelName = model_name ) |
def netrc_from_env ( ) -> Optional [ netrc . netrc ] :
"""Attempt to load the netrc file from the path specified by the env - var
NETRC or in the default location in the user ' s home directory .
Returns None if it couldn ' t be found or fails to parse .""" | netrc_env = os . environ . get ( 'NETRC' )
if netrc_env is not None :
netrc_path = Path ( netrc_env )
else :
try :
home_dir = Path . home ( )
except RuntimeError as e : # pragma : no cover
# if pathlib can ' t resolve home , it may raise a RuntimeError
client_logger . debug ( 'Could not ... |
def parse ( class_ , f , allow_segwit = None ) :
"""Parse a Bitcoin transaction Tx .
: param f : a file - like object that contains a binary streamed transaction
: param allow _ segwit : ( optional ) set to True to allow parsing of segwit transactions .
The default value is defined by the class variable ALLOW... | if allow_segwit is None :
allow_segwit = class_ . ALLOW_SEGWIT
txs_in = [ ]
txs_out = [ ]
version , = parse_struct ( "L" , f )
v1 = ord ( f . read ( 1 ) )
is_segwit = allow_segwit and ( v1 == 0 )
v2 = None
if is_segwit :
flag = f . read ( 1 )
if flag == b'\0' :
raise ValueError ( "bad flag in segwit... |
def acp_users_import ( ) :
"""Import users from a TSV file .""" | if not current_user . is_admin :
return error ( "Not authorized to edit users." , 401 )
if not db :
return error ( 'The ACP is not available in single-user mode.' , 500 )
form = UserImportForm ( )
if not form . validate ( ) :
return error ( "Bad Request" , 400 )
fh = request . files [ 'tsv' ] . stream
tsv =... |
def restore_point ( cls , cluster_id_label , s3_location , backup_id , table_names , overwrite = True , automatic = True ) :
"""Restoring cluster from a given hbase snapshot id""" | conn = Qubole . agent ( version = Cluster . api_version )
parameters = { }
parameters [ 's3_location' ] = s3_location
parameters [ 'backup_id' ] = backup_id
parameters [ 'table_names' ] = table_names
parameters [ 'overwrite' ] = overwrite
parameters [ 'automatic' ] = automatic
return conn . post ( cls . element_path ( ... |
def get ( self , filter_lambda = None , map_lambda = None ) :
"""Select elements of the TSV , using python filter and map .
Parameters
filter _ lambda : function
function to filter the tsv rows ( the function needs to return True / False )
map _ lambda : function
function to select the tsv columns
Retur... | if filter_lambda is None :
filter_lambda = lambda x : True
if map_lambda is None :
map_lambda = lambda x : x
return list ( map ( map_lambda , filter ( filter_lambda , self . tsv ) ) ) |
def add ( self , * a , ** ka ) :
"""Adds a route - > target pair or a Route object to the Router .
See Route ( ) for details .""" | route = a [ 0 ] if a and isinstance ( a [ 0 ] , Route ) else Route ( * a , ** ka )
self . routes . append ( route )
if route . name :
self . named [ route . name ] = route . format_str ( )
if route . static :
self . static [ route . route ] = route . target
return
gpatt = route . group_re ( )
fpatt = route ... |
def cnst_AT ( self , X ) :
r"""Compute : math : ` A ^ T \ mathbf { x } ` where : math : ` A \ mathbf { x } ` is
a component of ADMM problem constraint . In this case
: math : ` A ^ T \ mathbf { x } = ( G _ r ^ T \ ; \ ; G _ c ^ T ) \ mathbf { x } ` .""" | return np . sum ( np . concatenate ( [ sl . GTax ( X [ ... , ax ] , ax ) [ ... , np . newaxis ] for ax in self . axes ] , axis = X . ndim - 1 ) , axis = X . ndim - 1 ) |
def extract_string_pairs_in_dir ( directory , exclude_dirs , special_ui_components_prefix ) :
"""Extract string pairs in the given directory ' s xib / storyboard files .
Args :
directory ( str ) : The path to the directory .
exclude _ dirs ( str ) : A list of directories to exclude from extraction .
special... | result = [ ]
for ib_file_path in find_files ( directory , [ ".xib" , ".storyboard" ] , exclude_dirs ) :
result += extract_string_pairs_in_ib_file ( ib_file_path , special_ui_components_prefix )
return result |
def reverse_iterator ( self , symbol , chunk_range = None ) :
"""Returns a generator that accesses each chunk in descending order
Parameters
symbol : str
the symbol for the given item in the DB
chunk _ range : None , or a range object
allows you to subset the chunks by range
Returns
generator""" | sym = self . _get_symbol_info ( symbol )
if not sym :
raise NoDataFoundException ( "Symbol does not exist." )
c = CHUNKER_MAP [ sym [ CHUNKER ] ]
for chunk in list ( self . get_chunk_ranges ( symbol , chunk_range = chunk_range , reverse = True ) ) :
yield self . read ( symbol , chunk_range = c . to_range ( chun... |
def add_connection_score ( self , node ) :
"""Return a numeric value that determines this node ' s score for adding
a new connection . A negative value indicates that no connections
should be made to this node for at least that number of seconds .
A value of - inf indicates no connections should be made to th... | # TODO : this should ideally take node history into account
conntime = node . seconds_until_connect_ok ( )
if conntime > 0 :
self . log ( "not considering %r for new connection; has %r left on " "connect blackout" % ( node , conntime ) )
return - conntime
numconns = self . num_connectors_to ( node )
if numconns... |
def enum_sigma_cubic ( cutoff , r_axis ) :
"""Find all possible sigma values and corresponding rotation angles
within a sigma value cutoff with known rotation axis in cubic system .
The algorithm for this code is from reference , Acta Cryst , A40,108(1984)
Args :
cutoff ( integer ) : the cutoff of sigma val... | sigmas = { }
# make sure gcd ( r _ axis ) = = 1
if reduce ( gcd , r_axis ) != 1 :
r_axis = [ int ( round ( x / reduce ( gcd , r_axis ) ) ) for x in r_axis ]
# count the number of odds in r _ axis
odd_r = len ( list ( filter ( lambda x : x % 2 == 1 , r_axis ) ) )
# Compute the max n we need to enumerate .
if odd_r =... |
def crosscorrfunc ( freq , cross ) :
"""Calculate crosscorrelation function ( s ) for given cross spectra .
Parameters
freq : numpy . ndarray
1 dimensional array of frequencies .
cross : numpy . ndarray
2 dimensional array of cross spectra , 1st axis units , 2nd axis units ,
3rd axis frequencies .
Ret... | tbin = 1. / ( 2. * np . max ( freq ) ) * 1e3
# tbin in ms
time = np . arange ( - len ( freq ) / 2. + 1 , len ( freq ) / 2. + 1 ) * tbin
# T = max ( time )
multidata = False
# check whether cross contains many cross spectra
if len ( np . shape ( cross ) ) > 1 :
multidata = True
if multidata :
N = len ( cross )
... |
def get ( self , request ) :
"""Get a request handler based on the URL of the request , or raises an
error
: param request : Request object
: return : handler , arguments , keyword arguments""" | # No virtual hosts specified ; default behavior
if not self . hosts :
return self . _get ( request . path , request . method , "" )
# virtual hosts specified ; try to match route to the host header
try :
return self . _get ( request . path , request . method , request . headers . get ( "Host" , "" ) )
# try def... |
def _iter_backtrack ( ex , rand = False ) :
"""Iterate through all satisfying points using backtrack algorithm .""" | if ex is One :
yield dict ( )
elif ex is not Zero :
if rand :
v = random . choice ( ex . inputs ) if rand else ex . top
else :
v = ex . top
points = [ { v : 0 } , { v : 1 } ]
if rand :
random . shuffle ( points )
for point in points :
for soln in _iter_backtrack (... |
def _break_ties ( self , Y_s , break_ties = "random" ) :
"""Break ties in each row of a tensor according to the specified policy
Args :
Y _ s : An [ n , k ] np . ndarray of probabilities
break _ ties : A tie - breaking policy :
" abstain " : return an abstain vote ( 0)
" random " : randomly choose among t... | n , k = Y_s . shape
Y_h = np . zeros ( n )
diffs = np . abs ( Y_s - Y_s . max ( axis = 1 ) . reshape ( - 1 , 1 ) )
TOL = 1e-5
for i in range ( n ) :
max_idxs = np . where ( diffs [ i , : ] < TOL ) [ 0 ]
if len ( max_idxs ) == 1 :
Y_h [ i ] = max_idxs [ 0 ] + 1
# Deal with " tie votes " according to ... |
def getTreesFor ( self , document , content_type ) :
"""Provides all XML documents for that content type
@ param document : a Document or subclass object
@ param content _ type : a MIME content type
@ return : list of etree . _ ElementTree of that content type""" | # Relative path without potential leading path separator
# otherwise os . path . join doesn ' t work
for rel_path in self . overrides [ content_type ] :
if rel_path [ 0 ] in ( '/' , '\\' ) :
rel_path = rel_path [ 1 : ]
file_path = os . path . join ( document . _cache_dir , rel_path )
yield etree . p... |
def _build_service_uri ( self , base_uri , partition , name ) :
'''Build the proper uri for a service resource .
This follows the scheme :
< base _ uri > / ~ < partition > ~ < < name > . app > ~ < name >
: param base _ uri : str - - base uri for container
: param partition : str - - partition for this servi... | name = name . replace ( '/' , '~' )
return '%s~%s~%s.app~%s' % ( base_uri , partition , name , name ) |
def configure_deletefor ( self , ns , definition ) :
"""Register a delete - for relation endpoint .
The definition ' s func should be a delete function , which must :
- accept kwargs for path data
- return truthy / falsey
: param ns : the namespace
: param definition : the endpoint definition""" | @ self . add_route ( ns . relation_path , Operation . DeleteFor , ns )
@ wraps ( definition . func )
def delete ( ** path_data ) :
headers = dict ( )
response_data = dict ( )
require_response_data ( definition . func ( ** path_data ) )
definition . header_func ( headers , response_data )
response_fo... |
def import_start_event_to_graph ( diagram_graph , process_id , process_attributes , element ) :
"""Adds to graph the new element that represents BPMN start event .
Start event inherits attribute parallelMultiple from CatchEvent type
and sequence of eventDefinitionRef from Event type .
Separate methods for eac... | element_id = element . getAttribute ( consts . Consts . id )
start_event_definitions = { 'messageEventDefinition' , 'timerEventDefinition' , 'conditionalEventDefinition' , 'escalationEventDefinition' , 'signalEventDefinition' }
BpmnDiagramGraphImport . import_flow_node_to_graph ( diagram_graph , process_id , process_at... |
def decompress ( file_obj , file_type ) :
"""Given an open file object and a file type , return all components
of the archive as open file objects in a dict .
Parameters
file _ obj : file - like
Containing compressed data
file _ type : str
File extension , ' zip ' , ' tar . gz ' , etc
Returns
decomp... | def is_zip ( ) :
archive = zipfile . ZipFile ( file_obj )
result = { name : wrap_as_stream ( archive . read ( name ) ) for name in archive . namelist ( ) }
return result
def is_tar ( ) :
import tarfile
archive = tarfile . open ( fileobj = file_obj , mode = 'r' )
result = { name : archive . extra... |
def set ( self , value ) :
"""Sets the value of the string
: param value :
A unicode string""" | if not isinstance ( value , str_cls ) :
raise TypeError ( unwrap ( '''
%s value must be a unicode string, not %s
''' , type_name ( self ) , type_name ( value ) ) )
self . _unicode = value
self . contents = value . encode ( self . _encoding )
self . _header = None
if self . _indefinit... |
def recursive ( self ) :
"""When True , this CustomType has at least one member that is of the same
type as itself .""" | for m in self . members . values ( ) :
if m . kind is not None and m . kind . lower ( ) == self . name . lower ( ) :
return True
else :
return False |
def want_release ( self ) :
"""Does the user normally want to release this package .
Some colleagues find it irritating to have to remember to
answer the question " Check out the tag ( for tweaks or
pypi / distutils server upload ) " with the non - default ' no ' when
in 99 percent of the cases they just ma... | default = True
if self . config is None :
return default
try :
result = self . config . getboolean ( 'zest.releaser' , 'release' )
except ( NoSectionError , NoOptionError , ValueError ) :
return default
return result |
def s_bird ( X , scales , n_runs , p_above , p_active = 1 , max_iter = 100 , random_state = None , n_jobs = 1 , memory = Memory ( None ) , verbose = False ) :
"""Multichannel version of BIRD ( S - BIRD ) seeking Structured Sparsity
Parameters
X : array , shape ( n _ channels , n _ times )
The numpy n _ channe... | X , prepad = _pad ( X )
# Computing Lambda _ W ( Phi , p _ above )
n_channels = X . shape [ 0 ]
n_samples = float ( X . shape [ 1 ] )
# size of the full shift - invariant dictionary
M = np . sum ( np . array ( scales ) / 2 ) * n_samples
sigma = sqrt ( ( 1.0 - ( 2.0 / np . pi ) ) / float ( n_samples ) )
Lambda_W = sigma... |
def get_rotation_angle_from_sigma ( sigma , r_axis , lat_type = 'C' , ratio = None ) :
"""Find all possible rotation angle for the given sigma value .
Args :
sigma ( integer ) :
sigma value provided
r _ axis ( list of three integers , e . g . u , v , w
or four integers , e . g . u , v , t , w for hex / rh... | if lat_type . lower ( ) == 'c' :
logger . info ( 'Make sure this is for cubic system' )
sigma_dict = GrainBoundaryGenerator . enum_sigma_cubic ( cutoff = sigma , r_axis = r_axis )
elif lat_type . lower ( ) == 't' :
logger . info ( 'Make sure this is for tetragonal system' )
if ratio is None :
lo... |
def _compute_symbolic_link_mapping ( directory : str , extensions : Iterable [ str ] ) -> Dict [ str , str ] :
"""Given a shared analysis directory , produce a mapping from actual source files
to files contained within this directory . Only includes files which have
one of the provided extensions .
Watchman w... | symbolic_links = { }
try :
for symbolic_link in find_paths_with_extensions ( directory , extensions ) :
symbolic_links [ os . path . realpath ( symbolic_link ) ] = symbolic_link
except subprocess . CalledProcessError as error :
LOG . warning ( "Exception encountered trying to find source files " "in the... |
def publish_avatar_set ( self , avatar_set ) :
"""Make ` avatar _ set ` the current avatar of the jid associated with this
connection .
If : attr : ` synchronize _ vcard ` is true and PEP is available the
vCard is only synchronized if the PEP update is successful .
This means publishing the ` ` image / png ... | id_ = avatar_set . png_id
done = False
with ( yield from self . _publish_lock ) :
if ( yield from self . _pep . available ( ) ) :
yield from self . _pep . publish ( namespaces . xep0084_data , avatar_xso . Data ( avatar_set . image_bytes ) , id_ = id_ )
yield from self . _pep . publish ( namespaces ... |
def resolve_links ( self ) :
"""Attempt to resolve all internal links ( locally ) .
In case the linked resources are found either as members of the array or within
the ` includes ` element , those will be replaced and reference the actual resources .
No network calls will be performed .""" | for resource in self . items_mapped [ 'Entry' ] . values ( ) :
for dct in [ getattr ( resource , '_cf_cda' , { } ) , resource . fields ] :
for k , v in dct . items ( ) :
if isinstance ( v , ResourceLink ) :
resolved = self . _resolve_resource_link ( v )
if resolve... |
def _handle_http_error ( self , url , response_obj , status_code , psp_ref , raw_request , raw_response , headers , message ) :
"""This function handles the non 200 responses from Adyen , raising an
error that should provide more information .
Args :
url ( str ) : url of the request
response _ obj ( dict ) ... | if status_code == 404 :
if url == self . merchant_specific_url :
erstr = "Received a 404 for url:'{}'. Please ensure that" " the custom merchant specific url is correct" . format ( url )
raise AdyenAPICommunicationError ( erstr , error_code = response_obj . get ( "errorCode" ) )
else :
e... |
def connection ( self ) :
"""Provide the connection parameters for kombu ' s ConsumerMixin .
The ` Connection ` object is a declaration of connection parameters
that is lazily evaluated . It doesn ' t represent an established
connection to the broker at this point .""" | heartbeat = self . container . config . get ( HEARTBEAT_CONFIG_KEY , DEFAULT_HEARTBEAT )
transport_options = self . container . config . get ( TRANSPORT_OPTIONS_CONFIG_KEY , DEFAULT_TRANSPORT_OPTIONS )
ssl = self . container . config . get ( AMQP_SSL_CONFIG_KEY )
conn = Connection ( self . amqp_uri , transport_options ... |
def draw ( self , k = 1 , random_state = None ) :
"""Returns k draws from q .
For each such draw , the value i is returned with probability
q [ i ] .
Parameters
k : scalar ( int ) , optional
Number of draws to be returned
random _ state : int or np . random . RandomState , optional
Random seed ( integ... | random_state = check_random_state ( random_state )
return self . Q . searchsorted ( random_state . uniform ( 0 , 1 , size = k ) , side = 'right' ) |
def recursive_overwrite ( src , dest , ignore = None ) :
"""Banana banana""" | if os . path . islink ( src ) :
linkto = os . readlink ( src )
if os . path . exists ( dest ) :
os . remove ( dest )
symlink ( linkto , dest )
elif os . path . isdir ( src ) :
if not os . path . isdir ( dest ) :
os . makedirs ( dest )
files = os . listdir ( src )
if ignore is not... |
def request_pick_fruit ( self , req ) :
"""Pick a random fruit .""" | r = random . choice ( self . FRUIT + [ None ] )
if r is None :
return ( "fail" , "No fruit." )
delay = random . randrange ( 1 , 5 )
req . inform ( "Picking will take %d seconds" % delay )
def pick_handler ( ) :
self . _fruit_result . set_value ( r )
req . reply ( "ok" , r )
handle_timer = threading . Timer ... |
def create ( name , availability_zones , listeners , subnets = None , security_groups = None , scheme = 'internet-facing' , region = None , key = None , keyid = None , profile = None ) :
'''Create an ELB
CLI example to create an ELB :
. . code - block : : bash
salt myminion boto _ elb . create myelb ' [ " us ... | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
if exists ( name , region , key , keyid , profile ) :
return True
if isinstance ( availability_zones , six . string_types ) :
availability_zones = salt . utils . json . loads ( availability_zones )
if isinstance ( listeners , s... |
def _add_cxnSp ( self , connector_type , begin_x , begin_y , end_x , end_y ) :
"""Return a newly - added ` p : cxnSp ` element as specified .
The ` p : cxnSp ` element is for a connector of * connector _ type *
beginning at ( * begin _ x * , * begin _ y * ) and extending to
( * end _ x * , * end _ y * ) .""" | id_ = self . _next_shape_id
name = 'Connector %d' % ( id_ - 1 )
flipH , flipV = begin_x > end_x , begin_y > end_y
x , y = min ( begin_x , end_x ) , min ( begin_y , end_y )
cx , cy = abs ( end_x - begin_x ) , abs ( end_y - begin_y )
return self . _element . add_cxnSp ( id_ , name , connector_type , x , y , cx , cy , fli... |
def sort_snps ( snps ) :
"""Sort SNPs based on ordered chromosome list and position .""" | sorted_list = sorted ( snps [ "chrom" ] . unique ( ) , key = _natural_sort_key )
# move PAR and MT to the end of the dataframe
if "PAR" in sorted_list :
sorted_list . remove ( "PAR" )
sorted_list . append ( "PAR" )
if "MT" in sorted_list :
sorted_list . remove ( "MT" )
sorted_list . append ( "MT" )
# co... |
def extract_zipfile ( archive_name , destpath ) :
"Unpack a zip file" | archive = zipfile . ZipFile ( archive_name )
archive . extractall ( destpath ) |
def _GetNextPath ( self ) :
"""Gets the next path to load from .
This function also does the checking for out - of - order writes as it iterates
through the paths .
Returns :
The next path to load events from , or None if there are no more paths .""" | paths = sorted ( path for path in io_wrapper . ListDirectoryAbsolute ( self . _directory ) if self . _path_filter ( path ) )
if not paths :
return None
if self . _path is None :
return paths [ 0 ]
# Don ' t bother checking if the paths are GCS ( which we can ' t check ) or if
# we ' ve already detected an OOO w... |
def main ( ) :
"""Parse CLI and starts main program .""" | args = docopt ( __doc__ , version = __version__ )
if args [ '--print' ] :
for section in DEFAULT_OPTIONS :
print ( "[{}]" . format ( section ) )
for key , value in DEFAULT_OPTIONS [ section ] . items ( ) :
print ( "{k} = {v}" . format ( k = key , v = value ) )
print ( )
sys .... |
def headerSortAscending ( self ) :
"""Sorts the column at the current header index by ascending order .""" | self . setSortingEnabled ( True )
self . sortByColumn ( self . _headerIndex , QtCore . Qt . AscendingOrder ) |
def getTextualNode ( self , textId , subreference = None , prevnext = False , metadata = False ) :
"""Retrieve a text node from the API
: param textId : CtsTextMetadata Identifier
: param subreference : CapitainsCtsPassage Reference
: param prevnext : Retrieve graph representing previous and next passage
: ... | if subreference :
textId = "{}:{}" . format ( textId , subreference )
if prevnext or metadata :
return self . getPassagePlus ( urn = textId )
else :
return self . getPassage ( urn = textId ) |
def start_event ( self , event_type , * args , dt = 1 / 60 ) :
"""Begin dispatching the given event at the given frequency .
Calling this method will cause an event of type * event _ type * with
arguments * args * to be dispatched every * dt * seconds . This will
continue until ` stop _ event ( ) ` is called ... | # Don ' t bother scheduling a timer if nobody ' s listening . This isn ' t
# great from a general - purpose perspective , because a long - lived event
# could have listeners attach and detach in the middle . But I don ' t
# like the idea of making a bunch of clocks to spit out a bunch of
# events that are never used , ... |
def log1p ( data , copy = False ) :
"""Logarithmize the data matrix .
Computes : math : ` X = \\ log ( X + 1 ) ` , where : math : ` log ` denotes the natural logarithm .
Parameters
data : : class : ` ~ anndata . AnnData `
Annotated data matrix .
copy : ` bool ` ( default : ` False ` )
Return a copy of `... | adata = data . copy ( ) if copy else data
X = ( adata . X . data if issparse ( adata . X ) else adata . X ) if isinstance ( adata , AnnData ) else adata
np . log1p ( X , out = X )
return adata if copy else None |
def find_template ( self , name , dirs = None ) :
"""Helper method . Lookup the template : param name : in all the configured loaders""" | key = self . cache_key ( name , dirs )
try :
result = self . find_template_cache [ key ]
except KeyError :
result = None
for loader in self . loaders :
try :
template , display_name = loader ( name , dirs )
except TemplateDoesNotExist :
pass
else :
... |
def _get_auth_from_netrc ( self , hostname ) :
"""Try to find login auth in ` ` ~ / . netrc ` ` .""" | try :
hostauth = netrc ( self . NETRC_FILE )
except IOError as cause :
if cause . errno != errno . ENOENT :
raise
return None
except NetrcParseError as cause :
raise
# TODO : Map to common base class , so caller has to handle less error types ?
# Try to find specific ` user @ host ` credentials ... |
def delay_job ( self , job , delayed_until ) :
"""Add the job to the delayed list ( zset ) of the queue .""" | timestamp = datetime_to_score ( delayed_until )
self . delayed . zadd ( timestamp , job . ident ) |
def _init_map ( self ) :
"""stub""" | super ( EdXCompositionFormRecord , self ) . _init_map ( )
TextsFormRecord . _init_map ( self )
# because the OsidForm breaks the MRO chain for super , in TemporalFormRecord
ProvenanceFormRecord . _init_map ( self )
# because the OsidForm breaks the MRO chain for super , in TemporalFormRecord
self . my_osid_object_form ... |
def mget ( self , * keys ) :
"""- > # list of values at the specified @ keys""" | return list ( map ( self . _loads , self . _client . hmget ( self . key_prefix , * keys ) ) ) |
def dist_location ( dist ) :
"""Get the site - packages location of this distribution . Generally
this is dist . location , except in the case of develop - installed
packages , where dist . location is the source code location , and we
want to know where the egg - link file is .""" | egg_link = egg_link_path ( dist )
if os . path . exists ( egg_link ) :
return egg_link
return dist . location |
def iflatten_dict_values ( node , depth = 0 ) :
"""> > > from utool . util _ dict import * # NOQA""" | if isinstance ( node , dict ) :
_iter = ( iflatten_dict_values ( value ) for value in six . itervalues ( node ) )
return util_iter . iflatten ( _iter )
else :
return node |
def get_multi ( self , keys , get_cas = False ) :
"""Get multiple keys from server .
: param keys : A list of keys to from server .
: type keys : list
: param get _ cas : If get _ cas is true , each value is ( data , cas ) , with each result ' s CAS value .
: type get _ cas : boolean
: return : A dict wit... | servers = defaultdict ( list )
d = { }
for key in keys :
server_key = self . _get_server ( key )
servers [ server_key ] . append ( key )
for server , keys in servers . items ( ) :
results = server . get_multi ( keys )
if not get_cas : # Remove CAS data
for key , ( value , cas ) in results . item... |
def get_activations_causal ( self ) :
"""Extract causal Activation INDRA Statements .""" | # Search for causal connectives of type ONT : : CAUSE
ccs = self . tree . findall ( "CC/[type='ONT::CAUSE']" )
for cc in ccs :
factor = cc . find ( "arg/[@role=':FACTOR']" )
outcome = cc . find ( "arg/[@role=':OUTCOME']" )
# If either the factor or the outcome is missing , skip
if factor is None or outc... |
def reservations ( self ) :
"""Access the reservations
: returns : twilio . rest . taskrouter . v1 . workspace . task . reservation . ReservationList
: rtype : twilio . rest . taskrouter . v1 . workspace . task . reservation . ReservationList""" | if self . _reservations is None :
self . _reservations = ReservationList ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , task_sid = self . _solution [ 'sid' ] , )
return self . _reservations |
def context_click ( self , on_element = None ) :
"""Performs a context - click ( right click ) on an element .
: Args :
- on _ element : The element to context - click .
If None , clicks on current mouse position .""" | if on_element :
self . move_to_element ( on_element )
if self . _driver . w3c :
self . w3c_actions . pointer_action . context_click ( )
self . w3c_actions . key_action . pause ( )
self . w3c_actions . key_action . pause ( )
else :
self . _actions . append ( lambda : self . _driver . execute ( Comman... |
def loads ( s , base_uri = "" , loader = None , jsonschema = False , load_on_repr = True , ** kwargs ) :
"""Drop in replacement for : func : ` json . loads ` , where JSON references are
proxied to their referent data .
: param s : String containing JSON document
: param kwargs : This function takes any of the... | if loader is None :
loader = functools . partial ( jsonloader , ** kwargs )
return JsonRef . replace_refs ( json . loads ( s , ** kwargs ) , base_uri = base_uri , loader = loader , jsonschema = jsonschema , load_on_repr = load_on_repr , ) |
def _read_http_continuation ( self , size , kind , flag ) :
"""Read HTTP / 2 WINDOW _ UPDATE frames .
Structure of HTTP / 2 WINDOW _ UPDATE frame [ RFC 7540 ] :
| Length ( 24 ) |
| Type ( 8 ) | Flags ( 8 ) |
| R | Stream Identifier ( 31 ) |
| Header Block Fragment ( * ) . . .
Octets Bits Name Descriptio... | _flag = dict ( END_HEADERS = False , # bit 2
)
for index , bit in enumerate ( flag ) :
if index == 2 and bit :
_flag [ 'END_HEADERS' ] = True
elif bit :
raise ProtocolError ( f'HTTP/2: [Type {kind}] invalid format' , quiet = True )
else :
continue
_frag = self . _read_fileng ( size )... |
def visitComparisonExpression ( self , ctx ) :
"""expression : expression ( LTE | LT | GTE | GT ) expression""" | arg1 , arg2 = conversions . to_same ( self . visit ( ctx . expression ( 0 ) ) , self . visit ( ctx . expression ( 1 ) ) , self . _eval_context )
if isinstance ( arg1 , str ) : # string comparison is case - insensitive
compared = ( arg1 . lower ( ) > arg2 . lower ( ) ) - ( arg1 . lower ( ) < arg2 . lower ( ) )
else ... |
def sanitize_filepath ( file_path , replacement_text = "" , platform = None , max_len = None ) :
"""Make a valid file path from a string .
Replace invalid characters for a file path within the ` ` file _ path ` `
with the ` ` replacement _ text ` ` .
Invalid characters are as followings :
| invalid _ file _... | return FilePathSanitizer ( platform = platform , max_len = max_len ) . sanitize ( file_path , replacement_text ) |
def data ( self ) :
"""The ` ` bytes ` ` data for : tl : ` KeyboardButtonCallback ` objects .""" | if isinstance ( self . button , types . KeyboardButtonCallback ) :
return self . button . data |
def init ( self , n = 0 , ftype = "real" , colfac = 1.0e-8 , lmfac = 1.0e-3 , fid = 0 ) :
"""Set selected properties of the fitserver instance .
Like in the constructor , the number of unknowns to be solved for ;
the number of simultaneous solutions ; the ftype and the collinearity
and Levenberg - Marquardt f... | ftype = self . _gettype ( ftype )
self . _fitids [ fid ] [ "stat" ] = False
self . _fitids [ fid ] [ "solved" ] = False
self . _fitids [ fid ] [ "haserr" ] = False
self . _fitids [ fid ] [ "fit" ] = False
self . _fitids [ fid ] [ "looped" ] = False
if self . _fitproxy . init ( fid , n , ftype , colfac , lmfac ) :
s... |
def handle_version ( self , message_header , message ) :
"""This method will handle the Version message and
will send a VerAck message when it receives the
Version message .
: param message _ header : The Version message header
: param message : The Version message""" | log . debug ( "handle version" )
verack = VerAck ( )
log . debug ( "send VerAck" )
self . send_message ( verack )
self . verack = True
start_block_height = sorted ( self . blocks . keys ( ) ) [ 0 ]
if start_block_height < 1 :
start_block_height = 1
# ask for all blocks
block_hashes = [ ]
for height in sorted ( self... |
def load_db ( self ) :
"""Load the taxonomy into a sqlite3 database .
This will set ` ` self . db ` ` to a sqlite3 database which contains all of
the taxonomic information in the reference package .""" | db = taxdb . Taxdb ( )
db . create_tables ( )
reader = csv . DictReader ( self . open_resource ( 'taxonomy' , 'rU' ) )
db . insert_from_taxtable ( lambda : reader . _fieldnames , reader )
curs = db . cursor ( )
reader = csv . DictReader ( self . open_resource ( 'seq_info' , 'rU' ) )
curs . executemany ( "INSERT INTO se... |
def RepackAllTemplates ( self , upload = False , token = None ) :
"""Repack all the templates in ClientBuilder . template _ dir .""" | for template in os . listdir ( config . CONFIG [ "ClientBuilder.template_dir" ] ) :
template_path = os . path . join ( config . CONFIG [ "ClientBuilder.template_dir" ] , template )
self . RepackTemplate ( template_path , os . path . join ( config . CONFIG [ "ClientBuilder.executables_dir" ] , "installers" ) , u... |
def flat_map ( self , func = None , name = None ) :
"""Maps and flatterns each tuple from this stream into 0 or more tuples .
For each tuple on this stream ` ` func ( tuple ) ` ` is called .
If the result is not ` None ` then the the result is iterated over
with each value from the iterator that is not ` None... | if func is None :
func = streamsx . topology . runtime . _identity
if name is None :
name = 'flatten'
sl = _SourceLocation ( _source_info ( ) , 'flat_map' )
_name = self . topology . graph . _requested_name ( name , action = 'flat_map' , func = func )
stateful = self . _determine_statefulness ( func )
o... |
def _ParseRecurseKeys ( self , parser_mediator , root_key ) :
"""Parses the Registry keys recursively .
Args :
parser _ mediator ( ParserMediator ) : parser mediator .
root _ key ( dfwinreg . WinRegistryKey ) : root Windows Registry key .""" | for registry_key in root_key . RecurseKeys ( ) :
if parser_mediator . abort :
break
self . _ParseKey ( parser_mediator , registry_key ) |
def create_folder ( self , folder_name , parent_kind_str , parent_uuid ) :
"""Create a folder under a particular parent
: param folder _ name : str : name of the folder to create
: param parent _ kind _ str : str : kind of the parent of this folder
: param parent _ uuid : str : uuid of the parent of this fold... | return self . _create_item_response ( self . data_service . create_folder ( folder_name , parent_kind_str , parent_uuid ) , Folder ) |
def _mongodump_exec ( mongodump , address , port , user , passwd , db , out_dir , auth_db , dry_run ) :
"""Run mongodump on a database
: param address : server host name or IP address
: param port : server port
: param user : user name
: param passwd : password
: param db : database name
: param out _ d... | # Log the call
log . msg ( "mongodump [{mongodump}] db={db} auth_db={auth_db}" " mongodb://{user}@{host}:{port} > {output}" . format ( mongodump = mongodump , user = user , host = address , port = port , db = db , auth_db = auth_db , output = out_dir ) )
# Prepare the call
args = "--host {host}:{port} -d {db} -u {user}... |
def constrained_to ( self , initial_sequence : torch . Tensor , keep_beam_details : bool = True ) -> 'BeamSearch' :
"""Return a new BeamSearch instance that ' s like this one but with the specified constraint .""" | return BeamSearch ( self . _beam_size , self . _per_node_beam_size , initial_sequence , keep_beam_details ) |
def resize ( self , width , height ) :
"""Resizes the widget .
: param int width :
The width of the widget .
: param int height :
The height of the widget .""" | self . _width = width
self . _height = height
if width != "fill" :
self . _set_tk_config ( "width" , width )
if height != "fill" :
self . _set_tk_config ( "height" , height )
if width == "fill" or height == "fill" :
self . master . display_widgets ( ) |
def _set_password ( self , v , load = False ) :
"""Setter method for password , mapped from YANG variable / routing _ system / router / router _ bgp / address _ family / ipv4 / ipv4 _ unicast / af _ vrf / neighbor / af _ ipv4 _ vrf _ neighbor _ address _ holder / af _ ipv4 _ neighbor _ addr / password ( bgp - passw... | if hasattr ( v , "_utype" ) :
v = v . _utype ( v )
try :
t = YANGDynClass ( v , base = unicode , is_leaf = True , yang_name = "password" , rest_name = "password" , parent = self , path_helper = self . _path_helper , extmethods = self . _extmethods , register_paths = True , extensions = { u'tailf-common' : { u'i... |
def esinw ( b , orbit , solve_for = None , ** kwargs ) :
"""Create a constraint for esinw in an orbit .
If ' esinw ' does not exist in the orbit , it will be created
: parameter b : the : class : ` phoebe . frontend . bundle . Bundle `
: parameter str orbit : the label of the orbit in which this
constraint ... | orbit_ps = _get_system_ps ( b , orbit )
metawargs = orbit_ps . meta
metawargs . pop ( 'qualifier' )
esinw_def = FloatParameter ( qualifier = 'esinw' , value = 0.0 , default_unit = u . dimensionless_unscaled , limits = ( - 1.0 , 1.0 ) , description = 'Eccentricity times sin of argument of periastron' )
esinw , created =... |
async def run_async_task ( self , container , asynctask , newthread = True ) :
"Run asynctask ( sender ) in task pool , call sender ( events ) to send customized events , return result" | e = TaskEvent ( self , async_task = asynctask , newthread = newthread )
await container . wait_for_send ( e )
ev = await TaskDoneEvent . createMatcher ( e )
if hasattr ( ev , 'exception' ) :
raise ev . exception
else :
return ev . result |
def fetchmany ( self , count = None ) :
"""Fetch the next set of rows of a query result , returning a sequence of
sequences ( e . g . a list of tuples ) . An empty sequence is returned when
no more rows are available .""" | if count is None :
count = self . arraysize
if count == 0 :
return self . fetchall ( )
result = [ ]
for i in range ( count ) :
try :
result . append ( self . next ( ) )
except StopIteration :
pass
return result |
def new_worker ( self , name : str ) :
"""Creates a new Worker and start a new Thread with it . Returns the Worker .""" | if not self . running :
return self . immediate_worker
worker = self . _new_worker ( name )
self . _start_worker ( worker )
return worker |
def _update_view ( self , p_data ) :
"""Creates a view from the data entered in the view widget .""" | view = self . _viewdata_to_view ( p_data )
if self . column_mode == _APPEND_COLUMN or self . column_mode == _COPY_COLUMN :
self . _add_column ( view )
elif self . column_mode == _INSERT_COLUMN :
self . _add_column ( view , self . columns . focus_position )
elif self . column_mode == _EDIT_COLUMN :
current_c... |
def _convert_asset_timestamp_fields ( dict_ ) :
"""Takes in a dict of Asset init args and converts dates to pd . Timestamps""" | for key in _asset_timestamp_fields & viewkeys ( dict_ ) :
value = pd . Timestamp ( dict_ [ key ] , tz = 'UTC' )
dict_ [ key ] = None if isnull ( value ) else value
return dict_ |
def p_content ( self , content ) :
'''content : TITLE opttexts VERSION opttexts sections
| TITLE STATESTAG VERSION opttexts states _ sections''' | content [ 0 ] = self . doctype ( content [ 1 ] , content [ 3 ] , content [ 4 ] , content [ 5 ] )
if self . toc :
self . toc . set_articles ( [ a for a in content [ 0 ] . sections if isinstance ( a , Article ) ] ) |
def post ( self , * messages ) :
"""Executes an HTTP request to create message on the queue .
Creates queue if not existed .
Arguments :
messages - - An array of messages to be added to the queue .""" | url = "queues/%s/messages" % self . name
msgs = [ { 'body' : msg } if isinstance ( msg , basestring ) else msg for msg in messages ]
data = json . dumps ( { 'messages' : msgs } )
result = self . client . post ( url = url , body = data , headers = { 'Content-Type' : 'application/json' } )
return result [ 'body' ] |
def list_project ( self , offset = 0 , size = 100 ) :
"""list the project
Unsuccessful opertaion will cause an LogException .
: type offset : int
: param offset : the offset of all the matched names
: type size : int
: param size : the max return names count , - 1 means return all data
: return : ListPr... | # need to use extended method to get more
if int ( size ) == - 1 or int ( size ) > MAX_LIST_PAGING_SIZE :
return list_more ( self . list_project , int ( offset ) , int ( size ) , MAX_LIST_PAGING_SIZE )
headers = { }
params = { }
resource = "/"
params [ 'offset' ] = str ( offset )
params [ 'size' ] = str ( size )
( ... |
def json_using_iso8601 ( __obj : Dict ) -> Dict :
"""Parse ISO - 8601 values from JSON databases .
See : class : ` json . JSONDecoder `
Args :
_ _ obj : Object to decode""" | for key , value in __obj . items ( ) :
with suppress ( TypeError , ValueError ) :
__obj [ key ] = parse_datetime ( value )
with suppress ( TypeError , ValueError ) :
__obj [ key ] = parse_delta ( value )
return __obj |
def win_find_exe ( filename , installsubdir = None , env = "ProgramFiles" ) :
"""Find executable in current dir , system path or given ProgramFiles subdir""" | for fn in [ filename , filename + ".exe" ] :
try :
if installsubdir is None :
path = _where ( fn )
else :
path = _where ( fn , dirs = [ os . path . join ( os . environ [ env ] , installsubdir ) ] )
except IOError :
path = filename
else :
break
return p... |
def map_abi_data ( normalizers , types , data ) :
"""This function will apply normalizers to your data , in the
context of the relevant types . Each normalizer is in the format :
def normalizer ( datatype , data ) :
# Conditionally modify data
return ( datatype , data )
Where datatype is a valid ABI type ... | pipeline = itertools . chain ( [ abi_data_tree ( types ) ] , map ( data_tree_map , normalizers ) , [ partial ( recursive_map , strip_abi_type ) ] , )
return pipe ( data , * pipeline ) |
def predict ( self , data ) :
"""Predict new data for each group in the segmentation .
Parameters
data : pandas . DataFrame
Data to use for prediction . Must have a column with the
same name as ` segmentation _ col ` .
Returns
predicted : pandas . Series
Predicted data in a pandas Series . Will have t... | with log_start_finish ( 'predicting models in group {}' . format ( self . name ) , logger ) :
results = [ self . models [ name ] . predict ( df ) for name , df in self . _iter_groups ( data ) ]
return pd . concat ( results ) |
def QA_util_dict_remove_key ( dicts , key ) :
"""输入一个dict 返回删除后的""" | if isinstance ( key , list ) :
for item in key :
try :
dicts . pop ( item )
except :
pass
else :
try :
dicts . pop ( key )
except :
pass
return dicts |
def can_reupload ( self , user = None ) :
"""Determines whether a submission can be re - uploaded .
Returns a boolean value .
Requires : can _ modify .
Re - uploads are allowed only when test executions have failed .""" | # Re - uploads are allowed only when test executions have failed .
if self . state not in ( self . TEST_VALIDITY_FAILED , self . TEST_FULL_FAILED ) :
return False
# It must be allowed to modify the submission .
if not self . can_modify ( user = user ) :
return False
return True |
def requires_auth ( func ) :
"""Decorator for : class : ` TVDBClient ` methods that require authentication""" | @ wraps ( func )
def wrapper ( self , * args , ** kwargs ) :
if self . token is None or self . token_expired :
self . login ( )
elif self . token_needs_refresh :
self . refresh_token ( )
return func ( self , * args , ** kwargs )
return wrapper |
def recommend ( self , users = None , k = 10 , exclude = None , items = None , new_observation_data = None , new_user_data = None , new_item_data = None , exclude_known = True , diversity = 0 , random_seed = None , verbose = True ) :
"""Recommend the ` ` k ` ` highest scored items for each user .
Parameters
use... | from turicreate . _cython . cy_server import QuietProgress
assert type ( k ) == int
column_types = self . _get_data_schema ( )
user_id = self . user_id
item_id = self . item_id
user_type = column_types [ user_id ]
item_type = column_types [ item_id ]
__null_sframe = _SFrame ( )
if users is None :
users = __null_sfr... |
def class_details ( self , title = None ) :
"""Generates the class details .
: param title : optional title
: type title : str
: return : the details
: rtype : str""" | if title is None :
return javabridge . call ( self . jobject , "toClassDetailsString" , "()Ljava/lang/String;" )
else :
return javabridge . call ( self . jobject , "toClassDetailsString" , "(Ljava/lang/String;)Ljava/lang/String;" , title ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.