signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def put ( self , item , block = True , timeout = None ) :
'''Put an item into the queue .
If optional args ' block ' is true and ' timeout ' is None ( the default ) ,
block if necessary until a free slot is available . If ' timeout ' is
a non - negative number , it blocks at most ' timeout ' seconds and raise... | self . _parent . _check_closing ( )
with self . _parent . _sync_not_full :
if self . _parent . _maxsize > 0 :
if not block :
if self . _parent . _qsize ( ) >= self . _parent . _maxsize :
raise SyncQueueFull
elif timeout is None :
while self . _parent . _qsize ... |
def _start_node ( node ) :
"""Start the given node VM .
: return : bool - - True on success , False otherwise""" | log . debug ( "_start_node: working on node `%s`" , node . name )
# FIXME : the following check is not optimal yet . When a node is still
# in a starting state , it will start another node here , since the
# ` is _ alive ` method will only check for running nodes ( see issue # 13)
if node . is_alive ( ) :
log . inf... |
def write ( self , filename , arcname = None , compress_type = None ) :
"""Put the bytes from filename into the archive under the name
arcname .""" | if not self . fp :
raise RuntimeError ( "Attempt to write to ZIP archive that was already closed" )
st = os . stat ( filename )
isdir = stat . S_ISDIR ( st . st_mode )
mtime = time . localtime ( st . st_mtime )
date_time = mtime [ 0 : 6 ]
# Create ZipInfo instance to store file information
if arcname is None :
... |
def all_ip_address_in_subnet ( ip_net , cidr ) :
"""Function to return every ip in a subnet
: param ip _ net : Unicast or Multicast IP address or subnet in the following format 192.168.1.1 , 239.1.1.1
: param cidr : CIDR value of 0 to 32
: return :
A list of ip address ' s""" | ip_address_list = list ( )
if not ip_mask ( '{ip_net}/{cidr}' . format ( ip_net = ip_net , cidr = cidr ) , return_tuple = False ) :
LOGGER . critical ( '{network} is not a valid IPv4 network' . format ( network = '{ip_net}/{cidr}' . format ( ip_net = ip_net , cidr = cidr ) ) )
raise ValueError ( '{network} is n... |
def parse_schema ( schema_file ) :
"""parses the schema file and returns the columns that are later going to represent the columns of the genometric space dataframe
: param schema _ file : the path to the schema file
: return : the columns of the schema file""" | e = xml . etree . ElementTree . parse ( schema_file )
root = e . getroot ( )
cols = [ ]
for elem in root . findall ( ".//{http://genomic.elet.polimi.it/entities}field" ) : # XPATH
cols . append ( elem . text )
return cols |
def del_depth ( d , depth ) :
"""Delete all the nodes on specific depth in this dict""" | for node in DictTree . v_depth ( d , depth - 1 ) :
for key in [ key for key in DictTree . k ( node ) ] :
del node [ key ] |
def fake_shell ( self , func , stdout = False ) :
"""Execute a function and decorate its return value in the style of
_ low _ level _ execute _ command ( ) . This produces a return value that looks
like some shell command was run , when really func ( ) was implemented
entirely in Python .
If the function ra... | dct = self . COMMAND_RESULT . copy ( )
try :
rc = func ( )
if stdout :
dct [ 'stdout' ] = repr ( rc )
except mitogen . core . CallError :
LOG . exception ( 'While emulating a shell command' )
dct [ 'rc' ] = 1
dct [ 'stderr' ] = traceback . format_exc ( )
return dct |
def replace ( self , ** kwargs ) :
"""Return a : class : ` . Time ` with one or more components replaced
with new values .""" | return Time ( kwargs . get ( "hour" , self . __hour ) , kwargs . get ( "minute" , self . __minute ) , kwargs . get ( "second" , self . __second ) , kwargs . get ( "tzinfo" , self . __tzinfo ) ) |
def get_html ( self , chart_obj = None , slug = None ) :
"""Get the html and script tag for a chart""" | if chart_obj is None :
if self . chart_obj is None :
self . err ( "No chart object registered, please provide " "one in parameters" )
return
chart_obj = self . chart_obj
try :
if self . engine == "bokeh" :
html = self . _get_bokeh_html ( chart_obj )
if html is None :
... |
def downgrade ( ) :
"""Downgrade database .""" | ctx = op . get_context ( )
insp = Inspector . from_engine ( ctx . connection . engine )
for fk in insp . get_foreign_keys ( 'transaction' ) :
if fk [ 'referred_table' ] == 'accounts_user' :
op . drop_constraint ( op . f ( fk [ 'name' ] ) , 'transaction' , type_ = 'foreignkey' )
with op . batch_alter_table (... |
def ldap_server_maprole_group_ad_group ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
ldap_server = ET . SubElement ( config , "ldap-server" , xmlns = "urn:brocade.com:mgmt:brocade-aaa" )
maprole = ET . SubElement ( ldap_server , "maprole" )
group = ET . SubElement ( maprole , "group" )
ad_group = ET . SubElement ( group , "ad-group" )
ad_group . text = kwargs . pop ( ... |
def register ( self , name , function , plugin , description = None ) :
"""Registers a new document .
. . warning : You can not use any relative links inside a given document .
For instance , sphinx ' s toctree , image , figure or include statements do not work .
: param function : Function , which gets calle... | if name in self . threads . keys ( ) :
raise ThreadExistsException ( "Thread %s was already registered by %s" % ( name , self . threads [ name ] . plugin . name ) )
self . threads [ name ] = Thread ( name , function , plugin , description )
self . __log . debug ( "Thread %s registered by %s" % ( name , plugin . nam... |
def uninstall_trigger_function ( connection : connection , force : bool = False ) -> None :
"""Uninstall the psycopg2 - pgevents trigger function from the database .
Parameters
connection : psycopg2 . extensions . connection
Active connection to a PostGreSQL database .
force : bool
If True , force the un ... | modifier = ''
if force :
modifier = 'CASCADE'
log ( 'Uninstalling trigger function (cascade={})...' . format ( force ) , logger_name = _LOGGER_NAME )
statement = UNINSTALL_TRIGGER_FUNCTION_STATEMENT . format ( modifier = modifier )
execute ( connection , statement ) |
def print_result ( result ) :
"""Print the result , ascii encode if necessary""" | try :
print result
except UnicodeEncodeError :
if sys . stdout . encoding :
print result . encode ( sys . stdout . encoding , 'replace' )
else :
print result . encode ( 'utf8' )
except :
print "Unexpected error attempting to print result" |
def setBreak ( self , breakFlag = True ) :
"""Method to invoke the Python pdb debugger when this element is
about to be parsed . Set breakFlag to True to enable , False to
disable .""" | if breakFlag :
_parseMethod = self . _parse
def breaker ( instring , loc , doActions = True , callPreParse = True ) :
import pdb
pdb . set_trace ( )
_parseMethod ( instring , loc , doActions , callPreParse )
breaker . _originalParseMethod = _parseMethod
self . _parse = breaker
el... |
def check_unused ( intersection , duplicates , intersections ) :
"""Check if a " valid " ` ` intersection ` ` is already in ` ` intersections ` ` .
This assumes that
* ` ` intersection ` ` will have at least one of ` ` s = = 0.0 ` ` or ` ` t = = 0.0 ` `
* At least one of the intersections in ` ` intersections... | for other in intersections :
if ( other . interior_curve == UNUSED_T and intersection . index_first == other . index_first and intersection . index_second == other . index_second ) :
if intersection . s == 0.0 and other . s == 0.0 :
duplicates . append ( intersection )
return True
... |
def outpat ( self , acc = None ) :
"""Determine the full outfile pattern for the given account .
Return None if not specified .""" | outdir = self . outdir ( acc )
outpat = self . get ( 'outpat' , acc = acc )
return os . path . join ( outdir , outpat ) if outdir and outpat else None |
def _generate_class_comment ( self , data_type ) :
"""Emits a generic class comment for a union or struct .""" | if is_struct_type ( data_type ) :
class_type = 'struct'
elif is_union_type ( data_type ) :
class_type = 'union'
else :
raise TypeError ( 'Can\'t handle type %r' % type ( data_type ) )
self . emit ( comment_prefix )
self . emit_wrapped_text ( 'The `{}` {}.' . format ( fmt_class ( data_type . name ) , class_t... |
def centroid_refine_triangulation_by_triangles ( self , triangles ) :
"""return points defining a refined triangulation obtained by bisection of all edges
in the triangulation that are associated with the triangles in the list provided .
Notes
The triangles are here represented as a single index .
The verti... | # Remove duplicates from the list of triangles
triangles = np . unique ( np . array ( triangles ) )
xi , yi = self . face_midpoints ( simplices = self . simplices [ triangles ] )
x_v1 = np . concatenate ( ( self . x , xi ) , axis = 0 )
y_v1 = np . concatenate ( ( self . y , yi ) , axis = 0 )
return x_v1 , y_v1 |
def simple_notification ( connection , queue_name , exchange_name , routing_key , text_body ) :
"""Publishes a simple notification .
Inputs : - connection : A rabbitmq connection object .
- queue _ name : The name of the queue to be checked or created .
- exchange _ name : The name of the notification exchang... | channel = connection . channel ( )
try :
channel . queue_declare ( queue_name , durable = True , exclusive = False , auto_delete = False )
except PreconditionFailed :
pass
try :
channel . exchange_declare ( exchange_name , type = "fanout" , durable = True , auto_delete = False )
except PreconditionFailed :
... |
def missing_intervals ( startdate , enddate , start , end , dateconverter = None , parseinterval = None , intervals = None ) :
'''Given a ` ` startdate ` ` and an ` ` enddate ` ` dates , evaluate the
date intervals from which data is not available . It return a list of
two - dimensional tuples containing start ... | parseinterval = parseinterval or default_parse_interval
dateconverter = dateconverter or todate
startdate = dateconverter ( parseinterval ( startdate , 0 ) )
enddate = max ( startdate , dateconverter ( parseinterval ( enddate , 0 ) ) )
if intervals is not None and not isinstance ( intervals , Intervals ) :
interval... |
async def sinterstore ( self , dest , keys , * args ) :
"""Store the intersection of sets specified by ` ` keys ` ` into a new
set named ` ` dest ` ` . Returns the number of keys in the new set .""" | args = list_or_args ( keys , args )
return await self . execute_command ( 'SINTERSTORE' , dest , * args ) |
def get_tax_rate_by_id ( cls , tax_rate_id , ** kwargs ) :
"""Find TaxRate
Return single instance of TaxRate by its ID .
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async = True
> > > thread = api . get _ tax _ rate _ by _ id ( tax _ rate _ id... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async' ) :
return cls . _get_tax_rate_by_id_with_http_info ( tax_rate_id , ** kwargs )
else :
( data ) = cls . _get_tax_rate_by_id_with_http_info ( tax_rate_id , ** kwargs )
return data |
def _termination_callback ( self , returncode ) :
"""Called when the process has stopped .
: param returncode : Process returncode""" | if self . _started :
log . info ( "VPCS process has stopped, return code: %d" , returncode )
self . _started = False
self . status = "stopped"
self . _process = None
if returncode != 0 :
self . project . emit ( "log.error" , { "message" : "VPCS process has stopped, return code: {}\n{}" . for... |
def _remove ( self , timer ) :
"""Remove timer from heap lock and presence are assumed""" | assert timer . timer_heap == self
del self . timers [ timer ]
assert timer in self . heap
self . heap . remove ( timer )
heapq . heapify ( self . heap ) |
def get_attributes ( self ) :
"""Retrieves the attribute names and values .
Attributes that are set to None are ignored .
Yields :
tuple [ str , object ] : attribute name and value .""" | for attribute_name , attribute_value in iter ( self . __dict__ . items ( ) ) : # Not using startswith to improve performance .
if attribute_name [ 0 ] == '_' or attribute_value is None :
continue
yield attribute_name , attribute_value |
def _ProcessRegularFlowMessages ( self , flow_obj , notification ) :
"""Processes messages for a given flow .""" | session_id = notification . session_id
if not isinstance ( flow_obj , flow . FlowBase ) :
logging . warning ( "%s is not a proper flow object (got %s)" , session_id , type ( flow_obj ) )
stats_collector_instance . Get ( ) . IncrementCounter ( "worker_bad_flow_objects" , fields = [ str ( type ( flow_obj ) ) ] )
... |
def summary ( args ) :
"""% prog summary cdhit . clstr
Parse cdhit . clstr file to get distribution of cluster sizes .""" | from jcvi . graphics . histogram import loghistogram
p = OptionParser ( summary . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 1 :
sys . exit ( not p . print_help ( ) )
clstrfile , = args
cf = ClstrFile ( clstrfile )
data = list ( cf . iter_sizes ( ) )
loghistogram ( data , summary = True ) |
def get_sorted_series_files ( self , startpath = "" , series_number = None , return_files_with_info = False , sort_keys = "SliceLocation" , return_files = True , remove_doubled_slice_locations = True ) :
"""Function returns sorted list of dicom files . File paths are organized
by SeriesUID , StudyUID and FrameUID... | dcmdir = self . files_with_info [ : ]
# select sublist with SeriesNumber
if series_number is not None :
dcmdir = [ line for line in dcmdir if line [ 'SeriesNumber' ] == series_number ]
dcmdir = sort_list_of_dicts ( dcmdir , keys = sort_keys )
logger . debug ( 'SeriesNumber: ' + str ( series_number ) )
if remove_dou... |
def runExperimentPool ( numSequences , numFeatures , numLocations , numObjects , numWorkers = 7 , nTrials = 1 , seqLength = 10 , figure = "" , numRepetitions = 1 , synPermProximalDecL2 = [ 0.001 ] , minThresholdProximalL2 = [ 10 ] , sampleSizeProximalL2 = [ 15 ] , inputSize = [ 1024 ] , basalPredictedSegmentDecrement =... | # Create function arguments for every possibility
args = [ ]
for bd in basalPredictedSegmentDecrement :
for i in inputSize :
for thresh in minThresholdProximalL2 :
for dec in synPermProximalDecL2 :
for s in sampleSizeProximalL2 :
for o in reversed ( numSequenc... |
def immutable_attribs ( cls ) :
"""Class decorator like ` ` attr . s ( frozen = True ) ` ` with improved _ _ repr _ _""" | cls = attr . s ( cls , frozen = True )
defaults = OrderedDict ( [ ( a . name , a . default ) for a in cls . __attrs_attrs__ ] )
def repr_ ( self ) :
from qnet . printing import srepr
real_cls = self . __class__
class_name = real_cls . __name__
args = [ ]
for name in defaults . keys ( ) :
val... |
def Sine ( x , a , omega , phi , y0 ) :
"""Sine function
Inputs :
` ` x ` ` : independent variable
` ` a ` ` : amplitude
` ` omega ` ` : circular frequency
` ` phi ` ` : phase
` ` y0 ` ` : offset
Formula :
` ` a * sin ( x * omega + phi ) + y0 ` `""" | return a * np . sin ( x * omega + phi ) + y0 |
def traverse ( obj , * path , ** kwargs ) :
"""Traverse the object we receive with the given path . Path
items can be either strings or lists of strings ( or any
nested combination thereof ) . Behavior in given cases is
laid out line by line below .""" | if path :
if isinstance ( obj , list ) or isinstance ( obj , tuple ) : # If the current state of the object received is a
# list , return a list of each of its children elements ,
# traversed with the current state of the string
return [ traverse ( x , * path ) for x in obj ]
elif isinstance ( o... |
def edit_conf ( conf_file , out_format = 'simple' , read_only = False , lxc_config = None , ** kwargs ) :
'''Edit an LXC configuration file . If a setting is already present inside the
file , its value will be replaced . If it does not exist , it will be appended
to the end of the file . Comments and blank line... | data = [ ]
try :
conf = read_conf ( conf_file , out_format = out_format )
except Exception :
conf = [ ]
if not lxc_config :
lxc_config = [ ]
lxc_config = copy . deepcopy ( lxc_config )
# search if we want to access net config
# in that case , we will replace all the net configuration
net_config = [ ]
for lx... |
def upload ( ctx , files , max_threads , prompt , forward , reverse , tags , metadata , project_id , coerce_ascii ) :
"""Upload a FASTA or FASTQ ( optionally gzip ' d ) to One Codex""" | appendables = { }
if tags :
appendables [ "tags" ] = [ ]
for tag in tags :
appendables [ "tags" ] . append ( tag )
if metadata :
appendables [ "metadata" ] = { }
for metadata_kv in metadata :
split_metadata = metadata_kv . split ( "=" , 1 )
if len ( split_metadata ) > 1 :
... |
def load_replacement_patterns ( self ) :
"""Check for availability of the specified dictionary .""" | filename = self . dictionary + '.py'
models = self . language + '_models_cltk'
rel_path = os . path . join ( '~/cltk_data' , self . language , 'model' , models , 'semantics' , filename )
path = os . path . expanduser ( rel_path )
logger . info ( 'Loading lemmata or synonyms. This may take a minute.' )
loader = importli... |
def to_hex_string ( data ) :
'''Convert list of integers to a hex string , separated by " : "''' | if isinstance ( data , int ) :
return '%02X' % data
return ':' . join ( [ ( '%02X' % o ) for o in data ] ) |
def generate_lorem_ipsum ( n = 5 , html = True , min = 20 , max = 100 ) :
"""Generate some lorem impsum for the template .""" | from jinja2 . constants import LOREM_IPSUM_WORDS
from random import choice , randrange
words = LOREM_IPSUM_WORDS . split ( )
result = [ ]
for _ in xrange ( n ) :
next_capitalized = True
last_comma = last_fullstop = 0
word = None
last = None
p = [ ]
# each paragraph contains out of 20 to 100 word... |
def check_dups ( iterable , debug_limit = 1000 , ) :
"""Checks an iterable for duplicates
Note that it does not make sense to call this on a set ( )
If calling on a collection without a . count method ,
set @ debug _ limit to - 1.
For custom equality comparisons , create a custom
_ _ eq _ _ and _ _ hash _... | if not iterable :
return
unique = set ( iterable )
if len ( unique ) != len ( iterable ) :
if len ( iterable ) < debug_limit :
dups = [ x for x in unique if iterable . count ( x ) > 1 ]
msg = "Duplicate values: {}" . format ( dups )
else :
msg = ( "Duplicate values, not generating li... |
def version ( ) :
"""Get the version number without importing the mrcfile package .""" | namespace = { }
with open ( os . path . join ( 'mrcfile' , 'version.py' ) ) as f :
exec ( f . read ( ) , namespace )
return namespace [ '__version__' ] |
def features ( self ) :
"""Returns a list of the J - Link embedded features .
Args :
self ( JLink ) : the ` ` JLink ` ` instance
Returns :
A list of strings , each a feature . Example :
` ` [ ' RDI ' , ' FlashBP ' , ' FlashDL ' , ' JFlash ' , ' GDB ' ] ` `""" | buf = ( ctypes . c_char * self . MAX_BUF_SIZE ) ( )
self . _dll . JLINKARM_GetFeatureString ( buf )
result = ctypes . string_at ( buf ) . decode ( ) . strip ( )
if len ( result ) == 0 :
return list ( )
return result . split ( ', ' ) |
def GetNotation ( self , id , type ) :
'''method which searches for notation from < type > list at position < id >
: param id : the number to look for - i . e if you ' re looking for the first one in wrap notation , id will be 0
: param type : post , pre or wrap
: return : the notation class searched for or n... | if type == "post" :
if ( id == - 1 and len ( self . postnotation ) > 0 ) or ( id != - 1 and len ( self . postnotation ) > id ) :
return self . postnotation [ id ]
if type == "pre" :
if ( id == - 1 and len ( self . prenotation ) > 0 ) or ( id != - 1 and len ( self . postnotation ) > id ) :
return... |
def locate_fixed_differences ( ac1 , ac2 ) :
"""Locate variants with no shared alleles between two populations .
Parameters
ac1 : array _ like , int , shape ( n _ variants , n _ alleles )
Allele counts array from the first population .
ac2 : array _ like , int , shape ( n _ variants , n _ alleles )
Allele... | # check inputs
ac1 = asarray_ndim ( ac1 , 2 )
ac2 = asarray_ndim ( ac2 , 2 )
check_dim0_aligned ( ac1 , ac2 )
ac1 , ac2 = ensure_dim1_aligned ( ac1 , ac2 )
# stack allele counts for convenience
pac = np . dstack ( [ ac1 , ac2 ] )
# count numbers of alleles called in each population
pan = np . sum ( pac , axis = 1 )
# c... |
def headers ( params = { } ) :
"""This decorator adds the headers passed in to the response
http : / / flask . pocoo . org / snippets / 100/""" | def decorator ( f ) :
if inspect . isclass ( f ) :
h = headers ( params )
apply_function_to_members ( f , h )
return f
@ functools . wraps ( f )
def decorated_function ( * args , ** kwargs ) :
resp = make_response ( f ( * args , ** kwargs ) )
h = resp . headers
... |
def addNodeToGraph ( nodeName , graphFileHandle , label , width = 0.3 , height = 0.3 , shape = "circle" , colour = "black" , fontsize = 14 ) :
"""Adds a node to the graph .""" | graphFileHandle . write ( "node[width=%s,height=%s,shape=%s,colour=%s,fontsize=%s];\n" % ( width , height , shape , colour , fontsize ) )
graphFileHandle . write ( "%s [label=\"%s\"];\n" % ( nodeName , label ) ) |
def deserialize ( self , value , ** kwargs ) : # pylint : disable = unused - argument
"""Deserialize input value to valid Property value
This method uses the Property : code : ` deserializer ` if available .
Otherwise , it uses : code : ` from _ json ` . Any keyword arguments are
passed through to these metho... | kwargs . update ( { 'trusted' : kwargs . get ( 'trusted' , False ) } )
if self . deserializer is not None :
return self . deserializer ( value , ** kwargs )
if value is None :
return None
return self . from_json ( value , ** kwargs ) |
def inspect_mem ( self , mem ) :
"""Get the values in a map during the current simulation cycle .
: param mem : the memory to inspect
: return : { address : value }
Note that this returns the current memory state . Modifying the dictonary
will also modify the state in the simulator""" | if isinstance ( mem , RomBlock ) :
raise PyrtlError ( "ROM blocks are not stored in the simulation object" )
return self . mems [ self . _mem_varname ( mem ) ] |
def convert_pathway_mapping ( self , other_pathway_mapping ) :
"""Used to convert the pathway - to - vertex id mapping in one CoNetwork
to the one used in the current CoNetwork ( ` self ` ) .
The following tasks are carried out in the remapping :
(1 ) If ` self . pathways ` contains the pathway to be merged ,... | vertex_id_conversion = { }
for pathway , vertex_id in other_pathway_mapping . items ( ) :
if pathway in self . pathways :
vertex_id_conversion [ vertex_id ] = self . pathways [ pathway ]
else :
self_vertex_id = self . add_pathway ( pathway )
self . vertices [ self_vertex_id ] = Vertex ( ... |
def custom_module_classes ( ) :
"""MultiQC Custom Content class . This module does a lot of different
things depending on the input and is as flexible as possible .
NB : THIS IS TOTALLY DIFFERENT TO ALL OTHER MODULES""" | # Dict to hold parsed data . Each key should contain a custom data type
# eg . output from a particular script . Note that this script may pick
# up many different types of data from many different sources .
# Second level keys should be ' config ' and ' data ' . Data key should then
# contain sample names , and finall... |
def main ( argv = None , input_stream = stdin , output_stream = stdout , error_stream = stderr ) :
"""runs inline function - more info run ` cbox - - help `""" | args = _parse_args ( argv )
args_dict = args . __dict__ . copy ( )
inline_str = args_dict . pop ( 'inline' )
modules = args_dict . pop ( 'modules' )
func = get_inline_func ( inline_str , modules , ** args_dict )
return cbox . main ( func = func , argv = [ ] , input_stream = input_stream , output_stream = output_stream ... |
def get_word_under_cursor_legacy ( self ) :
"""Returns the document word under cursor ( Using Qt legacy " QTextCursor . WordUnderCursor " ) .
: return : Word under cursor .
: rtype : QString""" | cursor = self . textCursor ( )
cursor . select ( QTextCursor . WordUnderCursor )
return cursor . selectedText ( ) |
def clean ( image , mask = None , iterations = 1 ) :
'''Remove isolated pixels
0 0 0 0 0 0
0 1 0 - > 0 0 0
0 0 0 0 0 0
Border pixels and pixels adjoining masks are removed unless one valid
neighbor is true .''' | global clean_table
if mask is None :
masked_image = image
else :
masked_image = image . astype ( bool ) . copy ( )
masked_image [ ~ mask ] = False
result = table_lookup ( masked_image , clean_table , False , iterations )
if not mask is None :
result [ ~ mask ] = image [ ~ mask ]
return result |
def _conditions ( self , full_path , environ ) :
"""Return a tuple of etag , last _ modified by mtime from stat .""" | mtime = os . stat ( full_path ) . st_mtime
size = os . stat ( full_path ) . st_size
return str ( mtime ) , rfc822 . formatdate ( mtime ) , size |
def ListDir ( self , path = "temp" ) :
"""Returns a list of files in the specified path ( directory ) , or an
empty list if the directory doesn ' t exist .""" | full_path = _os . path . join ( self . path_home , path )
# only if the path exists !
if _os . path . exists ( full_path ) and _os . path . isdir ( full_path ) :
return _os . listdir ( full_path )
else :
return [ ] |
def get_event_discount ( self , id , discount_id , ** data ) :
"""GET / events / : id / discounts / : discount _ id /
Gets a : format : ` discount ` by ID as the key ` ` discount ` ` .""" | return self . get ( "/events/{0}/discounts/{0}/" . format ( id , discount_id ) , data = data ) |
def clear ( self ) -> None :
"""Clear all cache entries for directory and , if it is a ' pure ' directory , remove the directory itself""" | if self . _cache_directory is not None : # Safety - if there isn ' t a cache directory file , this probably isn ' t a valid cache
assert os . path . exists ( self . _cache_directory_index ) , "Attempt to clear a non-existent cache"
self . _load ( )
# Shouldn ' t have any impact but . . .
for e in self .... |
def _sql_expand_insert ( self , spec , key_prefix = '' , col_prefix = '' ) :
"""Expand a dict so it fits in a INSERT clause""" | col = list ( spec )
sql = '('
sql += ', ' . join ( col_prefix + key for key in col )
sql += ') VALUES ('
sql += ', ' . join ( '%(' + key_prefix + key + ')s' for key in col )
sql += ')'
params = { }
for key in spec :
params [ key_prefix + key ] = spec [ key ]
return sql , params |
def manage_pool ( hostname , username , password , name , allow_nat = None , allow_snat = None , description = None , gateway_failsafe_device = None , ignore_persisted_weight = None , ip_tos_to_client = None , ip_tos_to_server = None , link_qos_to_client = None , link_qos_to_server = None , load_balancing_mode = None ,... | ret = { 'name' : name , 'changes' : { } , 'result' : False , 'comment' : '' }
if __opts__ [ 'test' ] :
return _test_output ( ret , 'manage' , params = { 'hostname' : hostname , 'username' : username , 'password' : password , 'name' : name , 'allow_nat' : allow_nat , 'allow_snat' : allow_snat , 'description' : descr... |
def rollback ( using = None , sid = None ) :
"""Possibility of calling transaction . rollback ( ) in new Django versions ( in atomic block ) .
Important : transaction savepoint ( sid ) is required for Django < 1.8""" | if sid :
django . db . transaction . savepoint_rollback ( sid )
else :
try :
django . db . transaction . rollback ( using )
except django . db . transaction . TransactionManagementError :
django . db . transaction . set_rollback ( True , using ) |
def reassign_arguments ( self ) :
"""Deal with optional stringlist before a required one .""" | condition = ( "variable-list" in self . arguments and "list-of-flags" not in self . arguments )
if condition :
self . arguments [ "list-of-flags" ] = ( self . arguments . pop ( "variable-list" ) )
self . rargs_cnt = 1 |
def dijkstra_update_heap ( graph , weight , source = 0 , target = None ) :
"""single source shortest paths by Dijkstra
with a heap implementing item updates
: param graph : adjacency list or adjacency dictionary of a directed graph
: param weight : matrix or adjacency dictionary
: assumes : weights are non ... | n = len ( graph )
assert all ( weight [ u ] [ v ] >= 0 for u in range ( n ) for v in graph [ u ] )
prec = [ None ] * n
dist = [ float ( 'inf' ) ] * n
dist [ source ] = 0
heap = OurHeap ( [ ( dist [ node ] , node ) for node in range ( n ) ] )
while heap :
dist_node , node = heap . pop ( )
# Closest node from sou... |
def nacm_denied_data_writes ( self , ** kwargs ) :
"""Auto Generated Code""" | config = ET . Element ( "config" )
nacm = ET . SubElement ( config , "nacm" , xmlns = "urn:ietf:params:xml:ns:yang:ietf-netconf-acm" )
denied_data_writes = ET . SubElement ( nacm , "denied-data-writes" )
denied_data_writes . text = kwargs . pop ( 'denied_data_writes' )
callback = kwargs . pop ( 'callback' , self . _cal... |
def start ( self ) :
"""Start the listener .
This starts up a background thread to monitor the queue for
items to process .""" | self . _thread = t = threading . Thread ( target = self . _monitor )
t . setDaemon ( True )
t . start ( ) |
def to_match ( self ) :
"""Return a unicode object with the MATCH representation of this expression .""" | self . validate ( )
mark_name , field_name = self . fold_scope_location . get_location_name ( )
validate_safe_string ( mark_name )
template = u'$%(mark_name)s.%(field_name)s'
template_data = { 'mark_name' : mark_name , }
if field_name == COUNT_META_FIELD_NAME :
template_data [ 'field_name' ] = 'size()'
else :
i... |
def save_metadata_json ( self , filename : str , structure : JsonExportable ) -> None :
"""Saves metadata JSON file of a structure .""" | if self . compress_json :
filename += '.json.xz'
else :
filename += '.json'
save_structure_to_file ( structure , filename )
if isinstance ( structure , ( Post , StoryItem ) ) : # log ' json ' message when saving Post or StoryItem
self . context . log ( 'json' , end = ' ' , flush = True ) |
def _sighash_anyone_can_pay ( self , index , copy_tx , sighash_type ) :
'''int , byte - like , Tx , int - > bytes
Applies SIGHASH _ ANYONECANPAY procedure .
Should be called by another SIGHASH procedure .
Not on its own .
https : / / en . bitcoin . it / wiki / OP _ CHECKSIG # Procedure _ for _ Hashtype _ SI... | # The txCopy input vector is resized to a length of one .
copy_tx_ins = [ copy_tx . tx_ins [ index ] ]
copy_tx = copy_tx . copy ( tx_ins = copy_tx_ins )
return self . _sighash_final_hashing ( copy_tx , sighash_type | shared . SIGHASH_ANYONECANPAY ) |
def can_expand_to ( self , other_column ) :
"""returns True if this column can be expanded to the size of the
other column""" | if not self . is_string ( ) or not other_column . is_string ( ) :
return False
return other_column . string_size ( ) > self . string_size ( ) |
def _display_completions_like_readline ( cli , completions ) :
"""Display the list of completions in columns above the prompt .
This will ask for a confirmation if there are too many completions to fit
on a single page and provide a paginator to walk through them .""" | from prompt_toolkit . shortcuts import create_confirm_application
assert isinstance ( completions , list )
# Get terminal dimensions .
term_size = cli . output . get_size ( )
term_width = term_size . columns
term_height = term_size . rows
# Calculate amount of required columns / rows for displaying the
# completions . ... |
def info_hash ( self ) :
""": return : The SHA - 1 info hash of the torrent . Useful for generating
magnet links .
. . note : : ` ` generate ( ) ` ` must be called first .""" | if getattr ( self , '_data' , None ) :
return sha1 ( bencode ( self . _data [ 'info' ] ) ) . hexdigest ( )
else :
raise exceptions . TorrentNotGeneratedException |
def _compensate_pressure ( self , adc_p ) :
"""Compensate pressure .
Formula from datasheet Bosch BME280 Environmental sensor .
8.1 Compensation formulas in double precision floating point
Edition BST - BME280 - DS001-10 | Revision 1.1 | May 2015.""" | var_1 = ( self . _temp_fine / 2.0 ) - 64000.0
var_2 = ( ( var_1 / 4.0 ) * ( var_1 / 4.0 ) ) / 2048
var_2 *= self . _calibration_p [ 5 ]
var_2 += ( ( var_1 * self . _calibration_p [ 4 ] ) * 2.0 )
var_2 = ( var_2 / 4.0 ) + ( self . _calibration_p [ 3 ] * 65536.0 )
var_1 = ( ( ( self . _calibration_p [ 2 ] * ( ( ( var_1 /... |
def disco ( self , code , lasti = - 1 , file = None ) :
"""Disassemble a code object .""" | return _disco ( self . python_version , code , timestamp = 0 , out = file , is_pypy = self . is_pypy , header = False ) |
def _run ( handle_data , initialize , before_trading_start , analyze , algofile , algotext , defines , data_frequency , capital_base , bundle , bundle_timestamp , start , end , output , trading_calendar , print_algo , metrics_set , local_namespace , environ , blotter , benchmark_returns ) :
"""Run a backtest for th... | if benchmark_returns is None :
benchmark_returns , _ = load_market_data ( environ = environ )
if algotext is not None :
if local_namespace :
ip = get_ipython ( )
# noqa
namespace = ip . user_ns
else :
namespace = { }
for assign in defines :
try :
name ... |
def padded_ds ( ll_input , size = ( 250 , 300 ) , resize_method = ResizeMethod . CROP , padding_mode = 'zeros' , ** kwargs ) :
"For a LabelList ` ll _ input ` , resize each image to ` size ` using ` resize _ method ` and ` padding _ mode ` ." | return ll_input . transform ( tfms = crop_pad ( ) , size = size , resize_method = resize_method , padding_mode = padding_mode ) |
def _DetermineOperatingSystem ( self , searcher ) :
"""Tries to determine the underlying operating system .
Args :
searcher ( dfvfs . FileSystemSearcher ) : file system searcher .
Returns :
str : operating system for example " Windows " . This should be one of
the values in definitions . OPERATING _ SYSTE... | find_specs = [ file_system_searcher . FindSpec ( location = '/etc' , case_sensitive = False ) , file_system_searcher . FindSpec ( location = '/System/Library' , case_sensitive = False ) , file_system_searcher . FindSpec ( location = '/Windows/System32' , case_sensitive = False ) , file_system_searcher . FindSpec ( loca... |
def render ( self , context ) :
self . prepare ( context )
"Cached wrapper around self . _ render ( ) ." | if getattr ( settings , 'DOUBLE_RENDER' , False ) and self . can_double_render :
if 'SECOND_RENDER' not in context :
return self . double_render ( )
key = self . get_cache_key ( )
if key :
rend = cache . get ( key )
if rend is None :
rend = self . _render ( context )
cache . set ( ke... |
async def reclaim_task ( context , task ) :
"""Try to reclaim a task from the queue .
This is a keepalive / heartbeat . Without it the job will expire and
potentially be re - queued . Since this is run async from the task , the
task may complete before we run , in which case we ' ll get a 409 the next
time ... | while True :
log . debug ( "waiting %s seconds before reclaiming..." % context . config [ 'reclaim_interval' ] )
await asyncio . sleep ( context . config [ 'reclaim_interval' ] )
if task != context . task :
return
log . debug ( "Reclaiming task..." )
try :
context . reclaim_task = aw... |
def handle ( self , * args , ** options ) :
"""Queues the function given with the first argument with the
parameters given with the rest of the argument list .""" | verbosity = int ( options . get ( 'verbosity' , 1 ) )
timeout = options . get ( 'timeout' )
queue = get_queue ( options . get ( 'queue' ) )
job = queue . enqueue_call ( args [ 0 ] , args = args [ 1 : ] , timeout = timeout )
if verbosity :
print ( 'Job %s created' % job . id ) |
def search_disk_size ( self , search_index ) :
"""Retrieves disk size information about a specified search index within
the design document , returns dictionary
GET databasename / _ design / { ddoc } / _ search _ disk _ size / { search _ index }""" | ddoc_search_disk_size = self . r_session . get ( '/' . join ( [ self . document_url , '_search_disk_size' , search_index ] ) )
ddoc_search_disk_size . raise_for_status ( )
return response_to_json_dict ( ddoc_search_disk_size ) |
def create_fpath_dir ( self , fpath : str ) :
"""Creates directory for fpath .""" | os . makedirs ( os . path . dirname ( fpath ) , exist_ok = True ) |
def merge_regions ( self , id1 , id2 ) :
"""Merge two regions into one .
The merged region will take on the id1 identifier .
: param id1 : region 1 identifier
: param id2 : region 2 identifier""" | region2 = self . region_by_identifier ( id2 )
self [ region2 ] = id1 |
def decode_consumer_metadata_response ( cls , response ) :
"""Decode GroupCoordinatorResponse . Note that ConsumerMetadataResponse is
renamed to GroupCoordinatorResponse in 0.9 +
Arguments :
response : response to decode""" | return ConsumerMetadataResponse ( response . error_code , response . coordinator_id , response . host , response . port , ) |
def as_qubit_order ( val : 'qubit_order_or_list.QubitOrderOrList' ) -> 'QubitOrder' :
"""Converts a value into a basis .
Args :
val : An iterable or a basis .
Returns :
The basis implied by the value .""" | if isinstance ( val , collections . Iterable ) :
return QubitOrder . explicit ( val )
if isinstance ( val , QubitOrder ) :
return val
raise ValueError ( "Don't know how to interpret <{}> as a Basis." . format ( val ) ) |
def plot_acf ( series , ax = None , lags = None , alpha = None , use_vlines = True , unbiased = False , fft = True , title = 'Autocorrelation' , zero = True , vlines_kwargs = None , show = True , ** kwargs ) :
"""Plot a series ' auto - correlation as a line plot .
A wrapper method for the statsmodels ` ` plot _ a... | _err_for_no_mpl ( )
res = pacf ( x = series , ax = ax , lags = lags , alpha = alpha , use_vlines = use_vlines , unbiased = unbiased , fft = fft , title = title , zero = zero , vlines_kwargs = vlines_kwargs , ** kwargs )
return _show_or_return ( res , show ) |
def guidance_UV ( index ) :
"""Return Met Office guidance regarding UV exposure based on UV index""" | if 0 < index < 3 :
guidance = "Low exposure. No protection required. You can safely stay outside"
elif 2 < index < 6 :
guidance = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen"
elif 5 < index < 8 :
guidance = "High exposure. Seek shade during midday hours, cover up and wear... |
def parse_value ( source : SourceType , ** options : dict ) -> ValueNode :
"""Parse the AST for a given string containing a GraphQL value .
Throws GraphQLError if a syntax error is encountered .
This is useful within tools that operate upon GraphQL Values directly and in
isolation of complete GraphQL document... | if isinstance ( source , str ) :
source = Source ( source )
lexer = Lexer ( source , ** options )
expect_token ( lexer , TokenKind . SOF )
value = parse_value_literal ( lexer , False )
expect_token ( lexer , TokenKind . EOF )
return value |
def image ( self , raw_url , title = '' , alt = '' ) :
"""Adapt a standard Markdown image to a generated rendition set .
Container arguments used ( in addition to the rendition tags ) :
div _ class - - The CSS class name to use on any wrapper div
div _ style - - Additional CSS styles to apply to the wrapper d... | # pylint : disable = too - many - locals
text = ''
image_specs = raw_url
if title :
image_specs += ' "{}"' . format ( title )
alt , container_args = image . parse_alt_text ( alt )
container_args = { ** self . _config , ** container_args }
spec_list , original_count = image . get_spec_list ( image_specs , container_... |
def publish ( self ) :
"""Publish GitHub release as record .""" | with db . session . begin_nested ( ) :
deposit = self . deposit_class . create ( self . metadata )
deposit [ '_deposit' ] [ 'created_by' ] = self . event . user_id
deposit [ '_deposit' ] [ 'owners' ] = [ self . event . user_id ]
# Fetch the deposit files
for key , url in self . files :
depos... |
def run ( self , out , model_inputs , X ) :
"""Runs the model while also setting the learning phase flags to False .""" | feed_dict = dict ( zip ( model_inputs , X ) )
for t in self . learning_phase_flags :
feed_dict [ t ] = False
return self . session . run ( out , feed_dict ) |
def subjects ( subjects = None , recursive = False , include_tables = False , lang = DEFAULT_LANGUAGE ) :
"""List subjects from the subject hierarchy .
If subjects is not given , the root subjects will be used .
Returns a generator .""" | request = Request ( 'subjects' , * subjects , recursive = recursive , includeTables = include_tables , lang = lang )
return ( Subject ( subject , lang = lang ) for subject in request . json ) |
def convertToRateMatrix ( self , Q ) :
"""Converts the initial matrix to a rate matrix .
We make all rows in Q sum to zero by subtracting the row sums from the diagonal .""" | rowSums = Q . sum ( axis = 1 ) . getA1 ( )
idxRange = np . arange ( Q . shape [ 0 ] )
Qdiag = coo_matrix ( ( rowSums , ( idxRange , idxRange ) ) , shape = Q . shape ) . tocsr ( )
return Q - Qdiag |
def polymorph_response ( response , poly , bqm , penalty_strength = None , keep_penalty_variables = True , discard_unsatisfied = False ) :
"""Transforms the sampleset for the higher order problem .
Given a response of a penalized HUBO , this function creates a new sampleset
object , taking into account penalty ... | record = response . record
penalty_vector = penalty_satisfaction ( response , bqm )
original_variables = bqm . variables
if discard_unsatisfied :
samples_to_keep = list ( map ( bool , list ( penalty_vector ) ) )
penalty_vector = np . array ( [ True ] * np . sum ( samples_to_keep ) )
else :
samples_to_keep =... |
def publish_events ( self , events ) :
"""PublishEvents .
[ Preview API ]
: param [ CustomerIntelligenceEvent ] events :""" | content = self . _serialize . body ( events , '[CustomerIntelligenceEvent]' )
self . _send ( http_method = 'POST' , location_id = 'b5cc35c2-ff2b-491d-a085-24b6e9f396fd' , version = '5.0-preview.1' , content = content ) |
def hid ( manufacturer : str , serial_number : str , model : str ) -> str :
"""Computes the HID for the given properties of a device . The HID is suitable to use to an URI .""" | return Naming . url_word ( manufacturer ) + '-' + Naming . url_word ( serial_number ) + '-' + Naming . url_word ( model ) |
def get_task_scfcycles ( self , nids = None , wslice = None , task_class = None , exclude_ok_tasks = False ) :
"""Return list of ( taks , scfcycle ) tuples for all the tasks in the flow with a SCF algorithm
e . g . electronic GS - SCF iteration , DFPT - SCF iterations etc .
Args :
nids : List of node identifi... | select_status = [ self . S_RUN ] if exclude_ok_tasks else [ self . S_RUN , self . S_OK ]
tasks_cycles = [ ]
for task in self . select_tasks ( nids = nids , wslice = wslice ) : # Fileter
if task . status not in select_status or task . cycle_class is None :
continue
if task_class is not None and not task ... |
def reset ( self ) :
"""Clear out the state of the BuildGraph , in particular Target mappings and dependencies .
: API : public""" | self . _target_by_address = OrderedDict ( )
self . _target_dependencies_by_address = defaultdict ( OrderedSet )
self . _target_dependees_by_address = defaultdict ( OrderedSet )
self . _derived_from_by_derivative = { }
# Address - > Address .
self . _derivatives_by_derived_from = defaultdict ( list )
# Address - > list ... |
def locate ( self , pattern ) :
'''Find sequences matching a pattern . For a circular sequence , the
search extends over the origin .
: param pattern : str or NucleicAcidSequence for which to find matches .
: type pattern : str or coral . DNA
: returns : A list of top and bottom strand indices of matches . ... | top_matches = self . top . locate ( pattern )
bottom_matches = self . bottom . locate ( pattern )
return [ top_matches , bottom_matches ] |
def cdhit_clusters_from_seqs ( seqs , moltype = DNA , params = None ) :
"""Returns the CD - HIT clusters given seqs
seqs : dict like collection of sequences
moltype : cogent . core . moltype object
params : cd - hit parameters
NOTE : This method will call CD _ HIT if moltype is PROTIEN ,
CD _ HIT _ EST if... | # keys are not remapped . Tested against seq _ ids of 100char length
seqs = SequenceCollection ( seqs , MolType = moltype )
# Create mapping between abbreviated IDs and full IDs
int_map , int_keys = seqs . getIntMap ( )
# Create SequenceCollection from int _ map .
int_map = SequenceCollection ( int_map , MolType = molt... |
def _parse_track_dim ( self , d1 , interp = True , phys = False ) :
"""Parse the dimension to plot the stream track for""" | if interp :
interpStr = 'interpolated'
else :
interpStr = ''
if d1 . lower ( ) == 'x' :
tx = self . __dict__ [ '_%sObsTrackXY' % interpStr ] [ : , 0 ]
elif d1 . lower ( ) == 'y' :
tx = self . __dict__ [ '_%sObsTrackXY' % interpStr ] [ : , 1 ]
elif d1 . lower ( ) == 'z' :
tx = self . __dict__ [ '_%sO... |
def create_directories ( datadir , sitedir , srcdir = None ) :
"""Create expected directories in datadir , sitedir
and optionally srcdir""" | # It ' s possible that the datadir already exists
# ( we ' re making a secondary site )
if not path . isdir ( datadir ) :
os . makedirs ( datadir , mode = 0o700 )
try : # This should take care if the ' site ' subdir if needed
os . makedirs ( sitedir , mode = 0o700 )
except OSError :
raise DatacatsError ( "S... |
def get ( self , sid ) :
"""Constructs a AssetVersionContext
: param sid : The sid
: returns : twilio . rest . serverless . v1 . service . asset . asset _ version . AssetVersionContext
: rtype : twilio . rest . serverless . v1 . service . asset . asset _ version . AssetVersionContext""" | return AssetVersionContext ( self . _version , service_sid = self . _solution [ 'service_sid' ] , asset_sid = self . _solution [ 'asset_sid' ] , sid = sid , ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.