signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def normalize_UNTL ( subject ) :
"""Normalize a UNTL subject heading for consistency .""" | subject = subject . strip ( )
subject = re . sub ( r'[\s]+' , ' ' , subject )
return subject |
def is_philips ( dicom_input ) :
"""Use this function to detect if a dicom series is a philips dataset
: param dicom _ input : directory with dicom files for 1 scan of a dicom _ header""" | # read dicom header
header = dicom_input [ 0 ]
if 'Manufacturer' not in header or 'Modality' not in header :
return False
# we try generic conversion in these cases
# check if Modality is mr
if header . Modality . upper ( ) != 'MR' :
return False
# check if manufacturer is Philips
if 'PHILIPS' not in header . M... |
def get_comments ( self , id , project = None , from_revision = None , top = None , order = None ) :
"""GetComments .
[ Preview API ] Gets the specified number of comments for a work item from the specified revision .
: param int id : Work item id
: param str project : Project ID or project name
: param int... | route_values = { }
if project is not None :
route_values [ 'project' ] = self . _serialize . url ( 'project' , project , 'str' )
if id is not None :
route_values [ 'id' ] = self . _serialize . url ( 'id' , id , 'int' )
query_parameters = { }
if from_revision is not None :
query_parameters [ 'fromRevision' ]... |
def autodetect_style ( self , data ) :
"""Determine the style of a docstring ,
and sets it as the default input one for the instance .
: param data : the docstring ' s data to recognize .
: type data : str
: returns : the style detected else ' unknown '
: rtype : str""" | # evaluate styles with keys
found_keys = defaultdict ( int )
for style in self . tagstyles :
for key in self . opt :
found_keys [ style ] += data . count ( self . opt [ key ] [ style ] [ 'name' ] )
fkey = max ( found_keys , key = found_keys . get )
detected_style = fkey if found_keys [ fkey ] else 'unknown'... |
def setSectionCount ( self , count ) :
"""Sets the number of editors that the serial widget should have .
: param count | < int >""" | # cap the sections at 10
count = max ( 1 , min ( count , 10 ) )
# create additional editors
while self . layout ( ) . count ( ) < count :
editor = XLineEdit ( self )
editor . setFont ( self . font ( ) )
editor . setReadOnly ( self . isReadOnly ( ) )
editor . setHint ( self . hint ( ) )
editor . setA... |
def trim ( self , text ) :
"""Trim whitespace indentation from text .""" | lines = text . splitlines ( )
firstline = lines [ 0 ] or lines [ 1 ]
indent = len ( firstline ) - len ( firstline . lstrip ( ) )
return '\n' . join ( x [ indent : ] for x in lines if x . strip ( ) ) |
def sign ( self , h , sig_format = SER_BINARY ) :
"""Signs the message with SHA - 512 hash ` h ' with this private key .""" | outlen = ( self . curve . sig_len_compact if sig_format == SER_COMPACT else self . curve . sig_len_bin )
sig = self . _ECDSA_sign ( h )
return serialize_number ( sig , sig_format , outlen ) |
def notificationResponse ( ) :
"""NOTIFICATION RESPONSE Section 9.1.21d""" | a = TpPd ( pd = 0x6 )
b = MessageType ( mesType = 0x26 )
# 00100110
c = MobileStationClassmark2 ( )
d = MobileId ( )
e = DescriptiveGroupOrBroadcastCallReference ( )
packet = a / b / c / d / e
return packet |
def set_segmentid_range ( self , orchestrator_id , segid_min , segid_max ) :
"""set segment id range in DCNM .""" | url = self . _segmentid_ranges_url
payload = { 'orchestratorId' : orchestrator_id , 'segmentIdRanges' : "%s-%s" % ( segid_min , segid_max ) }
res = self . _send_request ( 'POST' , url , payload , 'segment-id range' )
if not ( res and res . status_code in self . _resp_ok ) :
LOG . error ( "Failed to set segment id r... |
def parse_numeric ( self ) :
"""Tokenize a Fortran numerical value .""" | word = ''
frac = False
if self . char == '-' :
word += self . char
self . update_chars ( )
while self . char . isdigit ( ) or ( self . char == '.' and not frac ) : # Only allow one decimal point
if self . char == '.' :
frac = True
word += self . char
self . update_chars ( )
# Check for float... |
def get_current_target ( module , module_parameter = None , action_parameter = None ) :
'''Get the currently selected target for the given module .
module
name of the module to be queried for its current target
module _ parameter
additional params passed to the defined module
action _ parameter
addition... | result = exec_action ( module , 'show' , module_parameter = module_parameter , action_parameter = action_parameter ) [ 0 ]
if not result :
return None
if result == '(unset)' :
return None
return result |
def flush ( self , fsync = False ) :
"""Force all buffered modifications to be written to disk .
Parameters
fsync : bool ( default False )
call ` ` os . fsync ( ) ` ` on the file handle to force writing to disk .
Notes
Without ` ` fsync = True ` ` , flushing may not guarantee that the OS writes
to disk ... | if self . _handle is not None :
self . _handle . flush ( )
if fsync :
try :
os . fsync ( self . _handle . fileno ( ) )
except OSError :
pass |
def set_epoch ( self , epoch ) :
"""Set the epoch for the current GPS scale .
This method will fail if the current X - axis scale isn ' t one of
the GPS scales . See : ref : ` gwpy - plot - gps ` for more details .
Parameters
epoch : ` float ` , ` str `
GPS - compatible time or date object , anything pars... | scale = self . get_xscale ( )
return self . set_xscale ( scale , epoch = epoch ) |
def has_project_permissions ( user : 'User' , project : 'Project' , request_method : str ) -> bool :
"""This logic is extracted here to be used also with Sanic api .""" | # Superusers and the creator is allowed to do everything
if user . is_staff or user . is_superuser or project . user == user :
return True
# Other user
return request_method in permissions . SAFE_METHODS and project . is_public |
def FUNCTIONNOPROTO ( self , _cursor_type ) :
"""Handles function with no prototype .""" | # id , returns , attributes
returns = _cursor_type . get_result ( )
# if self . is _ fundamental _ type ( returns ) :
returns = self . parse_cursor_type ( returns )
attributes = [ ]
obj = typedesc . FunctionType ( returns , attributes )
# argument _ types cant be asked . no arguments .
self . set_location ( obj , None ... |
def start_receive ( self , stream ) :
"""Mark the : attr : ` receive _ side < Stream . receive _ side > ` on ` stream ` as
ready for reading . Safe to call from any thread . When the associated
file descriptor becomes ready for reading ,
: meth : ` BasicStream . on _ receive ` will be called .""" | _vv and IOLOG . debug ( '%r.start_receive(%r)' , self , stream )
side = stream . receive_side
assert side and side . fd is not None
self . defer ( self . poller . start_receive , side . fd , ( side , stream . on_receive ) ) |
def send ( self , msg , error_check = False ) :
"""Send a raw string with the CR - LF appended to it .
Required arguments :
* msg - Message to send .
Optional arguments :
* error _ check = False - Check for errors .
If an error is found the relevant exception will be raised .""" | with self . lock :
msg = msg . replace ( '\r' , '\\r' ) . replace ( '\n' , '\\n' ) + self . _crlf
try :
data = msg . encode ( self . encoding )
except UnicodeEncodeError :
data = msg . encode ( self . fallback_encoding )
if len ( data ) > 512 :
raise self . MessageTooLong ( "Lurk... |
def serialize ( self ) :
"""Serializes the Peer data as a simple JSON map string .""" | return json . dumps ( { "name" : self . name , "ip" : self . ip , "port" : self . port } , sort_keys = True ) |
def add_token ( self , act , coro , performer ) :
"""Adds a completion token ` act ` in the proactor with associated ` coro `
corutine and perform callable .""" | assert act not in self . tokens
act . coro = coro
self . tokens [ act ] = performer
self . register_fd ( act , performer ) |
def _add_device_to_device_group ( self , device ) :
'''Add device to device service cluster group .
: param device : bigip object - - device to add to group''' | device_name = get_device_info ( device ) . name
dg = pollster ( self . _get_device_group ) ( device )
dg . devices_s . devices . create ( name = device_name , partition = self . partition )
pollster ( self . _check_device_exists_in_device_group ) ( device_name ) |
def retinotopy_mesh_field ( mesh , mdl , polar_angle = None , eccentricity = None , weight = None , weight_min = 0 , scale = 1 , sigma = None , shape = 2 , suffix = None , max_eccentricity = Ellipsis , max_polar_angle = 180 , angle_type = 'both' , exclusion_threshold = None ) :
'''retinotopy _ mesh _ field ( mesh ,... | # TODO : given a 3D mesh and a registered model , we should be able to return a 3D version of the
# anchors by unprojecting them
if pimms . is_str ( mdl ) :
mdl = retinotopy_model ( mdl )
if not isinstance ( mdl , RetinotopyMeshModel ) :
if isinstance ( mdl , RegisteredRetinotopyModel ) :
mdl = mdl . mo... |
def quantile_turnover ( quantile_factor , quantile , period = 1 ) :
"""Computes the proportion of names in a factor quantile that were
not in that quantile in the previous period .
Parameters
quantile _ factor : pd . Series
DataFrame with date , asset and factor quantile .
quantile : int
Quantile on whi... | quant_names = quantile_factor [ quantile_factor == quantile ]
quant_name_sets = quant_names . groupby ( level = [ 'date' ] ) . apply ( lambda x : set ( x . index . get_level_values ( 'asset' ) ) )
if isinstance ( period , int ) :
name_shifted = quant_name_sets . shift ( period )
else :
shifted_idx = utils . add... |
def create_roadmap_doc ( dat , opFile ) :
"""takes a dictionary read from a yaml file and converts
it to the roadmap documentation""" | op = format_title ( 'Roadmap for AIKIF' )
for h1 in dat [ 'projects' ] :
op += format_h1 ( h1 )
if dat [ h1 ] is None :
op += '(No details)\n'
else :
for h2 in dat [ h1 ] :
op += '\n' + format_h2 ( h2 )
if dat [ h1 ] [ h2 ] is None :
op += '(blank text... |
def parse_int ( self , buff , start , end ) :
'''parse an integer from the buffer given the interval of bytes
: param buff :
: param start :
: param end :''' | # num = self . parse _ uint ( buff , start , end )
# l = ( end - start )
# return self . twos _ comp ( num , l * 8)
return struct . unpack_from ( self . structmap [ end - start ] , buff , start ) [ 0 ] |
def from_indra_pickle ( path : str , name : Optional [ str ] = None , version : Optional [ str ] = None , description : Optional [ str ] = None , authors : Optional [ str ] = None , contact : Optional [ str ] = None , license : Optional [ str ] = None , copyright : Optional [ str ] = None , disclaimer : Optional [ str ... | with open ( path , 'rb' ) as f :
statements = load ( f )
return from_indra_statements ( stmts = statements , name = name , version = version , description = description , authors = authors , contact = contact , license = license , copyright = copyright , disclaimer = disclaimer , ) |
def read_config ( config_fname = None ) :
"""Parse input configuration file and return a config dict .""" | if not config_fname :
config_fname = DEFAULT_CONFIG_FNAME
try :
with open ( config_fname , 'r' ) as config_file :
config = yaml . load ( config_file )
except IOError as exc :
if exc . errno == errno . ENOENT :
print ( 'payu: warning: Configuration file {0} not found!' . format ( config_fname... |
def get_backend_cls ( self ) :
"""Get the currently used backend class .""" | backend_cls = self . backend_cls
if not backend_cls or isinstance ( backend_cls , basestring ) :
backend_cls = get_backend_cls ( backend_cls )
return backend_cls |
def cli ( obj , ids , query , filters ) :
"""Show status and severity changes for alerts .""" | client = obj [ 'client' ]
if obj [ 'output' ] == 'json' :
r = client . http . get ( '/alerts/history' )
click . echo ( json . dumps ( r [ 'history' ] , sort_keys = True , indent = 4 , ensure_ascii = False ) )
else :
timezone = obj [ 'timezone' ]
if ids :
query = [ ( 'id' , x ) for x in ids ]
... |
def _resolve_file_name ( source , destination ) :
"""Create a filename for the destination zip file .""" | number = 1
if os . path . exists ( os . path . join ( destination , os . path . basename ( source ) + '.zip' ) ) :
while True :
zip_filename = os . path . join ( destination , os . path . basename ( source ) + '_' + str ( number ) + '.zip' )
if not os . path . exists ( zip_filename ) :
b... |
def _spark_map ( fun , indexed_param_grid , sc , seed , X_bc ) :
"""We cannot pass a RandomState instance to each spark worker since it will
behave identically across partitions . Instead , we explictly handle the
partitions with a newly seeded instance .
The seed for each partition will be the " seed " ( Mon... | def _wrap_random_state ( split_index , partition ) :
prng = np . random . RandomState ( seed + split_index )
yield map ( partial ( fun , prng = prng , X = X_bc ) , partition )
par_param_grid = sc . parallelize ( indexed_param_grid )
indexed_results = par_param_grid . mapPartitionsWithIndex ( _wrap_random_state ... |
def has_symbol ( self , symbol , as_of = None ) :
"""Return True if the ' symbol ' exists in this library AND the symbol
isn ' t deleted in the specified as _ of .
It ' s possible for a deleted symbol to exist in older snapshots .
Parameters
symbol : ` str `
symbol name for the item
as _ of : ` str ` or... | try : # Always use the primary for has _ symbol , it ' s safer
self . _read_metadata ( symbol , as_of = as_of , read_preference = ReadPreference . PRIMARY )
return True
except NoDataFoundException :
return False |
def gpg_app_create_key ( blockchain_id , appname , keyname , txid = None , immutable = False , proxy = None , wallet_keys = None , config_dir = None ) :
"""Create a new application GPG key .
Use good defaults ( RSA - 4096)
Stash it to the app - specific keyring locally .
Return { ' status ' : True , ' key _ u... | assert is_valid_appname ( appname )
assert is_valid_keyname ( keyname )
if config_dir is None :
config_dir = get_config_dir ( )
client_config_path = os . path . join ( config_dir , blockstack_client . CONFIG_FILENAME )
if proxy is None :
proxy = blockstack_client . get_default_proxy ( config_path = client_confi... |
def groupby ( itr , key_fn = None ) :
"""An wrapper function around itertools . groupby to sort each results .
: param itr : Iterable object , a list / tuple / genrator , etc .
: param key _ fn : Key function to sort ' itr ' .
> > > import operator
> > > itr = [ ( " a " , 1 ) , ( " b " , - 1 ) , ( " c " , 1... | return itertools . groupby ( sorted ( itr , key = key_fn ) , key = key_fn ) |
def create_customer ( self , email , displayName ) :
"""Create a new customer and return an issue Resource for it .
: param email : Customer Email
: type email : str
: param displayName : Customer display name
: type displayName : str
: rtype : Customer""" | url = self . _options [ 'server' ] + '/rest/servicedeskapi/customer'
headers = { 'X-ExperimentalApi' : 'opt-in' }
r = self . _session . post ( url , headers = headers , data = json . dumps ( { 'email' : email , 'displayName' : displayName } ) )
raw_customer_json = json_loads ( r )
if r . status_code != 201 :
raise ... |
def get_logger ( name ) :
"""Return logger with null handle""" | log = logging . getLogger ( name )
if not log . handlers :
log . addHandler ( NullHandler ( ) )
return log |
def append_column ( table , col_name , default_value = None ) :
'''Appends a column to the raw data without any integrity checks .
Args :
default _ value : The value which will assigned , not copied into each row''' | table [ 0 ] . append ( col_name . strip ( ) )
for row in table [ 1 : ] :
row . append ( default_value ) |
def pprint ( self , imports = None , prefix = "\n " , unknown_value = '<?>' , qualify = False , separator = "" ) :
"""Same as Parameterized . pprint , except that X . classname ( Y
is replaced with X . classname . instance ( Y""" | r = Parameterized . pprint ( self , imports , prefix , unknown_value = unknown_value , qualify = qualify , separator = separator )
classname = self . __class__ . __name__
return r . replace ( ".%s(" % classname , ".%s.instance(" % classname ) |
def source ( self , getline = linecache . getline ) :
"""A string with the sourcecode for the current line ( from ` ` linecache ` ` - failures are ignored ) .
Fast but sometimes incomplete .
: type : str""" | try :
return getline ( self . filename , self . lineno )
except Exception as exc :
return "??? NO SOURCE: {!r}" . format ( exc ) |
def get_hosts ( service_instance , datacenter_name = None , host_names = None , cluster_name = None , get_all_hosts = False ) :
'''Returns a list of vim . HostSystem objects representing ESXi hosts
in a vcenter filtered by their names and / or datacenter , cluster membership .
service _ instance
The Service I... | properties = [ 'name' ]
if cluster_name and not datacenter_name :
raise salt . exceptions . ArgumentValueError ( 'Must specify the datacenter when specifying the cluster' )
if not host_names :
host_names = [ ]
if not datacenter_name : # Assume the root folder is the starting point
start_point = get_root_fol... |
def get_schema ( self , table , with_headers = False ) :
"""Retrieve the database schema for a particular table .""" | f = self . fetch ( 'desc ' + wrap ( table ) )
if not isinstance ( f [ 0 ] , list ) :
f = [ f ]
# Replace None with ' '
schema = [ [ '' if col is None else col for col in row ] for row in f ]
# If with _ headers is True , insert headers to first row before returning
if with_headers :
schema . insert ( 0 , [ 'Col... |
def _make_ocs_request ( self , method , service , action , ** kwargs ) :
"""Makes a OCS API request
: param method : HTTP method
: param service : service name
: param action : action path
: param \ * \ * kwargs : optional arguments that ` ` requests . Request . request ` ` accepts
: returns : class : ` r... | slash = ''
if service :
slash = '/'
path = self . OCS_BASEPATH + service + slash + action
attributes = kwargs . copy ( )
if 'headers' not in attributes :
attributes [ 'headers' ] = { }
attributes [ 'headers' ] [ 'OCS-APIREQUEST' ] = 'true'
if self . _debug :
print ( 'OCS request: %s %s %s' % ( method , self... |
def requires_dynamic_permission ( permission_s , logical_operator = all ) :
"""This method requires that the calling Subject be authorized to the extent
that is required to satisfy the dynamic permission _ s specified and the logical
operation upon them . Unlike ` ` requires _ permission ` ` , which uses static... | def outer_wrap ( fn ) :
@ functools . wraps ( fn )
def inner_wrap ( * args , ** kwargs ) :
newperms = [ perm . format ( ** kwargs ) for perm in permission_s ]
subject = Yosai . get_current_subject ( )
subject . check_permission ( newperms , logical_operator )
return fn ( * args ,... |
def _parse_game_data ( self , uri ) :
"""Parses a value for every attribute .
This function looks through every attribute and retrieves the value
according to the parsing scheme and index of the attribute from the
passed HTML data . Once the value is retrieved , the attribute ' s value is
updated with the r... | boxscore = self . _retrieve_html_page ( uri )
# If the boxscore is None , the game likely hasn ' t been played yet and
# no information can be gathered . As there is nothing to grab , the
# class instance should just be empty .
if not boxscore :
return
fields_to_special_parse = [ 'away_even_strength_assists' , 'awa... |
def execute_multiple ( self , actions , immediate = True ) :
"""Execute multiple Actions ( each containing commands on a single object ) .
Normally , the actions are sent for execution immediately ( possibly preceded
by earlier queued commands ) , but if you are going for maximum efficiency
you can set immeed... | # throttling part 1 : split up each action into smaller actions , as needed
# optionally split large lists of groups in add / remove commands ( if action supports it )
split_actions = [ ]
exceptions = [ ]
for a in actions :
if len ( a . commands ) == 0 :
if self . logger :
self . logger . warnin... |
async def modify ( cls , db , key , data : dict ) :
'''Partially modify a document by providing a subset of its data fields to be modified
: param db :
Handle to the MongoDB database
: param key :
The primary key of the database object being modified . Usually its ` ` _ id ` `
: param data :
The data se... | if data is None :
raise BadRequest ( 'Failed to modify document. No data fields to modify' )
# validate partial data
cls . _validate ( data )
query = { cls . primary_key : key }
for i in cls . connection_retries ( ) :
try :
result = await db [ cls . get_collection_name ( ) ] . find_one_and_update ( filt... |
def indent ( func ) :
"""Decorator for allowing to use method as normal method or with
context manager for auto - indenting code blocks .""" | def wrapper ( self , * args , ** kwds ) :
func ( self , * args , ** kwds )
return Indent ( self )
return wrapper |
def getAttribute ( self , attribute ) :
"""return attribute .
If attribute is type and it ' s None , and no simple or complex content ,
return the default type " xsd : anyType " """ | value = XMLSchemaComponent . getAttribute ( self , attribute )
if attribute != 'type' or value is not None :
return value
if self . content is not None :
return None
parent = self
while 1 :
nsdict = parent . attributes [ XMLSchemaComponent . xmlns ]
for k , v in nsdict . items ( ) :
if v not in ... |
def pip_install_to_target ( self , path , requirements = "" , local_package = None ) :
"""For a given active virtualenv , gather all installed pip packages then
copy ( re - install ) them to the path provided .
: param str path :
Path to copy installed pip packages to .
: param str requirements :
If set ,... | packages = [ ]
if not requirements :
logger . debug ( 'Gathering pip packages' )
# packages . extend ( pip . operations . freeze . freeze ( ) )
pass
else :
requirements_path = os . path . join ( self . get_src_path ( ) , requirements )
logger . debug ( 'Gathering packages from requirements: {}' . fo... |
def divide_hand ( self , tiles_34 , melds = None ) :
"""Return a list of possible hands .
: param tiles _ 34:
: param melds : list of Meld objects
: return :""" | if not melds :
melds = [ ]
closed_hand_tiles_34 = tiles_34 [ : ]
# small optimization , we can ' t have a pair in open part of the hand ,
# so we don ' t need to try find pairs in open sets
open_tile_indices = melds and reduce ( lambda x , y : x + y , [ x . tiles_34 for x in melds ] ) or [ ]
for open_item in open_t... |
def uniiterable ( arg , level ) :
"""Iterable object to unicode string .
: type arg : collections . Iterable
: param arg : iterable object
: type level : int
: param level : deep level
: rtype : unicode
: return : iterable object as unicode string""" | if not isinstance ( arg , collections . Iterable ) :
raise TypeError ( 'expected collections.Iterable, {} received' . format ( type ( arg ) . __name__ ) )
templates = { list : u'[{}]' , tuple : u'({})' }
result = [ ]
for i in arg :
result . append ( pretty_spaces ( level ) + convert ( i , level = level ) )
stri... |
def construct_concept_to_indicator_mapping ( n : int = 1 ) -> Dict [ str , List [ str ] ] :
"""Create a dictionary mapping high - level concepts to low - level indicators
Args :
n : Number of indicators to return
Returns :
Dictionary that maps concept names to lists of indicator names .""" | df = pd . read_sql_table ( "concept_to_indicator_mapping" , con = engine )
gb = df . groupby ( "Concept" )
_dict = { k : [ get_variable_and_source ( x ) for x in take ( n , v [ "Indicator" ] . values ) ] for k , v in gb }
return _dict |
def rand ( n , ** kwargs ) :
"""Random vector from the n - Sphere
This function will return a random vector which is an element of the n - Sphere .
The n - Sphere is defined as a vector in R ^ n + 1 with a norm of one .
Basically , we ' ll find a random vector in R ^ n + 1 and normalize it .
This uses the m... | rvec = np . random . randn ( 3 )
rvec = rvec / np . linalg . norm ( rvec )
return rvec |
def getCertificateExpireDate ( self , CorpNum ) :
"""공인인증서 만료일 확인 , 등록여부 확인용도로 활용가능
args
CorpNum : 확인할 회원 사업자번호
return
등록시 만료일자 , 미등록시 해당 PopbillException raise .
raise
PopbillException""" | result = self . _httpget ( '/Taxinvoice?cfg=CERT' , CorpNum )
return datetime . strptime ( result . certificateExpiration , '%Y%m%d%H%M%S' ) |
def get_message ( self , dummy0 , dummy1 , use_cmd = False ) :
"""Get a getmore message .""" | ns = _UJOIN % ( self . db , self . coll )
if use_cmd :
ns = _UJOIN % ( self . db , "$cmd" )
spec = self . as_command ( ) [ 0 ]
return query ( 0 , ns , 0 , - 1 , spec , None , self . codec_options )
return get_more ( ns , self . ntoreturn , self . cursor_id ) |
def toString ( val , join_char = '\n' ) :
"""Turn a string or array value into a string .""" | if type ( val ) in ( list , tuple ) :
return join_char . join ( val )
return val |
def update_state_active ( self ) :
"""Update the state of the model run to active .
Raises an exception if update fails or resource is unknown .
Returns
ModelRunHandle
Refreshed run handle .""" | # Update state to active
self . update_state ( self . links [ REF_UPDATE_STATE_ACTIVE ] , { 'type' : RUN_ACTIVE } )
# Returned refreshed verion of the handle
return self . refresh ( ) |
def prepare_params ( req : snug . Request ) -> snug . Request :
"""prepare request parameters""" | return req . replace ( params = { key : dump_param ( val ) for key , val in req . params . items ( ) if val is not None } ) |
def userInvitations ( self ) :
"""gets all user invitations""" | self . __init ( )
items = [ ]
for n in self . _userInvitations :
if "id" in n :
url = "%s/%s" % ( self . root , n [ 'id' ] )
items . append ( self . Invitation ( url = url , securityHandler = self . _securityHandler , proxy_url = self . _proxy_url , proxy_port = self . _proxy_port , initialize = Tru... |
def filter_vectors ( self , input_list ) :
"""Returns subset of specified input list .""" | unique_dict = { }
for v in input_list :
unique_dict [ v [ 1 ] ] = v
return list ( unique_dict . values ( ) ) |
def delete ( endpoint = 'incidents' , id = None , api_url = None , page_id = None , api_key = None , api_version = None ) :
'''Remove an entry from an endpoint .
endpoint : incidents
Request a specific endpoint .
page _ id
Page ID . Can also be specified in the config file .
api _ key
API key . Can also... | params = _get_api_params ( api_url = api_url , page_id = page_id , api_key = api_key , api_version = api_version )
if not _validate_api_params ( params ) :
log . error ( 'Invalid API params.' )
log . error ( params )
return { 'result' : False , 'comment' : 'Invalid API params. See log for details' }
endpoin... |
def _calc_strain_max ( self , loc_input , loc_layer , motion , * args ) :
"""Compute the effective strain at the center of a layer .""" | return motion . calc_peak ( self . calc_strain_tf ( loc_input , loc_layer ) ) |
def HA2 ( credentials , request , algorithm ) :
"""Create HA2 md5 hash
If the qop directive ' s value is " auth " or is unspecified , then HA2:
HA2 = md5 ( A2 ) = MD5 ( method : digestURI )
If the qop directive ' s value is " auth - int " , then HA2 is
HA2 = md5 ( A2 ) = MD5 ( method : digestURI : MD5 ( ent... | if credentials . get ( "qop" ) == "auth" or credentials . get ( 'qop' ) is None :
return H ( b":" . join ( [ request [ 'method' ] . encode ( 'utf-8' ) , request [ 'uri' ] . encode ( 'utf-8' ) ] ) , algorithm )
elif credentials . get ( "qop" ) == "auth-int" :
for k in 'method' , 'uri' , 'body' :
if k not... |
def calc_timestep_statistic ( self , statistic , time ) :
"""Calculate statistics from the primary attribute of the StObject .
Args :
statistic : statistic being calculated
time : Timestep being investigated
Returns :
Value of the statistic""" | ti = np . where ( self . times == time ) [ 0 ] [ 0 ]
ma = np . where ( self . masks [ ti ] . ravel ( ) == 1 )
if statistic in [ 'mean' , 'max' , 'min' , 'std' , 'ptp' ] :
stat_val = getattr ( self . timesteps [ ti ] . ravel ( ) [ ma ] , statistic ) ( )
elif statistic == 'median' :
stat_val = np . median ( self ... |
def readline ( self , limit = - 1 ) :
"""Read up to and including the next newline . Returns the bytes read .""" | if limit != - 1 :
raise NotImplementedError ( 'limits other than -1 not implemented yet' )
the_line = io . BytesIO ( )
while not ( self . _eof and len ( self . _buffer ) == 0 ) : # In the worst case , we ' re reading the unread part of self . _ buffer
# twice here , once in the if condition and once when calling in... |
def move_datetime_week ( dt , direction , num_shifts ) :
"""Move datetime 1 week in the chosen direction .
unit is a no - op , to keep the API the same as the day case""" | delta = relativedelta ( weeks = + num_shifts )
return _move_datetime ( dt , direction , delta ) |
def set_home_position_send ( self , target_system , latitude , longitude , altitude , x , y , z , q , approach_x , approach_y , approach_z , force_mavlink1 = False ) :
'''The position the system will return to and land on . The position is
set automatically by the system during the takeoff in
case it was not ex... | return self . send ( self . set_home_position_encode ( target_system , latitude , longitude , altitude , x , y , z , q , approach_x , approach_y , approach_z ) , force_mavlink1 = force_mavlink1 ) |
def format_unix_var ( text ) :
"""Example : :
this _ is _ very _ good""" | text = text . strip ( )
if len ( text ) == 0 : # if empty string , return it
raise ValueError ( "can not be empty string!" )
else :
if text [ 0 ] in string . digits :
raise ValueError ( "variable can not start with digits!" )
text = text . lower ( )
# delete redundant empty space
words = lis... |
def get_scheduler_from_hostname ( self , host_name ) :
"""Get scheduler linked to the given host _ name
: param host _ name : host _ name we want the scheduler from
: type host _ name : str
: return : scheduler with id corresponding to the mapping table
: rtype : dict""" | scheduler_uuid = self . hosts_schedulers . get ( host_name , None )
return self . schedulers . get ( scheduler_uuid , None ) |
def _execute_on_selected ( self , p_cmd_str , p_execute_signal ) :
"""Executes command specified by p _ cmd _ str on selected todo item .
p _ cmd _ str should be a string with one replacement field ( ' { } ' ) which
will be substituted by id of the selected todo item .
p _ execute _ signal is the signal name ... | try :
todo = self . listbox . focus . todo
todo_id = str ( self . view . todolist . number ( todo ) )
urwid . emit_signal ( self , p_execute_signal , p_cmd_str , todo_id )
# force screen redraw after editing
if p_cmd_str . startswith ( 'edit' ) :
urwid . emit_signal ( self , 'refresh' )
exce... |
def translate_doc ( self , d , field_mapping = None , map_identifiers = None , ** kwargs ) :
"""Translate a solr document ( i . e . a single result row )""" | if field_mapping is not None :
self . map_doc ( d , field_mapping )
subject = self . translate_obj ( d , M . SUBJECT )
obj = self . translate_obj ( d , M . OBJECT )
# TODO : use a more robust method ; we need equivalence as separate field in solr
if map_identifiers is not None :
if M . SUBJECT_CLOSURE in d :
... |
def get_features ( self , api = None ) :
"""Returns filtered list of features in this registry
: param str api : Return only features with this api name , or None to
return all features .
: return : list of Feature objects""" | return [ x for x in self . features . values ( ) if api and x . api == api or not api ] |
def with_rank_at_most ( self , rank ) :
"""Returns a shape based on ` self ` with at most the given rank .
Args :
rank : An integer .
Returns :
A shape that is at least as specific as ` self ` with at most the given
rank .
Raises :
ValueError : If ` self ` does not represent a shape with at most the g... | if self . ndims is not None and self . ndims > rank :
raise ValueError ( "Shape %s must have rank at most %d" % ( self , rank ) )
else :
return self |
def trackerItem ( self ) :
"""Returns the tracker item for this chart .
: return < XChartTrackerItem > | | None""" | # check for the tracking enabled state
if not self . isTrackingEnabled ( ) :
return None
# generate a new tracker item
if not ( self . _trackerItem and self . _trackerItem ( ) ) :
item = XChartTrackerItem ( )
self . addItem ( item )
self . _trackerItem = weakref . ref ( item )
return self . _trackerItem... |
def walk_dir ( path , args , state ) :
"""Check all files in ` path ' to see if there is any requests that
we should send out on the bus .""" | if args . debug :
sys . stderr . write ( "Walking %s\n" % path )
for root , _dirs , files in os . walk ( path ) :
if not safe_process_files ( root , files , args , state ) :
return False
if state . should_quit ( ) :
return False
return True |
def _apply_line_rules ( lines , commit , rules , line_nr_start ) :
"""Iterates over the lines in a given list of lines and validates a given list of rules against each line""" | all_violations = [ ]
line_nr = line_nr_start
for line in lines :
for rule in rules :
violations = rule . validate ( line , commit )
if violations :
for violation in violations :
violation . line_nr = line_nr
all_violations . append ( violation )
line_n... |
def _get_supervisorctl_bin ( bin_env ) :
'''Return supervisorctl command to call , either from a virtualenv , an argument
passed in , or from the global modules options''' | cmd = 'supervisorctl'
if not bin_env :
which_result = __salt__ [ 'cmd.which_bin' ] ( [ cmd ] )
if which_result is None :
raise CommandNotFoundError ( 'Could not find a `{0}` binary' . format ( cmd ) )
return which_result
# try to get binary from env
if os . path . isdir ( bin_env ) :
cmd_bin = o... |
def _format_return_timestamps ( self , return_timestamps = None ) :
"""Format the passed in return timestamps value as a numpy array .
If no value is passed , build up array of timestamps based upon
model start and end times , and the ' saveper ' value .""" | if return_timestamps is None : # Build based upon model file Start , Stop times and Saveper
# Vensim ' s standard is to expect that the data set includes the ` final time ` ,
# so we have to add an extra period to make sure we get that value in what
# numpy ' s ` arange ` gives us .
return_timestamps_array = np . a... |
def _process_dataset ( name , directory , num_shards , labels_file ) :
"""Process a complete data set and save it as a TFRecord .
Args :
name : string , unique identifier specifying the data set .
directory : string , root path to the data set .
num _ shards : integer number of shards for this data set .
... | filenames , texts , labels = _find_image_files ( directory , labels_file )
_process_image_files ( name , filenames , texts , labels , num_shards ) |
def delete_lb ( kwargs = None , call = None ) :
'''Permanently delete a load - balancer .
CLI Example :
. . code - block : : bash
salt - cloud - f delete _ lb gce name = lb''' | if call != 'function' :
raise SaltCloudSystemExit ( 'The delete_hc function must be called with -f or --function.' )
if not kwargs or 'name' not in kwargs :
log . error ( 'A name must be specified when deleting a health check.' )
return False
name = kwargs [ 'name' ]
lb_conn = get_lb_conn ( get_conn ( ) )
_... |
def tyn_calus ( target , VA , VB , sigma_A , sigma_B , temperature = 'pore.temperature' , viscosity = 'pore.viscosity' ) :
r"""Uses Tyn _ Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
target : OpenPNM Object
The... | T = target [ temperature ]
mu = target [ viscosity ]
A = 8.93e-8 * ( VB * 1e6 ) ** 0.267 / ( VA * 1e6 ) ** 0.433 * T
B = ( sigma_B / sigma_A ) ** 0.15 / ( mu * 1e3 )
value = A * B
return value |
def distrib_ ( self , label = None , style = None , opts = None ) :
"""Get a Seaborn distribution chart""" | try :
return self . _get_chart ( "distribution" , style = style , opts = opts , label = label )
except Exception as e :
self . err ( e , "Can not draw distrinution chart" ) |
def execution_cls ( self ) :
"""Get execution layer class""" | name = self . campaign . process . type
for clazz in [ ExecutionDriver , SrunExecutionDriver ] :
if name == clazz . name :
return clazz
raise NameError ( "Unknown execution layer: '%s'" % name ) |
def to_unit_memory ( number ) :
"""Creates a string representation of memory size given ` number ` .""" | kb = 1024
number /= kb
if number < 100 :
return '{} Kb' . format ( round ( number , 2 ) )
number /= kb
if number < 300 :
return '{} Mb' . format ( round ( number , 2 ) )
number /= kb
return '{} Gb' . format ( round ( number , 2 ) ) |
def get_node_resource_by_type ( api_url = None , node_name = None , type_name = None , verify = False , cert = list ( ) ) :
"""Returns specified resource for a Node
: param api _ url : Base PuppetDB API url
: param node _ name : Name of node
: param type _ name : Type of resource""" | return utils . _make_api_request ( api_url , '/nodes/{0}/resources/{1}' . format ( node_name , type_name ) , verify , cert ) |
def update_eol ( self , os_name ) :
"""Update end of line status .""" | os_name = to_text_string ( os_name )
value = { "nt" : "CRLF" , "posix" : "LF" } . get ( os_name , "CR" )
self . set_value ( value ) |
def dispose ( self ) :
"""Disposes the : py : class : ` securityhandlerhelper ` object .""" | self . _username = None
self . _password = None
self . _org_url = None
self . _proxy_url = None
self . _proxy_port = None
self . _token_url = None
self . _securityHandler = None
self . _valid = None
self . _message = None
del self . _username
del self . _password
del self . _org_url
del self . _proxy_url
del self . _pr... |
def output_to_json ( sources ) :
"""Print statistics to the terminal in Json format""" | results = OrderedDict ( )
for source in sources :
if source . get_is_available ( ) :
source . update ( )
source_name = source . get_source_name ( )
results [ source_name ] = source . get_sensors_summary ( )
print ( json . dumps ( results , indent = 4 ) )
sys . exit ( ) |
def CompleteBreakpoint ( self , breakpoint_id ) :
"""Marks the specified breaking as completed .
Appends the ID to set of completed breakpoints and clears it .
Args :
breakpoint _ id : breakpoint ID to complete .""" | with self . _lock :
self . _completed . add ( breakpoint_id )
if breakpoint_id in self . _active :
self . _active . pop ( breakpoint_id ) . Clear ( ) |
def isalive ( self ) :
'''This tests if the child process is running or not . This is
non - blocking . If the child was terminated then this will read the
exitstatus or signalstatus of the child . This returns True if the child
process appears to be running or False if not . It can take literally
SECONDS fo... | ptyproc = self . ptyproc
with _wrap_ptyprocess_err ( ) :
alive = ptyproc . isalive ( )
if not alive :
self . status = ptyproc . status
self . exitstatus = ptyproc . exitstatus
self . signalstatus = ptyproc . signalstatus
self . terminated = True
return alive |
def get_citation_by_pmid ( self , pubmed_identifier : str ) -> Optional [ Citation ] :
"""Get a citation object by its PubMed identifier .""" | return self . get_citation_by_reference ( reference = pubmed_identifier , type = CITATION_TYPE_PUBMED ) |
def list ( ctx ) :
"""List SWAG account info .""" | if ctx . namespace != 'accounts' :
click . echo ( click . style ( 'Only account data is available for listing.' , fg = 'red' ) )
return
swag = create_swag_from_ctx ( ctx )
accounts = swag . get_all ( )
_table = [ [ result [ 'name' ] , result . get ( 'id' ) ] for result in accounts ]
click . echo ( tabulate ( _t... |
def summary ( self ) :
"""Gets summary ( e . g . accuracy / precision / recall , objective history , total iterations ) of model
trained on the training set . An exception is thrown if ` trainingSummary is None ` .""" | if self . hasSummary :
if self . numClasses <= 2 :
return BinaryLogisticRegressionTrainingSummary ( super ( LogisticRegressionModel , self ) . summary )
else :
return LogisticRegressionTrainingSummary ( super ( LogisticRegressionModel , self ) . summary )
else :
raise RuntimeError ( "No trai... |
def create_handlers_map ( ) :
"""Create new handlers map .
Returns :
list of ( regexp , handler ) pairs for WSGIApplication constructor .""" | pipeline_handlers_map = [ ]
if pipeline :
pipeline_handlers_map = pipeline . create_handlers_map ( prefix = ".*/pipeline" )
return pipeline_handlers_map + [ # Task queue handlers .
# Always suffix by mapreduce _ id or shard _ id for log analysis purposes .
# mapreduce _ id or shard _ id also presents in headers or ... |
def query ( self , coords , mode = 'random_sample' ) :
"""Returns A0 at the given coordinates . There are several different query
modes , which handle the probabilistic nature of the map differently .
Args :
coords ( : obj : ` astropy . coordinates . SkyCoord ` ) : The coordinates to query .
mode ( Optional... | # Check that the query mode is supported
valid_modes = [ 'random_sample' , 'random_sample_per_pix' , 'samples' , 'median' , 'mean' ]
if mode not in valid_modes :
raise ValueError ( '"{}" is not a valid `mode`. Valid modes are:\n' ' {}' . format ( mode , valid_modes ) )
n_coords_ret = coords . shape [ 0 ]
# Determi... |
def start_optimisation ( self , rounds : int , max_angle : float , max_distance : float , temp : float = 298.15 , stop_when = None , verbose = None ) :
"""Starts the loop fitting protocol .
Parameters
rounds : int
The number of Monte Carlo moves to be evaluated .
max _ angle : float
The maximum variation ... | self . _generate_initial_score ( )
self . _mmc_loop ( rounds , max_angle , max_distance , temp = temp , stop_when = stop_when , verbose = verbose )
return |
def cmd ( f ) :
"""wrapper for easily exposing a function as a CLI command .
including help message , arguments help and type .
Example Usage :
> > > import cbox
> > > @ cbox . cmd
> > > def hello ( name : str ) :
> > > ' ' ' greets a person by its name .
> > > : param name : the name of the person
... | @ wraps ( f )
def wrapper ( * args , ** kwargs ) :
return f ( * args , ** kwargs )
setattr ( wrapper , executors . EXECUTOR_ATTR , executors . CMD )
return wrapper |
def find ( self , name , namespace = None ) :
"""Find plugin object
Parameters
name : string
A name of the object entry or full namespace
namespace : string , optional
A period separated namespace . E . g . ` foo . bar . hogehoge `
Returns
instance
An instance found
Raises
KeyError
If the name... | if "." in name :
namespace , name = name . rsplit ( "." , 1 )
caret = self . raw
if namespace :
for term in namespace . split ( '.' ) :
if term not in caret :
caret [ term ] = Bunch ( )
caret = caret [ term ]
return caret [ name ] |
def aggregate ( cls , pipeline = None , ** kwargs ) :
"""Returns the document dicts returned from the Aggregation Pipeline""" | return list ( cls . collection . aggregate ( pipeline or [ ] , ** kwargs ) ) |
def AjustarLiquidacion ( self ) :
"Ajustar Liquidación de Tabaco Verde" | # renombrar la clave principal de la estructura
if 'liquidacion' in self . solicitud :
liq = self . solicitud . pop ( 'liquidacion' )
self . solicitud [ "liquidacionAjuste" ] = liq
# llamar al webservice :
ret = self . client . ajustarLiquidacion ( auth = { 'token' : self . Token , 'sign' : self . Sign , 'cuit'... |
def _score_macro_average ( self , n_classes ) :
"""Compute the macro average scores for the ROCAUC curves .""" | # Gather all FPRs
all_fpr = np . unique ( np . concatenate ( [ self . fpr [ i ] for i in range ( n_classes ) ] ) )
avg_tpr = np . zeros_like ( all_fpr )
# Compute the averages per class
for i in range ( n_classes ) :
avg_tpr += interp ( all_fpr , self . fpr [ i ] , self . tpr [ i ] )
# Finalize the average
avg_tpr ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.