signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def custom ( srcpaths , event_cb = None , poll_interval = 1 , recurse = True , restart_cb = None , restart_func = None , close_fds = True ) :
'''Sets up lazarus in custom mode .
See the : py : func : ` default ` function for a simpler mode of use .
The custom mode of lazarus is to watch all modules rooted at an... | if _active :
msg = 'lazarus is already active'
raise RuntimeWarning ( msg )
if restart_cb and not callable ( restart_cb ) :
msg = 'restart_cb keyword argument is not callable'
raise TypeError ( msg )
if restart_func and not callable ( restart_func ) :
msg = 'restart_func keyword argument is not call... |
def sentences ( ctx , input , output ) :
"""Read input document , and output sentences .""" | log . info ( 'chemdataextractor.read.elements' )
log . info ( 'Reading %s' % input . name )
doc = Document . from_file ( input )
for element in doc . elements :
if isinstance ( element , Text ) :
for raw_sentence in element . raw_sentences :
output . write ( raw_sentence . strip ( ) )
... |
def set_password_prompt ( self , regex = None ) :
"""Defines a pattern that is used to monitor the response of the
connected host for a password prompt .
: type regex : RegEx
: param regex : The pattern that , when matched , causes an error .""" | if regex is None :
self . manual_password_re = regex
else :
self . manual_password_re = to_regexs ( regex ) |
def display ( self ) :
"""Displays the symbol table content""" | # Finding the maximum length for each column
sym_name = "Symbol name"
sym_len = max ( max ( len ( i . name ) for i in self . table ) , len ( sym_name ) )
kind_name = "Kind"
kind_len = max ( max ( len ( SharedData . KINDS [ i . kind ] ) for i in self . table ) , len ( kind_name ) )
type_name = "Type"
type_len = max ( ma... |
def _get_for_address ( address , key ) :
"""Retrieve an attribute of or the physical interface that
the IP address provided could be bound to .
: param address ( str ) : An individual IPv4 or IPv6 address without a net
mask or subnet prefix . For example , ' 192.168.1.1 ' .
: param key : ' iface ' for the p... | address = netaddr . IPAddress ( address )
for iface in netifaces . interfaces ( ) :
addresses = netifaces . ifaddresses ( iface )
if address . version == 4 and netifaces . AF_INET in addresses :
addr = addresses [ netifaces . AF_INET ] [ 0 ] [ 'addr' ]
netmask = addresses [ netifaces . AF_INET ]... |
def get_handlers ( self , kind = None ) :
"""Retrieves the handlers of the given kind . If kind is None , all handlers
are returned .
: param kind : The kind of the handlers to return
: return : A list of handlers , or an empty list""" | with self . _lock :
if kind is not None :
try :
return self . _handlers [ kind ] [ : ]
except KeyError :
return [ ]
return self . __all_handlers . copy ( ) |
def get_args_index ( target ) -> int :
"""Returns the index of the " * args " parameter if such a parameter exists in
the function arguments or - 1 otherwise .
: param target :
The target function for which the args index should be determined
: return :
The arguments index if it exists or - 1 if not""" | code = target . __code__
if not bool ( code . co_flags & inspect . CO_VARARGS ) :
return - 1
return code . co_argcount + code . co_kwonlyargcount |
def _read_response ( self ) :
"""Reads a complete response packet from the server""" | result = self . buf . read_line ( ) . decode ( "utf-8" )
if not result :
raise NoResponseError ( "No response received from server." )
msg = self . _read_message ( )
if result != "ok" :
raise InvalidResponseError ( msg )
return msg |
def multiplicity ( self ) :
"""Returns the multiplicity of a defect site within the structure ( needed for concentration analysis )""" | if self . _multiplicity is None : # generate multiplicity based on space group symmetry operations performed on defect coordinates
try :
d_structure = create_saturated_interstitial_structure ( self )
except ValueError :
logger . debug ( 'WARNING! Multiplicity was not able to be calculated adequa... |
def deploy_webconf ( ) :
"""Deploy nginx and other wsgi server site configurations to the host""" | deployed = [ ]
log_dir = '/' . join ( [ deployment_root ( ) , 'log' ] )
# TODO - incorrect - check for actual package to confirm installation
if webserver_list ( ) :
if env . verbosity :
print env . host , "DEPLOYING webconf:"
if not exists ( log_dir ) :
run ( 'ln -s /var/log log' )
# deploy... |
def _rebuild_blknos_and_blklocs ( self ) :
"""Update mgr . _ blknos / mgr . _ blklocs .""" | new_blknos = np . empty ( self . shape [ 0 ] , dtype = np . int64 )
new_blklocs = np . empty ( self . shape [ 0 ] , dtype = np . int64 )
new_blknos . fill ( - 1 )
new_blklocs . fill ( - 1 )
for blkno , blk in enumerate ( self . blocks ) :
rl = blk . mgr_locs
new_blknos [ rl . indexer ] = blkno
new_blklocs [... |
def valuewrapper ( f , arguments = None ) :
"""Return a likelihood accepting value instead of x as a keyword argument .
This is specifically intended for the instantiator above .""" | def wrapper ( ** kwds ) :
value = kwds . pop ( 'value' )
return f ( value , ** kwds )
if arguments is None :
wrapper . __dict__ . update ( f . __dict__ )
else :
wrapper . __dict__ . update ( arguments )
return wrapper |
def _render_content ( self , content , ** settings ) :
"""Perform widget rendering , but do not print anything .""" | result = [ ]
bars = settings [ self . SETTING_BARS ]
label_width = self . chart_measure ( bars )
if not settings [ self . SETTING_BAR_WIDTH ] :
settings [ self . SETTING_BAR_WIDTH ] = TERMINAL_WIDTH - label_width - 3
max_value = max ( content )
i = 0
for bar in content :
result . append ( self . _render_bar ( b... |
def bbox_to_mip ( self , bbox , mip , to_mip ) :
"""Convert bbox or slices from one mip level to another .""" | if not type ( bbox ) is Bbox :
bbox = lib . generate_slices ( bbox , self . mip_bounds ( mip ) . minpt , self . mip_bounds ( mip ) . maxpt , bounded = False )
bbox = Bbox . from_slices ( bbox )
def one_level ( bbox , mip , to_mip ) :
original_dtype = bbox . dtype
# setting type required for Python2
... |
def read_folder ( folder ) :
"""Parameters
folder : str
Returns
list of HandwrittenData objects""" | hwr_objects = [ ]
for filepath in natsort . natsorted ( glob . glob ( "%s/*.inkml" % folder ) ) :
tmp = inkml . read ( filepath )
for hwr in tmp . to_single_symbol_list ( ) :
hwr_objects . append ( hwr )
logging . info ( "Done reading formulas" )
save_raw_pickle ( hwr_objects )
return hwr_objects |
def list_pkgs ( versions_as_list = False , include_components = True , include_updates = True , ** kwargs ) :
'''List the packages currently installed .
. . note : :
To view installed software as displayed in the Add / Remove Programs , set
` ` include _ components ` ` and ` ` include _ updates ` ` to False .... | versions_as_list = salt . utils . data . is_true ( versions_as_list )
# not yet implemented or not applicable
if any ( [ salt . utils . data . is_true ( kwargs . get ( x ) ) for x in ( 'removed' , 'purge_desired' ) ] ) :
return { }
saltenv = kwargs . get ( 'saltenv' , 'base' )
refresh = salt . utils . data . is_tru... |
def iter_genotypes ( self ) :
"""Iterates on available markers .
Returns :
Genotypes instances .""" | for v in self . get_vcf ( ) :
alleles = { v . REF } | set ( v . ALT )
if self . quality_field :
variant = ImputedVariant ( v . ID , v . CHROM , v . POS , alleles , getattr ( v , self . quality_field ) )
else :
variant = Variant ( v . ID , v . CHROM , v . POS , alleles )
for coded_allele ... |
def connect ( self ) :
"""Connect to device .""" | return self . loop . create_connection ( lambda : self , self . host , self . port ) |
def remove ( self , interval ) :
"""Removes an interval from the tree , if present . If not , raises
ValueError .
Completes in O ( log n ) time .""" | # self . verify ( )
if interval not in self : # print ( self . all _ intervals )
raise ValueError
self . top_node = self . top_node . remove ( interval )
self . all_intervals . remove ( interval )
self . _remove_boundaries ( interval ) |
def capture_guest ( userid ) :
"""Caputre a virtual machine image .
Input parameters :
: userid : USERID of the guest , last 8 if length > 8
Output parameters :
: image _ name : Image name that captured""" | # check power state , if down , start it
ret = sdk_client . send_request ( 'guest_get_power_state' , userid )
power_status = ret [ 'output' ]
if power_status == 'off' :
sdk_client . send_request ( 'guest_start' , userid )
# TODO : how much time ?
time . sleep ( 1 )
# do capture
image_name = 'image_captured_... |
def is_ipv4 ( value , ** kwargs ) :
"""Indicate whether ` ` value ` ` is a valid IP version 4 address .
: param value : The value to evaluate .
: returns : ` ` True ` ` if ` ` value ` ` is valid , ` ` False ` ` if it is not .
: rtype : : class : ` bool < python : bool > `
: raises SyntaxError : if ` ` kwarg... | try :
value = validators . ipv4 ( value , ** kwargs )
except SyntaxError as error :
raise error
except Exception :
return False
return True |
def get_methods_class ( self , class_name ) :
"""Return all methods of a specific class
: param class _ name : the class name
: type class _ name : string
: rtype : a list with : class : ` EncodedMethod ` objects""" | l = [ ]
for i in self . classes . class_def :
for j in i . get_methods ( ) :
if class_name == j . get_class_name ( ) :
l . append ( j )
return l |
def get_self_url ( request_data ) :
"""Returns the URL of the current host + current view + query .
: param request _ data : The request as a dict
: type : dict
: return : The url of current host + current view + query
: rtype : string""" | self_url_host = OneLogin_Saml2_Utils . get_self_url_host ( request_data )
request_uri = ''
if 'request_uri' in request_data :
request_uri = request_data [ 'request_uri' ]
if not request_uri . startswith ( '/' ) :
match = re . search ( '^https?://[^/]*(/.*)' , request_uri )
if match is not None :... |
def time_from_frequencyseries ( htilde , sample_frequencies = None , discont_threshold = 0.99 * numpy . pi ) :
"""Computes time as a function of frequency from the given
frequency - domain waveform . This assumes the stationary phase
approximation . Any frequencies lower than the first non - zero value in
hti... | if sample_frequencies is None :
sample_frequencies = htilde . sample_frequencies . numpy ( )
phase = phase_from_frequencyseries ( htilde ) . data
dphi = numpy . diff ( phase )
time = - dphi / ( 2. * numpy . pi * numpy . diff ( sample_frequencies ) )
nzidx = numpy . nonzero ( abs ( htilde . data ) ) [ 0 ]
kmin , kma... |
def complete_io ( self , iocb , msg ) :
"""Called by a handler to return data to the client .""" | if _debug :
IOQController . _debug ( "complete_io %r %r" , iocb , msg )
# check to see if it is completing the active one
if iocb is not self . active_iocb :
raise RuntimeError ( "not the current iocb" )
# normal completion
IOController . complete_io ( self , iocb , msg )
# no longer an active iocb
self . activ... |
def _connect ( self ) :
"""Connect to the MySQL server""" | self . _close ( )
self . conn = MySQLdb . Connect ( host = self . hostname , port = self . port , user = self . username , passwd = self . password , db = self . database ) |
def nfa ( self ) :
"""convert the expression into an NFA""" | finalstate = State ( final = True )
nextstate = finalstate
for tokenexpr in reversed ( self ) :
state = tokenexpr . nfa ( nextstate )
nextstate = state
return NFA ( state ) |
def extend_is_dir ( value , minimum = None , maximum = None ) :
u"""This function is extended is _ dir ( ) .
This function was able to take ListType or StringType as argument .""" | if isinstance ( value , list ) :
return [ is_dir ( member ) for member in validate . is_list ( value , minimum , maximum ) ]
else :
return is_dir ( value ) |
def safe_filter ( error_output = '' ) :
"""A safe filter decorator only raising errors when ` ` THUMBNAIL _ DEBUG ` ` is
` ` True ` ` otherwise returning ` ` error _ output ` ` .""" | def inner ( f ) :
@ wraps ( f )
def wrapper ( * args , ** kwargs ) :
try :
return f ( * args , ** kwargs )
except Exception as err :
if sorl_settings . THUMBNAIL_DEBUG :
raise
logger . error ( 'Thumbnail filter failed: %s' % str ( err ) , exc_i... |
def reset_ids_in_meta_df ( meta_df ) :
"""Meta _ df is modified inplace .""" | # Record original index name , and then change it so that the column that it
# becomes will be appropriately named
original_index_name = meta_df . index . name
meta_df . index . name = "old_id"
# Reset index
meta_df . reset_index ( inplace = True )
# Change the index name back to what it was
meta_df . index . name = or... |
def is_parans_exp ( istr ) :
"""Determines if an expression is a valid function " call " """ | fxn = istr . split ( '(' ) [ 0 ]
if ( not fxn . isalnum ( ) and fxn != '(' ) or istr [ - 1 ] != ')' :
return False
plevel = 1
for c in '(' . join ( istr [ : - 1 ] . split ( '(' ) [ 1 : ] ) :
if c == '(' :
plevel += 1
elif c == ')' :
plevel -= 1
if plevel == 0 :
return False
retur... |
def Burr ( c , k , tag = None ) :
"""A Burr random variate
Parameters
c : scalar
The first shape parameter
k : scalar
The second shape parameter""" | assert c > 0 and k > 0 , 'Burr "c" and "k" parameters must be greater than zero'
return uv ( ss . burr ( c , k ) , tag = tag ) |
def parse_hicpro_stats ( self , f , rsection ) :
"""Parse a HiC - Pro stat file""" | s_name = self . clean_s_name ( os . path . basename ( f [ 'root' ] ) , os . path . dirname ( f [ 'root' ] ) )
if s_name not in self . hicpro_data . keys ( ) :
self . hicpro_data [ s_name ] = { }
self . add_data_source ( f , s_name , section = rsection )
for l in f [ 'f' ] . splitlines ( ) :
if not l . startswit... |
def get_relationships ( self ) :
"""Gets all ` ` Relationships ` ` .
return : ( osid . relationship . RelationshipList ) - a list of
` ` Relationships ` `
raise : OperationFailed - unable to complete request
raise : PermissionDenied - authorization failure
* compliance : mandatory - - This method must be ... | url_path = ( '/handcar/services/relationship/families/' + self . _catalog_idstr + '/relationships' )
return objects . RelationshipList ( self . _get_request ( url_path ) ) |
def allocate_stream ( self , stream_type , stream_id = None , previous = None , attach = False ) :
"""Allocate a new stream of the given type .
The stream is allocated with an incremental ID starting at
StreamAllocator . StartingID . The returned data stream can always
be used to to attach a NodeInput to this... | if stream_type not in DataStream . TypeToString :
raise ArgumentError ( "Unknown stream type in allocate_stream" , stream_type = stream_type )
if stream_id is not None and stream_id >= StreamAllocator . StartingID :
raise ArgumentError ( "Attempted to explicitly allocate a stream id in the internally managed id... |
def _filter_metadata_for_connection ( target , connection , ** kw ) :
"""Listener to control what indexes get created .
Useful for skipping postgres - specific indexes on a sqlite for example .
It ' s looking for info entry ` engines ` on an index
( ` Index ( info = dict ( engines = [ ' postgresql ' ] ) ) ` )... | engine = connection . engine . name
default_engines = ( engine , )
tables = target if isinstance ( target , sa . Table ) else kw . get ( "tables" , [ ] )
for table in tables :
indexes = list ( table . indexes )
for idx in indexes :
if engine not in idx . info . get ( "engines" , default_engines ) :
... |
def comparedist ( df , * args , ** kwargs ) :
"""Compare the distributions of two DataFrames giving visualisations of :
- individual and combined distributions
- distribution of non - common values
- distribution of non - common values vs . each side
Plot distribution as area ( fill _ between ) + mean , med... | bins = kwargs . get ( 'bins' , 50 )
xlabel = kwargs . get ( 'xlabel' , 'Value' )
ylabel = kwargs . get ( 'ylabel' , 'Count' )
base_fmt = kwargs . get ( 'base_fmt' )
arg_fmt = kwargs . get ( 'arg_fmt' )
# The base for comparisons is the first passed selector .
base_selector , selectors = args [ 0 ] , args [ 1 : ]
df1 = ... |
def _raw_print_image ( self , line , size , output = None ) :
"""Print formatted image""" | i = 0
cont = 0
buffer = ""
raw = ""
def __raw ( string ) :
if output :
output ( string )
else :
self . _raw ( string )
raw += S_RASTER_N
buffer = "%02X%02X%02X%02X" % ( ( ( size [ 0 ] / size [ 1 ] ) / 8 ) , 0 , size [ 1 ] , 0 )
raw += buffer . decode ( 'hex' )
buffer = ""
while i < len ( line ) ... |
def remove_empty_dir ( path ) :
"""Function to remove empty folders""" | try :
if not os . path . isdir ( path ) :
return
files = os . listdir ( path )
# if folder empty , delete it
if len ( files ) == 0 :
os . rmdir ( path )
# remove empty subdirectory
elif len ( files ) > 0 :
for f in files :
abspath = os . path . join ( path , f... |
def add_snippet_client ( self , name , package ) :
"""Adds a snippet client to the management .
Args :
name : string , the attribute name to which to attach the snippet
client . E . g . ` name = ' maps ' ` attaches the snippet client to
` ad . maps ` .
package : string , the package name of the snippet ap... | # Should not load snippet with the same name more than once .
if name in self . _snippet_clients :
raise Error ( self , 'Name "%s" is already registered with package "%s", it cannot ' 'be used again.' % ( name , self . _snippet_clients [ name ] . client . package ) )
# Should not load the same snippet package more ... |
def env_absent ( name , user = 'root' ) :
'''Verifies that the specified environment variable is absent from the crontab
for the specified user
name
The name of the environment variable to remove from the user crontab
user
The name of the user whose crontab needs to be modified , defaults to
the root us... | name = name . strip ( )
ret = { 'name' : name , 'result' : True , 'changes' : { } , 'comment' : '' }
if __opts__ [ 'test' ] :
status = _check_cron_env ( user , name )
ret [ 'result' ] = None
if status == 'absent' :
ret [ 'result' ] = True
ret [ 'comment' ] = 'Cron env {0} is absent' . format... |
def register_name ( self , register_index ) :
"""Retrives and returns the name of an ARM CPU register .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
register _ index ( int ) : index of the register whose name to retrieve
Returns :
Name of the register .""" | result = self . _dll . JLINKARM_GetRegisterName ( register_index )
return ctypes . cast ( result , ctypes . c_char_p ) . value . decode ( ) |
def gauss_fltr_astropy ( dem , size = None , sigma = None , origmask = False , fill_interior = False ) :
"""Astropy gaussian filter properly handles convolution with NaN
http : / / stackoverflow . com / questions / 23832852 / by - which - measures - should - i - set - the - size - of - my - gaussian - filter - in... | # import astropy . nddata
import astropy . convolution
dem = malib . checkma ( dem )
# Generate 2D gaussian kernel for input sigma and size
# Default size is 8 * sigma in x and y directions
# kernel = astropy . nddata . make _ kernel ( [ size , size ] , sigma , ' gaussian ' )
# Size must be odd
if size is not None :
... |
def calculate_hash ( options ) :
"""returns an option _ collection _ hash given a list of options""" | options = sorted ( list ( options ) )
sha_hash = sha1 ( )
# equivalent to loop over the options and call sha _ hash . update ( )
sha_hash . update ( '' . join ( options ) . encode ( 'utf-8' ) )
return sha_hash . hexdigest ( ) |
def get_call_name ( self , node ) :
"""Return call name for the given node .""" | if isinstance ( node . func , ast . Attribute ) :
return node . func . attr
elif isinstance ( node . func , ast . Name ) :
return node . func . id |
def _read_eeprom ( self , address , size ) :
'''Read EEPROM''' | self . _intf . write ( self . _base_addr + self . CAL_EEPROM_ADD , array ( 'B' , pack ( '>H' , address & 0x3FFF ) ) )
# 14 - bit address , 16384 bytes
n_pages , n_bytes = divmod ( size , self . CAL_EEPROM_PAGE_SIZE )
data = array ( 'B' )
for _ in range ( n_pages ) :
data . extend ( self . _intf . read ( self . _bas... |
def pick ( self , form , target_units , parcel_size , ave_unit_size , current_units , max_parcel_size = 200000 , min_unit_size = 400 , drop_after_build = True , residential = True , bldg_sqft_per_job = 400.0 , profit_to_prob_func = None ) :
"""Choose the buildings from the list that are feasible to build in
order... | if len ( self . feasibility ) == 0 : # no feasible buildings , might as well bail
return
if form is None :
df = self . feasibility
elif isinstance ( form , list ) :
df = self . keep_form_with_max_profit ( form )
else :
df = self . feasibility [ form ]
# feasible buildings only for this building type
df ... |
def add_method ( self , f = None , name = None ) :
"""Add a method to the dispatcher .
Parameters
f : callable
Callable to be added .
name : str , optional
Name to register ( the default is function * * f * * name )
Notes
When used as a decorator keeps callable object unmodified .
Examples
Use as ... | if name and not f :
return functools . partial ( self . add_method , name = name )
self . method_map [ name or f . __name__ ] = f
return f |
def getEPrintURL ( self , CorpNum , MgtKey , UserID = None ) :
"""공급받는자용 인쇄 URL 확인
args
CorpNum : 팝빌회원 사업자번호
MgtKey : 문서관리번호
UserID : 팝빌회원 아이디
return
팝빌 URL as str
raise
PopbillException""" | if MgtKey == None or MgtKey == "" :
raise PopbillException ( - 99999999 , "관리번호가 입력되지 않았습니다." )
result = self . _httpget ( '/Cashbill/' + MgtKey + '?TG=EPRINT' , CorpNum , UserID )
return result . url |
def set_metadata ( self , metadata , clear = False , prefix = None ) :
"""Accepts a dictionary of metadata key / value pairs and updates the
specified container metadata with them .
If ' clear ' is True , any existing metadata is deleted and only the
passed metadata is retained . Otherwise , the values passed... | return self . manager . set_metadata ( self , metadata , clear = clear , prefix = prefix ) |
def get_data ( self ) :
"""Gets data from the given url""" | url = self . build_url ( )
self . incidents_data = requests . get ( url )
if not self . incidents_data . status_code == 200 :
raise self . incidents_data . raise_for_status ( ) |
def _maybe_fill ( arr , fill_value = np . nan ) :
"""if we have a compatible fill _ value and arr dtype , then fill""" | if _isna_compat ( arr , fill_value ) :
arr . fill ( fill_value )
return arr |
def upload_documentation ( self , metadata , doc_dir ) :
"""Upload documentation to the index .
: param metadata : A : class : ` Metadata ` instance defining at least a name
and version number for the documentation to be
uploaded .
: param doc _ dir : The pathname of the directory which contains the
docum... | self . check_credentials ( )
if not os . path . isdir ( doc_dir ) :
raise DistlibException ( 'not a directory: %r' % doc_dir )
fn = os . path . join ( doc_dir , 'index.html' )
if not os . path . exists ( fn ) :
raise DistlibException ( 'not found: %r' % fn )
metadata . validate ( )
name , version = metadata . n... |
def list_media ( self , series , sort = META . SORT_DESC , limit = META . MAX_MEDIA , offset = 0 ) :
"""List media for a given series or collection
@ param crunchyroll . models . Series series the series to search for
@ param str sort choose the ordering of the
results , only META . SORT _ DESC
is known to ... | params = { 'sort' : sort , 'offset' : offset , 'limit' : limit , }
params . update ( self . _get_series_query_dict ( series ) )
result = self . _android_api . list_media ( ** params )
return result |
def new ( cls , chart_type , chart_data , package ) :
"""Return a new | ChartPart | instance added to * package * containing
a chart of * chart _ type * and depicting * chart _ data * .""" | chart_blob = chart_data . xml_bytes ( chart_type )
partname = package . next_partname ( cls . partname_template )
content_type = CT . DML_CHART
chart_part = cls . load ( partname , content_type , chart_blob , package )
xlsx_blob = chart_data . xlsx_blob
chart_part . chart_workbook . update_from_xlsx_blob ( xlsx_blob )
... |
def factorize_groupby_cols ( self , groupby_cols ) :
"""factorizes all columns that are used in the groupby
it will use cache carrays if available
if not yet auto _ cache is valid , it will create cache carrays""" | # first check if the factorized arrays already exist
# unless we need to refresh the cache
factor_list = [ ]
values_list = [ ]
# factorize the groupby columns
for col in groupby_cols :
if self . auto_cache or self . cache_valid ( col ) : # create factorization cache if needed
if not self . cache_valid ( col... |
def no_type_check ( arg ) :
"""Decorator to indicate that annotations are not type hints .
The argument must be a class or function ; if it is a class , it
applies recursively to all methods and classes defined in that class
( but not to methods defined in its superclasses or subclasses ) .
This mutates the... | if isinstance ( arg , type ) :
arg_attrs = arg . __dict__ . copy ( )
for attr , val in arg . __dict__ . items ( ) :
if val in arg . __bases__ + ( arg , ) :
arg_attrs . pop ( attr )
for obj in arg_attrs . values ( ) :
if isinstance ( obj , types . FunctionType ) :
obj ... |
def vis_keypoints ( img , kps , kp_thresh = 2 , alpha = 0.7 ) :
"""Visualizes keypoints ( adapted from vis _ one _ image ) .
kps has shape ( 4 , # keypoints ) where 4 rows are ( x , y , logit , prob ) .""" | dataset_keypoints = PersonKeypoints . NAMES
kp_lines = PersonKeypoints . CONNECTIONS
# Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv .
cmap = plt . get_cmap ( 'rainbow' )
colors = [ cmap ( i ) for i in np . linspace ( 0 , 1 , len ( kp_lines ) + 2 ) ]
colors = [ ( c [ 2 ] * 255 , c [ 1 ] * 255 , c [ 0 ... |
def start_program ( self , turn_on_load = True ) :
"""Starts running programmed test sequence
: return : None""" | self . __set_buffer_start ( self . CMD_START_PROG )
self . __set_checksum ( )
self . __send_buffer ( )
# Turn on Load if not on
if turn_on_load and not self . load_on :
self . load_on = True |
def autocomplete_query ( self , ** kwargs ) :
"""Query the Yelp Autocomplete API .
documentation : https : / / www . yelp . com / developers / documentation / v3 / autocomplete
required parameters :
* text - search text""" | if not kwargs . get ( 'text' ) :
raise ValueError ( 'Valid text (parameter "text") must be provided.' )
return self . _query ( AUTOCOMPLETE_API_URL , ** kwargs ) |
def server_socket ( self , config ) :
""": meth : ` . WNetworkNativeTransportProto . server _ socket ` method implementation""" | if self . __server_socket is None :
self . __server_socket = self . create_server_socket ( config )
self . __server_socket . bind ( self . bind_socket ( config ) . pair ( ) )
return self . __server_socket |
def get_user ( self , user_id ) :
"""Returns the current user from the session data .
If authenticated , this return the user object based on the user ID
and session data .
. . note : :
This required monkey - patching the ` ` contrib . auth ` ` middleware
to make the ` ` request ` ` object available to th... | if ( hasattr ( self , 'request' ) and user_id == self . request . session [ "user_id" ] ) :
token = self . request . session [ 'token' ]
endpoint = self . request . session [ 'region_endpoint' ]
services_region = self . request . session [ 'services_region' ]
user = auth_user . create_user_from_token ( ... |
def execute_ls ( host_list , remote_user , remote_pass ) :
'''Execute any adhoc command on the hosts .''' | runner = spam . ansirunner . AnsibleRunner ( )
result , failed_hosts = runner . ansible_perform_operation ( host_list = host_list , remote_user = remote_user , remote_pass = remote_pass , module = "command" , module_args = "ls -1" )
print "Result: " , result |
def Sign ( message , private_key ) :
"""Sign the message with the given private key .
Args :
message ( str ) : message to be signed
private _ key ( str ) : 32 byte key as a double digit hex string ( e . g . having a length of 64)
Returns :
bytearray : the signature of the message .""" | hash = hashlib . sha256 ( binascii . unhexlify ( message ) ) . hexdigest ( )
v , r , s = bitcoin . ecdsa_raw_sign ( hash , private_key )
rb = bytearray ( r . to_bytes ( 32 , 'big' ) )
sb = bytearray ( s . to_bytes ( 32 , 'big' ) )
sig = rb + sb
return sig |
def Poll ( generator = None , condition = None , interval = None , timeout = None ) :
"""Periodically calls generator function until a condition is satisfied .""" | if not generator :
raise ValueError ( "generator has to be a lambda" )
if not condition :
raise ValueError ( "condition has to be a lambda" )
if interval is None :
interval = DEFAULT_POLL_INTERVAL
if timeout is None :
timeout = DEFAULT_POLL_TIMEOUT
started = time . time ( )
while True :
obj = genera... |
def register ( self , uri , prefix ) :
'''Registers the given URI and associates it with the given prefix .
If the URI has already been registered , this is a no - op .
: param uri : string
: param prefix : string''' | if not is_valid_schema_uri ( uri ) :
raise KeyError ( 'cannot register invalid URI {} (prefix {})' . format ( uri , prefix ) )
if not is_valid_prefix ( prefix ) :
raise ValueError ( 'cannot register invalid prefix %q for URI %q' . format ( prefix , uri ) )
if self . _uri_to_prefix . get ( uri ) is None :
se... |
def update_radii ( self , radii ) :
'''Update the radii inplace''' | self . radii = np . array ( radii , dtype = 'float32' )
prim_radii = self . _gen_radii ( self . radii )
self . _radii_vbo . set_data ( prim_radii )
self . widget . update ( ) |
def zone_compare ( timezone ) :
'''Compares the given timezone name with the system timezone name .
Checks the hash sum between the given timezone , and the one set in
/ etc / localtime . Returns True if names and hash sums match , and False if not .
Mostly useful for running state checks .
. . versionchang... | if 'Solaris' in __grains__ [ 'os_family' ] or 'AIX' in __grains__ [ 'os_family' ] :
return timezone == get_zone ( )
if 'FreeBSD' in __grains__ [ 'os_family' ] :
if not os . path . isfile ( _get_localtime_path ( ) ) :
return timezone == get_zone ( )
tzfile = _get_localtime_path ( )
zonepath = _get_zone_f... |
def _save_cfg_packages ( self , data ) :
'''Save configuration packages . ( NG )
: param data :
: return :''' | pkg_id = 0
pkg_cfg_id = 0
for pkg_name , pkg_configs in data . items ( ) :
pkg = Package ( )
pkg . id = pkg_id
pkg . name = pkg_name
self . db . store ( pkg )
for pkg_config in pkg_configs :
cfg = PackageCfgFile ( )
cfg . id = pkg_cfg_id
cfg . pkgid = pkg_id
cfg . pat... |
def sample_rollout_single_env ( self , rollout_length ) :
"""Return indexes of next sample""" | # Sample from up to total size
if self . current_size < self . buffer_capacity :
if rollout_length + 1 > self . current_size :
raise VelException ( "Not enough elements in the buffer to sample the rollout" )
# -1 because we cannot take the last one
return np . random . choice ( self . current_size -... |
def get_privilege_set ( self , hiveObject , user_name , group_names ) :
"""Parameters :
- hiveObject
- user _ name
- group _ names""" | self . send_get_privilege_set ( hiveObject , user_name , group_names )
return self . recv_get_privilege_set ( ) |
def parse_star_genecount_report ( self , f ) :
"""Parse a STAR gene counts output file""" | # Three numeric columns : unstranded , stranded / first - strand , stranded / second - strand
keys = [ 'N_unmapped' , 'N_multimapping' , 'N_noFeature' , 'N_ambiguous' ]
unstranded = { 'N_genes' : 0 }
first_strand = { 'N_genes' : 0 }
second_strand = { 'N_genes' : 0 }
num_errors = 0
num_genes = 0
for l in f [ 'f' ] :
... |
def _get_question_map ( self , question_id ) :
"""get question map from questions matching question _ id
This can make sense of both Section assigned Ids or normal Question / Item Ids""" | if question_id . get_authority ( ) == ASSESSMENT_AUTHORITY :
key = '_id'
match_value = ObjectId ( question_id . get_identifier ( ) )
else :
key = 'questionId'
match_value = str ( question_id )
for question_map in self . _my_map [ 'questions' ] :
if question_map [ key ] == match_value :
retur... |
def _finalize ( self , dry_run = False ) :
"""Remove / compress files as requested""" | for rmfile in self . files . temp_files :
if dry_run :
print ( "remove %s" % rmfile )
else :
os . remove ( rmfile )
for gzfile in self . files . gzip_files :
if dry_run : # print ( " gzip % s " % gzfile )
pass
else :
os . system ( 'gzip -9 %s' % gzfile ) |
def is_subscriber ( self ) :
"""Returns whether the user is a subscriber or not . True or False .""" | doc = self . _request ( self . ws_prefix + ".getInfo" , True )
return _extract ( doc , "subscriber" ) == "1" |
def share_project ( project_id , usernames , read_only , share , ** kwargs ) :
"""Share an entire project with a list of users , identifed by
their usernames .
The read _ only flag ( ' Y ' or ' N ' ) must be set
to ' Y ' to allow write access or sharing .
The share flat ( ' Y ' or ' N ' ) must be set to ' Y... | user_id = kwargs . get ( 'user_id' )
proj_i = _get_project ( project_id )
# Is the sharing user allowed to share this project ?
proj_i . check_share_permission ( int ( user_id ) )
user_id = int ( user_id )
for owner in proj_i . owners :
if user_id == owner . user_id :
break
else :
raise HydraError ( "Pe... |
def close ( self ) :
"""Close the audio file and free associated memory .""" | if not self . closed :
check ( _coreaudio . ExtAudioFileDispose ( self . _obj ) )
self . closed = True |
def outputWord ( self ) :
"""Output report to word docx""" | import docx
from docx . enum . text import WD_ALIGN_PARAGRAPH
doc = docx . Document ( )
doc . styles [ 'Normal' ] . paragraph_format . alignment = WD_ALIGN_PARAGRAPH . JUSTIFY
doc . add_heading ( self . title , level = 0 )
if self . addTime :
from time import localtime , strftime
doc . add_heading ( strftime ( ... |
def post_event ( event , channel = None , username = None , api_url = None , hook = None ) :
'''Send an event to a Mattermost channel .
: param channel : The channel name , either will work .
: param username : The username of the poster .
: param event : The event to send to the Mattermost channel .
: para... | if not api_url :
api_url = _get_api_url ( )
if not hook :
hook = _get_hook ( )
if not username :
username = _get_username ( )
if not channel :
channel = _get_channel ( )
if not event :
log . error ( 'message is a required option.' )
log . debug ( 'Event: %s' , event )
log . debug ( 'Event data: %s' ... |
def all_tables ( self ) -> List [ str ] :
"""List of all known tables
: return :""" | return sorted ( [ k for k in self . __dict__ . keys ( ) if k not in _I2B2Tables . _funcs and not k . startswith ( "_" ) ] ) |
def setMinimum ( self , minimum ) :
"""setter to _ minimum .
Args :
minimum ( int or long ) : new _ minimum value .
Raises :
TypeError : If the given argument is not an integer .""" | if not isinstance ( minimum , int ) :
raise TypeError ( "Argument is not of type int or long" )
self . _minimum = minimum |
def vrrp_vip ( self , ** kwargs ) :
"""Set VRRP VIP .
Args :
int _ type ( str ) : Type of interface . ( gigabitethernet ,
tengigabitethernet , etc ) .
name ( str ) : Name of interface . ( 1/0/5 , 1/0/10 , etc ) .
vrid ( str ) : VRRPv3 ID .
vip ( str ) : IPv4 / IPv6 Virtual IP Address .
rbridge _ id ( ... | int_type = kwargs . pop ( 'int_type' ) . lower ( )
name = kwargs . pop ( 'name' )
vrid = kwargs . pop ( 'vrid' )
vip = kwargs . pop ( 'vip' )
rbridge_id = kwargs . pop ( 'rbridge_id' , '1' )
callback = kwargs . pop ( 'callback' , self . _callback )
valid_int_types = [ 'gigabitethernet' , 'tengigabitethernet' , 'fortygi... |
def to_dict ( self , depth = - 1 , ordered = True , ** kwargs ) :
"""Returns a dict representation of the object .""" | if ordered :
dict_fun = OrderedDict
else :
dict_fun = dict
out = dict_fun ( )
out [ 'name' ] = self . _name
out [ 'id' ] = self . _id
if depth != 0 :
out [ 'children' ] = dict_fun ( [ ( name , child . to_dict ( depth = depth - 1 ) ) for name , child in self . _children . items ( ) ] )
# noqa
return out |
def rn_boundary ( af , b_hi ) :
"""R ( n ) ratio boundary for selecting between [ b _ hi - 1 , b _ hi ]
alpha = b + 2""" | return np . sqrt ( rn_theory ( af , b ) * rn_theory ( af , b - 1 ) ) |
def create_product ( AcceptLanguage = None , Name = None , Owner = None , Description = None , Distributor = None , SupportDescription = None , SupportEmail = None , SupportUrl = None , ProductType = None , Tags = None , ProvisioningArtifactParameters = None , IdempotencyToken = None ) :
"""Creates a new product . ... | pass |
def parent_organisations ( self ) :
'''The organisations this RTC belongs to .''' | class ParentOrg :
def __init__ ( self , sdo_id , org_id ) :
self . sdo_id = sdo_id
self . org_id = org_id
with self . _mutex :
if not self . _parent_orgs :
for sdo in self . _obj . get_organizations ( ) :
if not sdo :
continue
owner = sdo . get_own... |
def get_closest ( self , lon , lat , depth = 0 ) :
"""Get the closest object to the given longitude and latitude
and its distance .
: param lon : longitude in degrees
: param lat : latitude in degrees
: param depth : depth in km ( default 0)
: returns : ( object , distance )""" | xyz = spherical_to_cartesian ( lon , lat , depth )
min_dist , idx = self . kdtree . query ( xyz )
return self . objects [ idx ] , min_dist |
def auto_code_block ( self , node ) :
"""Try to automatically generate nodes for codeblock syntax .
Parameters
node : nodes . literal _ block
Original codeblock node
Returns
tocnode : docutils node
The converted toc tree node , None if conversion is not possible .""" | assert isinstance ( node , nodes . literal_block )
original_node = node
if 'language' not in node :
return None
self . state_machine . reset ( self . document , node . parent , self . current_level )
content = node . rawsource . split ( '\n' )
language = node [ 'language' ]
if language == 'math' :
if self . con... |
def stable_reverse_topological_sort ( graph ) :
"""Return a list of nodes in topological sort order .
This topological sort is a * * unique * * permutation of the nodes
such that an edge from u to v implies that u appears before v in the
topological sort order .
Parameters
graph : NetworkX digraph
A dir... | if not graph . is_directed ( ) :
raise networkx . NetworkXError ( 'Topological sort not defined on undirected graphs.' )
# nonrecursive version
seen = set ( )
explored = set ( )
for v in sorted ( graph . nodes ( ) ) :
if v in explored :
continue
fringe = [ v ]
# nodes yet to look at
while fr... |
def dot ( * , last : bool = False , fileobj : Any = None ) -> None :
"""Print a dot without a newline unless it is the last one .
Useful when you want to display a progress with very little
knowledge .
: param last : whether this is the last dot ( will insert a newline )""" | end = "\n" if last else ""
info ( "." , end = end , fileobj = fileobj ) |
def getInterpretation ( self ) :
"""Get the value of the previously POSTed Tropo action .""" | actions = self . _actions
if ( type ( actions ) is list ) :
dict = actions [ 0 ]
else :
dict = actions
return dict [ 'interpretation' ] |
def _configure_manager ( self ) :
"""Creates the Manager instances to handle monitoring .""" | self . _flavor_manager = CloudCDNFlavorManager ( self , uri_base = "flavors" , resource_class = CloudCDNFlavor , response_key = None , plural_response_key = "flavors" )
self . _services_manager = CloudCDNServiceManager ( self , uri_base = "services" , resource_class = CloudCDNService , response_key = None , plural_resp... |
def thickness ( mesh , points , exterior = False , normals = None , method = 'max_sphere' ) :
"""Find the thickness of the mesh at the given points .
Parameters
points : ( n , 3 ) float , list of points in space
exterior : bool , whether to compute the exterior thickness
( a . k . a . reach )
normals : ( ... | points = np . asanyarray ( points , dtype = np . float64 )
if not util . is_shape ( points , ( - 1 , 3 ) ) :
raise ValueError ( 'points must be (n,3)!' )
if normals is not None :
normals = np . asanyarray ( normals , dtype = np . float64 )
if not util . is_shape ( normals , ( - 1 , 3 ) ) :
raise Val... |
def route ( self , origin , message ) :
'''Using the routing dictionary , dispatch a message to all subscribers
: param origin : name of the origin node
: type origin : : py : class : ` str `
: param message : message to dispatch
: type message : : py : class : ` emit . message . Message ` or subclass''' | # side - effect : we have to know all the routes before we can route . But
# we can ' t resolve them while the object is initializing , so we have to
# do it just in time to route .
self . resolve_node_modules ( )
if not self . routing_enabled :
return
subs = self . routes . get ( origin , set ( ) )
for destination... |
def append ( self , key , data ) :
"""Append the given data to the data that already exists
in the container for the given key .
Only data with equal dimensions ( except the first ) are allowed ,
since they are concatenated / stacked along the first dimension .
Args :
key ( str ) : Key to store data for .... | existing = self . get ( key , mem_map = True )
if existing is not None :
num_existing = existing . shape [ 0 ]
if existing . shape [ 1 : ] != data . shape [ 1 : ] :
error_msg = ( 'The data to append needs to' 'have the same dimensions ({}).' )
raise ValueError ( error_msg . format ( existing . s... |
def generate_trajs ( P , M , N , start = None , stop = None , dt = 1 ) :
"""Generates multiple realizations of the Markov chain with transition matrix P .
Parameters
P : ( n , n ) ndarray
transition matrix
M : int
number of trajectories
N : int
trajectory length
start : int , optional , default = No... | sampler = MarkovChainSampler ( P , dt = dt )
return sampler . trajectories ( M , N , start = start , stop = stop ) |
async def hscan ( self , name , cursor = 0 , match = None , count = None ) :
"""Incrementally return key / value slices in a hash . Also return a cursor
indicating the scan position .
` ` match ` ` allows for filtering the keys by pattern
` ` count ` ` allows for hint the minimum number of returns""" | pieces = [ name , cursor ]
if match is not None :
pieces . extend ( [ b ( 'MATCH' ) , match ] )
if count is not None :
pieces . extend ( [ b ( 'COUNT' ) , count ] )
return await self . execute_command ( 'HSCAN' , * pieces ) |
def add_event ( self , event ) :
"""Adds an event to the event file .
Args :
event : An ` Event ` protocol buffer .""" | if not isinstance ( event , event_pb2 . Event ) :
raise TypeError ( "Expected an event_pb2.Event proto, " " but got %s" % type ( event ) )
self . _async_writer . write ( event . SerializeToString ( ) ) |
def points ( self ) :
'''Return unordered array with all the points in this neuron''' | if self . _points is None :
_points = self . soma . points . tolist ( )
for n in self . neurites :
_points . extend ( n . points . tolist ( ) )
self . _points = np . array ( _points )
return self . _points |
def decompile ( input_ , file_ , output , format_ , jar , limit , decompiler ) :
"""Decompile an APK and create Control Flow Graphs .
Example :
$ androguard resources . arsc""" | from androguard import session
if file_ and input_ :
print ( "Can not give --input and positional argument! " "Please use only one of them!" , file = sys . stderr )
sys . exit ( 1 )
if not input_ and not file_ :
print ( "Give one file to decode!" , file = sys . stderr )
sys . exit ( 1 )
if input_ :
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.