signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def milestone ( self , number ) :
"""Get the milestone indicated by ` ` number ` ` .
: param int number : ( required ) , unique id number of the milestone
: returns : : class : ` Milestone < github3 . issues . milestone . Milestone > `""" | json = None
if int ( number ) > 0 :
url = self . _build_url ( 'milestones' , str ( number ) , base_url = self . _api )
json = self . _json ( self . _get ( url ) , 200 )
return Milestone ( json , self ) if json else None |
def _config ( key , mandatory = True , opts = None ) :
'''Return a value for ' name ' from master config file options or defaults .''' | try :
if opts :
value = opts [ 'auth.ldap.{0}' . format ( key ) ]
else :
value = __opts__ [ 'auth.ldap.{0}' . format ( key ) ]
except KeyError :
try :
value = __defopts__ [ 'auth.ldap.{0}' . format ( key ) ]
except KeyError :
if mandatory :
msg = 'missing auth... |
def fastp_general_stats_table ( self ) :
"""Take the parsed stats from the fastp report and add it to the
General Statistics table at the top of the report""" | headers = OrderedDict ( )
headers [ 'pct_duplication' ] = { 'title' : '% Duplication' , 'description' : 'Duplication rate in filtered reads' , 'max' : 100 , 'min' : 0 , 'suffix' : '%' , 'scale' : 'RdYlGn-rev' }
headers [ 'after_filtering_q30_rate' ] = { 'title' : '% > Q30' , 'description' : 'Percentage of reads > Q30 a... |
def load ( self ) :
"""Load data , from default location
Returns :
pandas . DataFrame : columns ' key ' ( NUTS2 code ) , ' name '""" | # read file , keep all values as strings
df = pd . read_csv ( self . input_file , sep = ',' , quotechar = '"' , encoding = 'utf-8' , dtype = object )
# wer are only interested in the NUTS code and description , rename them also
df = df [ [ 'NUTS-Code' , 'Description' ] ]
df . columns = [ 'key' , 'name' ]
# we only want... |
def html ( content , ** kwargs ) :
"""HTML ( Hypertext Markup Language )""" | if hasattr ( content , 'read' ) :
return content
elif hasattr ( content , 'render' ) :
return content . render ( ) . encode ( 'utf8' )
return str ( content ) . encode ( 'utf8' ) |
def csv_writer ( csvfile ) :
"""Get a CSV writer for the version of python that is being run .""" | if sys . version_info >= ( 3 , ) :
writer = csv . writer ( csvfile , delimiter = ',' , lineterminator = '\n' )
else :
writer = csv . writer ( csvfile , delimiter = b',' , lineterminator = '\n' )
return writer |
def compile ( self , prog , features = Features . ALL ) :
"""Currently this compiler simply returns an interpreter instead of compiling
TODO : Write this compiler to increase LPProg run speed and to prevent exceeding maximum recursion depth
Args :
prog ( str ) : A string containing the program .
features ( ... | return LPProg ( Parser ( Tokenizer ( prog , features ) , features ) . program ( ) , features ) |
def _set_property ( self , name , value ) :
"""Set property ` name ` to ` value ` , but only if it is part of the mapping
returned from ` worker _ mapping ` ( ie - data transported to frontend ) .
This method is used from the REST API DB , so it knows what to set and
what not , to prevent users from setting i... | if name in worker_mapping ( ) . keys ( ) :
setattr ( self , name , value )
return
raise KeyError ( "Can't set `%s`!" % name ) |
def get_index ( self , bucket , index , startkey , endkey = None , return_terms = None , max_results = None , continuation = None , timeout = None , term_regex = None ) :
"""Performs a secondary index query .""" | raise NotImplementedError |
def citeFilter ( self , keyString = '' , field = 'all' , reverse = False , caseSensitive = False ) :
"""Filters ` Records ` by some string , _ keyString _ , in their citations and returns all ` Records ` with at least one citation possessing _ keyString _ in the field given by _ field _ .
# Parameters
_ keyStri... | retRecs = [ ]
keyString = str ( keyString )
for R in self :
try :
if field == 'all' :
for cite in R . get ( 'citations' ) :
if caseSensitive :
if keyString in cite . original :
retRecs . append ( R )
break
... |
def snapshot_delete ( repository , snapshot , hosts = None , profile = None ) :
'''. . versionadded : : 2017.7.0
Delete snapshot from specified repository .
repository
Repository name
snapshot
Snapshot name
CLI example : :
salt myminion elasticsearch . snapshot _ delete testrepo testsnapshot''' | es = _get_instance ( hosts , profile )
try :
result = es . snapshot . delete ( repository = repository , snapshot = snapshot )
return result . get ( 'acknowledged' , False )
except elasticsearch . NotFoundError :
return True
except elasticsearch . TransportError as e :
raise CommandExecutionError ( "Can... |
def nii_gzip ( imfile , outpath = '' ) :
'''Compress * . gz file''' | import gzip
with open ( imfile , 'rb' ) as f :
d = f . read ( )
# Now store the compressed data
if outpath == '' :
fout = imfile + '.gz'
else :
fout = os . path . join ( outpath , os . path . basename ( imfile ) + '.gz' )
# store compressed file data from ' d ' variable
with gzip . open ( fout , 'wb' ) as f... |
def max_ver ( ver1 , ver2 ) :
"""Returns the greater version of two versions
: param ver1 : version string 1
: param ver2 : version string 2
: return : the greater version of the two
: rtype : : class : ` VersionInfo `
> > > import semver
> > > semver . max _ ver ( " 1.0.0 " , " 2.0.0 " )
'2.0.0'""" | cmp_res = compare ( ver1 , ver2 )
if cmp_res == 0 or cmp_res == 1 :
return ver1
else :
return ver2 |
def bulk_delete ( handler , request ) :
"""Bulk delete items""" | ids = request . GET . getall ( 'ids' )
Message . delete ( ) . where ( Message . id << ids ) . execute ( )
raise muffin . HTTPFound ( handler . url ) |
def write_mesa ( self , mesa_isos_file = 'isos.txt' , add_excess_iso = 'fe56' , outfile = 'xa_iniabu.dat' , header_string = 'initial abundances for a MESA run' , header_char = '!' ) :
'''Write initial abundance file , returns written abundances and
mesa names .
Parameters
mesa _ isos _ file : string , optiona... | f = open ( 'isos.txt' )
a = f . readlines ( )
isos = [ ]
for i in range ( len ( a ) ) :
isos . append ( a [ i ] . strip ( ) . rstrip ( ',' ) )
mesa_names = [ ]
abus = [ ]
for i in range ( len ( self . z ) ) :
b = self . names [ i ] . split ( )
a = ''
a = a . join ( b )
if a in isos :
mesa_na... |
def from_raw ( self , rval : RawScalar , jptr : JSONPointer = "" ) -> ScalarValue :
"""Override the superclass method .""" | res = self . type . from_raw ( rval )
if res is None :
raise RawTypeError ( jptr , self . type . yang_type ( ) + " value" )
return res |
def tai_timestamp ( ) :
"""Return current TAI timestamp .""" | timestamp = time . time ( )
date = datetime . utcfromtimestamp ( timestamp )
if date . year < 1972 :
return timestamp
offset = 10 + timestamp
leap_seconds = [ ( 1972 , 1 , 1 ) , ( 1972 , 7 , 1 ) , ( 1973 , 1 , 1 ) , ( 1974 , 1 , 1 ) , ( 1975 , 1 , 1 ) , ( 1976 , 1 , 1 ) , ( 1977 , 1 , 1 ) , ( 1978 , 1 , 1 ) , ( 197... |
def from_envvar ( self , variable_name ) :
"""Load a configuration from an environment variable pointing to
a configuration file .
: param variable _ name : name of the environment variable
: return : bool . ` ` True ` ` if able to load config , ` ` False ` ` otherwise .""" | config_file = os . environ . get ( variable_name )
if not config_file :
raise RuntimeError ( "The environment variable %r is not set and " "thus configuration could not be loaded." % variable_name )
return self . from_pyfile ( config_file ) |
def signature ( f , s = None , block_size = RS_DEFAULT_BLOCK_LEN ) :
"""Generate a signature for the file ` f ` . The signature will be written to ` s ` .
If ` s ` is omitted , a temporary file will be used . This function returns the
signature file ` s ` . You can specify the size of the blocks using the
opt... | if s is None :
s = tempfile . SpooledTemporaryFile ( max_size = MAX_SPOOL , mode = 'wb+' )
job = _librsync . rs_sig_begin ( block_size , RS_DEFAULT_STRONG_LEN )
try :
_execute ( job , f , s )
finally :
_librsync . rs_job_free ( job )
return s |
def task ( self , * args , ** kwargs ) :
"""Get Task Definition
This end - point will return the task - definition . Notice that the task
definition may have been modified by queue , if an optional property is
not specified the queue may provide a default value .
This method gives output : ` ` v1 / task . j... | return self . _makeApiCall ( self . funcinfo [ "task" ] , * args , ** kwargs ) |
def tile ( self , username , style_id , z , x , y , tile_size = 512 , retina = False ) :
"/ styles / v1 / { username } / { style _ id } / tiles / { tileSize } / { z } / { x } / { y } { @ 2x }" | if tile_size not in ( 256 , 512 ) :
raise errors . ImageSizeError ( 'tile_size must be 256 or 512 pixels' )
pth = '/{username}/{style_id}/tiles/{tile_size}/{z}/{x}/{y}'
values = dict ( username = username , style_id = style_id , tile_size = tile_size , z = z , x = x , y = y )
uri = URITemplate ( self . baseuri + pt... |
async def load ( self , request ) :
"""Load session from cookies .""" | if SESSION_KEY not in request :
session = Session ( self . cfg . secret , key = self . cfg . session_cookie , max_age = self . cfg . max_age , domain = self . cfg . domain )
session . load ( request . cookies )
self . app . logger . debug ( 'Session loaded: %s' , session )
request [ SESSION_KEY ] = requ... |
def _ImportHookBySuffix ( name , globals = None , locals = None , fromlist = None , level = None ) :
"""Callback when an import statement is executed by the Python interpreter .
Argument names have to exactly match those of _ _ import _ _ . Otherwise calls
to _ _ import _ _ that use keyword syntax will fail : _... | _IncrementNestLevel ( )
if level is None : # A level of 0 means absolute import , positive values means relative
# imports , and - 1 means to try both an absolute and relative import .
# Since imports were disambiguated in Python 3 , - 1 is not a valid value .
# The default values are 0 and - 1 for Python 3 and 3 respe... |
def plot_soma ( ax , soma , plane = 'xy' , soma_outline = True , linewidth = _LINEWIDTH , color = None , alpha = _ALPHA ) :
'''Generates a 2d figure of the soma .
Args :
ax ( matplotlib axes ) : on what to plot
soma ( neurom . core . Soma ) : plotted soma
plane ( str ) : Any pair of ' xyz '
diameter _ sca... | plane0 , plane1 = _plane2col ( plane )
color = _get_color ( color , tree_type = NeuriteType . soma )
if isinstance ( soma , SomaCylinders ) :
plane0 , plane1 = _plane2col ( plane )
for start , end in zip ( soma . points , soma . points [ 1 : ] ) :
common . project_cylinder_onto_2d ( ax , ( plane0 , plan... |
def _save_pys ( self , filepath ) :
"""Saves file as pys file and returns True if save success
Parameters
filepath : String
\t Target file path for xls file""" | try :
with Bz2AOpen ( filepath , "wb" , main_window = self . main_window ) as outfile :
interface = Pys ( self . grid . code_array , outfile )
interface . from_code_array ( )
except ( IOError , ValueError ) , err :
try :
post_command_event ( self . main_window , self . StatusBarMsg , tex... |
def convert_to_id ( s , id_set ) :
"""Some parts of . wxs need an Id attribute ( for example : The File and
Directory directives . The charset is limited to A - Z , a - z , digits ,
underscores , periods . Each Id must begin with a letter or with a
underscore . Google for " CNDL0015 " for information about th... | charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'
if s [ 0 ] in '0123456789.' :
s += '_' + s
id = [ c for c in s if c in charset ]
# did we already generate an id for this file ?
try :
return id_set [ id ] [ s ]
except KeyError : # no we did not , so initialize with the id
if id no... |
def stream2real ( binary_stream , conv , endianness = "@" ) :
"""Converts a binary stream into a sequence of real numbers
@ param binary _ stream : a binary string representing a sequence of numbers
@ param conv : conv structure containing conversion specs
@ param endianness : optionally specify bytes endiann... | size = len ( binary_stream ) // ( conv [ "bits" ] // 8 )
fmt = endianness + str ( size ) + conv [ "fmt" ]
data = struct . unpack ( fmt , binary_stream )
data = [ fix2real ( d , conv ) for d in data ]
return data |
def extend_src_text ( self , content , context , text_list , category ) :
"""Extend the source text list with the gathered text data .""" | prefix = self . prefix + '-' if self . prefix else ''
for comment , line , encoding in text_list :
content . append ( filters . SourceText ( textwrap . dedent ( comment ) , "%s (%d)" % ( context , line ) , encoding , prefix + category ) ) |
def set_type ( self ) :
"""Set the node type""" | if self . device_info [ 'type' ] == 'Router' :
self . node [ 'type' ] = self . device_info [ 'model' ] . upper ( )
else :
self . node [ 'type' ] = self . device_info [ 'type' ] |
def categorical_partition_data ( data ) :
"""Convenience method for creating weights from categorical data .
Args :
data ( list - like ) : The data from which to construct the estimate .
Returns :
A new partition object : :
" partition " : ( list ) The categorical values present in the data
" weights " ... | # Make dropna explicit ( even though it defaults to true )
series = pd . Series ( data )
value_counts = series . value_counts ( dropna = True )
# Compute weights using denominator only of nonnull values
null_indexes = series . isnull ( )
nonnull_count = ( null_indexes == False ) . sum ( )
weights = value_counts . value... |
def group_by_ngram ( self , labels ) :
"""Groups result rows by n - gram and label , providing a single summary
field giving the range of occurrences across each work ' s
witnesses . Results are sorted by n - gram then by label ( in the
order given in ` labels ` ) .
: param labels : labels to order on
: t... | if self . _matches . empty : # Ensure that the right columns are used , even though the
# results are empty .
self . _matches = pd . DataFrame ( { } , columns = [ constants . NGRAM_FIELDNAME , constants . SIZE_FIELDNAME , constants . LABEL_FIELDNAME , constants . WORK_COUNTS_FIELDNAME ] )
return
label_order_col... |
def add_details ( file_name , title , artist , album , lyrics = "" ) :
'''Adds the details to song''' | tags = EasyMP3 ( file_name )
tags [ "title" ] = title
tags [ "artist" ] = artist
tags [ "album" ] = album
tags . save ( )
tags = ID3 ( file_name )
uslt_output = USLT ( encoding = 3 , lang = u'eng' , desc = u'desc' , text = lyrics )
tags [ "USLT::'eng'" ] = uslt_output
tags . save ( file_name )
log . log ( "> Adding pro... |
def qmax_boiling ( rhol = None , rhog = None , sigma = None , Hvap = None , D = None , P = None , Pc = None , Method = None , AvailableMethods = False ) :
r'''This function handles the calculation of nucleate boiling critical
heat flux and chooses the best method for performing the calculation .
Preferred metho... | def list_methods ( ) :
methods = [ ]
if all ( ( sigma , Hvap , rhol , rhog , D ) ) :
methods . append ( 'Serth-HEDH' )
if all ( ( sigma , Hvap , rhol , rhog ) ) :
methods . append ( 'Zuber' )
if all ( ( P , Pc ) ) :
methods . append ( 'HEDH-Montinsky' )
return methods
if Avai... |
def step ( self , count = 1 ) :
"""Step the engine forward by one ( or more ) step .""" | return self . _client . send ( step = sc_pb . RequestStep ( count = count ) ) |
def do_evaluate ( parser , token ) :
'''Calls an arbitrary method on an object .''' | code = token . contents
firstspace = code . find ( ' ' )
if firstspace >= 0 :
code = code [ firstspace + 1 : ]
return Evaluator ( code ) |
def get_polypeptide_within ( self , chain_id , resnum , angstroms , only_protein = True , use_ca = False , custom_coord = None , return_resnums = False ) :
"""Get a Polypeptide object of the amino acids within X angstroms of the specified chain + residue number .
Args :
resnum ( int ) : Residue number of the st... | # XTODO : documentation , unit test
if self . structure :
parsed = self . structure
else :
parsed = self . parse_structure ( )
residue_list = ssbio . protein . structure . properties . residues . within ( resnum = resnum , chain_id = chain_id , model = parsed . first_model , angstroms = angstroms , use_ca = use... |
def _build_row ( self , row , parent , align , border ) :
"""Given a row of text , build table cells .""" | tr = etree . SubElement ( parent , 'tr' )
tag = 'td'
if parent . tag == 'thead' :
tag = 'th'
cells = self . _split_row ( row , border )
# We use align here rather than cells to ensure every row
# contains the same number of columns .
for i , a in enumerate ( align ) :
c = etree . SubElement ( tr , tag )
try... |
def _formatIds ( self , element , element_type ) :
"""Formats a set of identifiers for query""" | elementClause = None
if isinstance ( element , collections . Iterable ) :
elements = [ ]
for _id in element :
elements . append ( '?{} = <{}> ' . format ( element_type , _id ) )
elementClause = "({})" . format ( " || " . join ( elements ) )
return elementClause |
def summaries ( self , sc , limit = None ) :
"""Summary of the files contained in the current dataset
Every item in the summary is a dict containing a key name and the corresponding size of
the key item in bytes , e . g . : :
{ ' key ' : ' full / path / to / my / key ' , ' size ' : 200}
: param limit : Max ... | clauses = copy ( self . clauses )
schema = self . schema
if self . prefix :
schema = [ 'prefix' ] + schema
# Add a clause for the prefix that always returns True , in case
# the output is not filtered at all ( so that we do a scan / filter
# on the prefix directory )
clauses [ 'prefix' ] = lambda x ... |
def find_lexer_class ( name ) :
"""Lookup a lexer class by name .
Return None if not found .""" | if name in _lexer_cache :
return _lexer_cache [ name ]
# lookup builtin lexers
for module_name , lname , aliases , _ , _ in itervalues ( LEXERS ) :
if name == lname :
_load_lexers ( module_name )
return _lexer_cache [ name ]
# continue with lexers from setuptools entrypoints
for cls in find_plug... |
def GetProperties ( cls , path_spec ) :
"""Retrieves a dictionary containing the path specification properties .
Args :
path _ spec ( PathSpec ) : path specification .
Returns :
dict [ str , str ] : path specification properties .
Raises :
dict : path specification properties .""" | properties = { }
for property_name in cls . PROPERTY_NAMES : # Note that we do not want to set the properties when not used .
if hasattr ( path_spec , property_name ) :
properties [ property_name ] = getattr ( path_spec , property_name )
return properties |
def _get_indexes_by_path ( self , field ) :
"""Returns a list of indexes by field path .
: param field : Field structure as following :
* . subfield _ 2 would apply the function to the every subfield _ 2 of the elements
1 . subfield _ 2 would apply the function to the subfield _ 2 of the element 1
* would a... | try :
field , next_field = field . split ( '.' , 1 )
except ValueError :
next_field = ''
if field == '*' :
index_list = [ ]
for item in self :
index_list . append ( self . index ( item ) )
if index_list :
return index_list , next_field
return [ ] , None
elif field . isnumeric ( )... |
def readValuesPyBigWig ( self , reference , start , end ) :
"""Use pyBigWig package to read a BigWig file for the
given range and return a protocol object .
pyBigWig returns an array of values that fill the query range .
Not sure if it is possible to get the step and span .
This method trims NaN values from... | if not self . checkReference ( reference ) :
raise exceptions . ReferenceNameNotFoundException ( reference )
if start < 0 :
start = 0
bw = pyBigWig . open ( self . _sourceFile )
referenceLen = bw . chroms ( reference )
if referenceLen is None :
raise exceptions . ReferenceNameNotFoundException ( reference )... |
def counter ( self , key , ** dims ) :
"""Adds counter with dimensions to the registry""" | return super ( RegexRegistry , self ) . counter ( self . _get_key ( key ) , ** dims ) |
def _get_observation ( self ) :
"""Returns an OrderedDict containing observations [ ( name _ string , np . array ) , . . . ] .
Important keys :
robot - state : contains robot - centric information .""" | di = super ( ) . _get_observation ( )
# proprioceptive features
di [ "joint_pos" ] = np . array ( [ self . sim . data . qpos [ x ] for x in self . _ref_joint_pos_indexes ] )
di [ "joint_vel" ] = np . array ( [ self . sim . data . qvel [ x ] for x in self . _ref_joint_vel_indexes ] )
robot_states = [ np . sin ( di [ "jo... |
def get_average_length_of_string ( strings ) :
"""Computes average length of words
: param strings : list of words
: return : Average length of word on list""" | if not strings :
return 0
return sum ( len ( word ) for word in strings ) / len ( strings ) |
def focusin ( self , event ) :
"""Change style on focus in events .""" | self . old_value = self . get ( )
bc = self . style . lookup ( "TEntry" , "bordercolor" , ( "focus" , ) )
dc = self . style . lookup ( "TEntry" , "darkcolor" , ( "focus" , ) )
lc = self . style . lookup ( "TEntry" , "lightcolor" , ( "focus" , ) )
self . style . configure ( "%s.spinbox.TFrame" % self . frame , bordercol... |
def fetch_load_restriction ( self , ) :
"""Fetch whether loading is restricted
: returns : True , if loading is restricted
: rtype : : class : ` bool `
: raises : None""" | inter = self . get_refobjinter ( )
restricted = self . status ( ) != self . UNLOADED
return restricted or inter . fetch_action_restriction ( self , 'load' ) |
def set_inteface_up ( ifindex , auth , url , devid = None , devip = None ) :
"""function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to " undo shut " the specified interface on the target device .
: param devid : int or str value of the target device
: param devip : ipv... | if devip is not None :
devid = get_dev_details ( devip , auth , url ) [ 'id' ]
set_int_up_url = "/imcrs/plat/res/device/" + str ( devid ) + "/interface/" + str ( ifindex ) + "/up"
f_url = url + set_int_up_url
try :
response = requests . put ( f_url , auth = auth , headers = HEADERS )
if response . status_co... |
def list_api_service ( self , ** kwargs ) : # noqa : E501
"""list _ api _ service # noqa : E501
list or watch objects of kind APIService # noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . list _ a... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . list_api_service_with_http_info ( ** kwargs )
# noqa : E501
else :
( data ) = self . list_api_service_with_http_info ( ** kwargs )
# noqa : E501
return data |
def get_dev_examples ( self , data_dir ) :
"""See base class .""" | return self . _create_examples ( self . _read_tsv ( os . path . join ( data_dir , "dev_matched.tsv" ) ) , "dev_matched" ) |
def optimally_align_text ( x , y , texts , expand = ( 1. , 1. ) , add_bboxes = [ ] , renderer = None , ax = None , direction = 'xy' ) :
"""For all text objects find alignment that causes the least overlap with
points and other texts and apply it""" | if ax is None :
ax = plt . gca ( )
if renderer is None :
r = get_renderer ( ax . get_figure ( ) )
else :
r = renderer
xmin , xmax = sorted ( ax . get_xlim ( ) )
ymin , ymax = sorted ( ax . get_ylim ( ) )
bboxes = get_bboxes ( texts , r , expand , ax = ax )
if 'x' not in direction :
ha = [ '' ]
else :
... |
def process_read_batch ( self , batch ) :
"""Process a single , partitioned read .
: type batch : mapping
: param batch :
one of the mappings returned from an earlier call to
: meth : ` generate _ read _ batches ` .
: rtype : : class : ` ~ google . cloud . spanner _ v1 . streamed . StreamedResultSet `
:... | kwargs = copy . deepcopy ( batch [ "read" ] )
keyset_dict = kwargs . pop ( "keyset" )
kwargs [ "keyset" ] = KeySet . _from_dict ( keyset_dict )
return self . _get_snapshot ( ) . read ( partition = batch [ "partition" ] , ** kwargs ) |
def get_property ( self , name ) :
"""Return the value of a resource property .
If the resource property is not cached in this object yet , the full set
of resource properties is retrieved and cached in this object , and the
resource property is again attempted to be returned .
Authorization requirements : ... | try :
return self . _properties [ name ]
except KeyError :
if self . _full_properties :
raise
self . pull_full_properties ( )
return self . _properties [ name ] |
def container_difference ( container = None , container_subtract = None , image_package = None , image_package_subtract = None , comparison = None ) :
'''container _ difference will return a data structure to render an html
tree ( graph ) of the differences between two images or packages . The second
container ... | if comparison == None :
comparison = compare_containers ( container1 = container , container2 = container_subtract , image_package1 = image_package , image_package2 = image_package_subtract , by = [ 'files.txt' , 'folders.txt' ] )
files = comparison [ "files.txt" ] [ 'unique1' ]
folders = comparison [ 'folders.txt'... |
def enable_from_env ( state = None ) :
"""Enable certification for this thread based on the environment variable ` CERTIFIABLE _ STATE ` .
: param bool state :
Default status to use .
: return :
The new state .
: rtype :
bool""" | try :
x = os . environ . get ( ENVVAR , state , )
value = bool ( int ( x ) )
except Exception : # pylint : disable = broad - except
value = bool ( state )
return enable ( value ) |
def save ( params , filename , source ) :
'''Write a sequence of samples as a WAV file
Currently a 16 bit mono file''' | writer = wave . open ( filename , 'wb' ) ;
# Set the WAV file parameters , currently default values
writer . setnchannels ( 1 )
writer . setsampwidth ( 2 )
writer . setframerate ( params . sample_rate )
data_out = array . array ( 'h' )
for x in source :
data_out . append ( int ( x * 32766 ) )
writer . writeframes (... |
def conv_lstm ( x , kernel_size , filters , padding = "SAME" , dilation_rate = ( 1 , 1 ) , name = None , reuse = None ) :
"""Convolutional LSTM in 1 dimension .""" | with tf . variable_scope ( name , default_name = "conv_lstm" , values = [ x ] , reuse = reuse ) :
gates = conv ( x , 4 * filters , kernel_size , padding = padding , dilation_rate = dilation_rate )
g = tf . split ( layer_norm ( gates , 4 * filters ) , 4 , axis = 3 )
new_cell = tf . sigmoid ( g [ 0 ] ) * x + ... |
def import_file ( self , file_obj , folder ) :
"""Create a File or an Image into the given folder""" | try :
iext = os . path . splitext ( file_obj . name ) [ 1 ] . lower ( )
except : # noqa
iext = ''
if iext in [ '.jpg' , '.jpeg' , '.png' , '.gif' ] :
obj , created = Image . objects . get_or_create ( original_filename = file_obj . name , file = file_obj , folder = folder , is_public = FILER_IS_PUBLIC_DEFAUL... |
def _fields_to_object ( descriptor , fields ) :
'Helper to convert a descriptor and a set of fields to a Protobuf instance' | # pylint : disable = protected - access
obj = descriptor . _concrete_class ( )
for name , value in fields :
if isinstance ( value , tuple ) :
subtype = descriptor . fields_by_name [ name ] . message_type
value = _fields_to_object ( subtype , value )
_assign_to_field ( obj , name , value )
return... |
def reindex ( self , kdims = [ ] , force = False ) :
"""Reorders key dimensions on DynamicMap
Create a new object with a reordered set of key dimensions .
Dropping dimensions is not allowed on a DynamicMap .
Args :
kdims : List of dimensions to reindex the mapping with
force : Not applicable to a DynamicM... | if not isinstance ( kdims , list ) :
kdims = [ kdims ]
kdims = [ self . get_dimension ( kd , strict = True ) for kd in kdims ]
dropped = [ kd for kd in self . kdims if kd not in kdims ]
if dropped :
raise ValueError ( "DynamicMap does not allow dropping dimensions, " "reindex may only be used to reorder dimensi... |
def ensure_header ( self , header : BlockHeader = None ) -> BlockHeader :
"""Return ` ` header ` ` if it is not ` ` None ` ` , otherwise return the header
of the canonical head .""" | if header is None :
head = self . get_canonical_head ( )
return self . create_header_from_parent ( head )
else :
return header |
def update_context ( self , context , app = None ) :
"""Replace the component ' s context with a new one .
Args :
context ( dict ) : The new context to set this component ' s context to .
Keyword Args :
app ( flask . Flask , optional ) : The app to update this context for . If
not provided , the result of... | if ( app is None and self . _context is _CONTEXT_MISSING and not in_app_context ( ) ) :
raise RuntimeError ( "Attempted to update component context without" " a bound app context or eager app set! Please" " pass the related app you want to update the" " context for!" )
if self . _context is not _CONTEXT_MISSING :
... |
def dissolve ( infile , outfile , field , layername = None ) :
"""dissolve the polygons of a vector file by an attribute field
Parameters
infile : str
the input vector file
outfile : str
the output shapefile
field : str
the field name to merge the polygons by
layername : str
the name of the output... | with Vector ( infile ) as vec :
srs = vec . srs
feat = vec . layer [ 0 ]
d = feat . GetFieldDefnRef ( field )
width = d . width
type = d . type
feat = None
layername = layername if layername is not None else os . path . splitext ( os . path . basename ( infile ) ) [ 0 ]
# the following can be us... |
def _parse_text ( self , element_name , namespace = '' ) :
"""Returns the text , as a string , of the specified element in the specified
namespace of the RSS feed .
Takes element _ name and namespace as strings .""" | try :
text = self . _channel . find ( './/' + namespace + element_name ) . text
except AttributeError :
raise Exception ( 'Element, {0} not found in RSS feed' . format ( element_name ) )
return text |
def pretty_req ( req ) :
"""return a copy of a pip requirement that is a bit more readable ,
at the expense of removing some of its data""" | from copy import copy
req = copy ( req )
req . link = None
req . satisfied_by = None
return req |
def main ( argv = None ) :
"""This is the main thread of execution
: param argv : list of command line arguments""" | # Exit code
exit_code = 0
# First , we change main ( ) to take an optional ' argv '
# argument , which allows us to call it from the interactive
# Python prompt
if argv is None :
argv = sys . argv
try : # Bootstrap
init ( argv )
# Perform the actual backup job
make_backup_files ( )
except Exception as e... |
def _create_model ( self , X , Y ) :
"""Creates the model given some input data X and Y .""" | from sklearn . ensemble import RandomForestRegressor
self . X = X
self . Y = Y
self . model = RandomForestRegressor ( bootstrap = self . bootstrap , criterion = self . criterion , max_depth = self . max_depth , max_features = self . max_features , max_leaf_nodes = self . max_leaf_nodes , min_samples_leaf = self . min_s... |
def award_group_award_id ( tag ) :
"""Find the award group award id , one for each
item found in the get _ funding _ group section""" | award_group_award_id = [ ]
award_id_tags = extract_nodes ( tag , "award-id" )
for t in award_id_tags :
award_group_award_id . append ( t . text )
return award_group_award_id |
def get_instance ( self , payload ) :
"""Build an instance of AssetVersionInstance
: param dict payload : Payload response from the API
: returns : twilio . rest . serverless . v1 . service . asset . asset _ version . AssetVersionInstance
: rtype : twilio . rest . serverless . v1 . service . asset . asset _ v... | return AssetVersionInstance ( self . _version , payload , service_sid = self . _solution [ 'service_sid' ] , asset_sid = self . _solution [ 'asset_sid' ] , ) |
def shuffle_sparse_coo_matrix ( sparse_matrix , dropout_rate = 0.0 , min_dropout_rate = None , max_dropout_rate = None ) :
"""Shuffle sparse matrix encoded as a SciPy coo matrix .
Args :
sparse _ matrix : a SciPy coo sparse matrix .
dropout _ rate : if dropout _ rate > 0 then non - zero elements of the input ... | if ( dropout_rate < 0.0 ) or ( dropout_rate >= 1.0 ) :
raise ValueError ( "Dropout rate should be in [0, 1) but is %f" % dropout_rate )
( num_rows , num_cols ) = sparse_matrix . shape
shuffled_rows = shuffle ( np . arange ( num_rows ) )
shuffled_cols = shuffle ( np . arange ( num_cols ) )
if dropout_rate > 0.0 :
... |
def posix_rename ( self , oldpath , newpath ) :
"""Rename a file or folder from ` ` oldpath ` ` to ` ` newpath ` ` , following
posix conventions .
: param str oldpath : existing name of the file or folder
: param str newpath : new name for the file or folder , will be
overwritten if it already exists
: ra... | oldpath = self . _adjust_cwd ( oldpath )
newpath = self . _adjust_cwd ( newpath )
self . _log ( DEBUG , "posix_rename({!r}, {!r})" . format ( oldpath , newpath ) )
self . _request ( CMD_EXTENDED , "posix-rename@openssh.com" , oldpath , newpath ) |
def generate_df ( js_dict , naming , value = "value" ) :
"""Decode JSON - stat dict into pandas . DataFrame object . Helper method that should be called inside from _ json _ stat ( ) .
Args :
js _ dict ( OrderedDict ) : OrderedDict with data in JSON - stat format , previously deserialized into a python object b... | values = [ ]
dimensions , dim_names = get_dimensions ( js_dict , naming )
values = get_values ( js_dict , value = value )
output = pd . DataFrame ( [ category + [ values [ i ] ] for i , category in enumerate ( get_df_row ( dimensions , naming ) ) ] )
output . columns = dim_names + [ value ]
output . index = range ( 0 ,... |
def attributesToBinary ( cls , attributes ) :
""": rtype : ( str | None , int )
: return : the binary data and the number of chunks it was composed from""" | chunks = [ ( int ( k ) , v ) for k , v in iteritems ( attributes ) if cls . _isValidChunkName ( k ) ]
chunks . sort ( )
numChunks = int ( attributes [ u'numChunks' ] )
if numChunks :
serializedJob = b'' . join ( v for k , v in chunks )
compressed = base64 . b64decode ( serializedJob )
if compressed [ 0 ] ==... |
def check_sync ( self ) :
"""Check if sync is required based on last sync date .""" | # If refresh interval is not specified , we should refresh every time .
expiration = utcnow ( )
refresh_td = current_app . config . get ( 'GITHUB_REFRESH_TIMEDELTA' )
if refresh_td :
expiration -= refresh_td
last_sync = parse_timestamp ( self . account . extra_data [ 'last_sync' ] )
return last_sync < expiration |
def init_recv ( self ) :
"""Parses the IKE _ INIT response packet received from Responder .
Assigns the correct values of rSPI and Nr
Calculates Diffie - Hellman exchange and assigns all keys to self .""" | assert len ( self . packets ) == 2
packet = self . packets [ - 1 ]
for p in packet . payloads :
if p . _type == payloads . Type . Nr :
self . Nr = p . _data
logger . debug ( u"Responder nonce {}" . format ( binascii . hexlify ( self . Nr ) ) )
elif p . _type == payloads . Type . KE :
int... |
def keywords ( text , cloud = None , batch = False , api_key = None , version = 2 , batch_size = None , ** kwargs ) :
"""Given input text , returns series of keywords and associated scores
Example usage :
. . code - block : : python
> > > import indicoio
> > > import numpy as np
> > > text = ' Monday : De... | if kwargs . get ( "language" , "english" ) != "english" :
version = 1
url_params = { "batch" : batch , "api_key" : api_key , "version" : version }
return api_handler ( text , cloud = cloud , api = "keywords" , url_params = url_params , batch_size = batch_size , ** kwargs ) |
def write ( series , output , scale = None ) :
"""Write a ` TimeSeries ` to a WAV file
Parameters
series : ` TimeSeries `
the series to write
output : ` file ` , ` str `
the file object or filename to write to
scale : ` float ` , optional
the factor to apply to scale the data to ( - 1.0 , 1.0 ) ,
pa... | fsamp = int ( series . sample_rate . decompose ( ) . value )
if scale is None :
scale = 1 / numpy . abs ( series . value ) . max ( )
data = ( series . value * scale ) . astype ( 'float32' )
return wavfile . write ( output , fsamp , data ) |
def references ( self ) :
""": return : generator of referencing table names and their referencing columns""" | return self . connection . query ( """
SELECT concat('`', table_schema, '`.`', table_name, '`') as referencing_table, column_name
FROM information_schema.key_column_usage
WHERE referenced_table_name="{tab}" and referenced_table_schema="{db}"
""" . format ( tab = self . table_name , db = ... |
def _cursor_position_changed ( self ) :
"""Updates the tip based on user cursor movement .""" | cursor = self . _text_edit . textCursor ( )
position = cursor . position ( )
document = self . _text_edit . document ( )
char = to_text_string ( document . characterAt ( position - 1 ) )
if position <= self . _start_position :
self . hide ( )
elif char == ')' :
pos , _ = self . _find_parenthesis ( position - 1 ... |
def ResetHandler ( self , name ) :
'''Method which assigns handler to the tag encountered before the current , or else
sets it to None
: param name : name of the latest tag
: return :''' | if name in self . tags :
if len ( self . tags ) > 1 :
key = len ( self . tags ) - 2
self . handler = None
while key >= 0 :
if self . tags [ key ] in self . structure :
self . handler = self . structure [ self . tags [ key ] ]
break
key ... |
def _context_menu_make ( self , pos ) :
"""Reimplement the IPython context menu""" | menu = super ( ShellWidget , self ) . _context_menu_make ( pos )
return self . ipyclient . add_actions_to_context_menu ( menu ) |
def addTextErr ( self , text ) :
"""add red text""" | self . _currentColor = self . _red
self . addText ( text ) |
def LMTD ( Thi , Tho , Tci , Tco , counterflow = True ) :
r'''Returns the log - mean temperature difference of an ideal counterflow
or co - current heat exchanger .
. . math : :
\ Delta T _ { LMTD } = \ frac { \ Delta T _ 1 - \ Delta T _ 2 } { \ ln ( \ Delta T _ 1 / \ Delta T _ 2 ) }
\ text { For countercur... | if counterflow :
dTF1 = Thi - Tco
dTF2 = Tho - Tci
else :
dTF1 = Thi - Tci
dTF2 = Tho - Tco
return ( dTF2 - dTF1 ) / log ( dTF2 / dTF1 ) |
def add_factors ( self , * factors ) :
"""Associate a factor to the graph .
See factors class for the order of potential values
Parameters
* factor : pgmpy . factors . factors object
A factor object on any subset of the variables of the model which
is to be associated with the model .
Returns
None
E... | for factor in factors :
factor_scope = set ( factor . scope ( ) )
nodes = [ set ( node ) for node in self . nodes ( ) ]
if factor_scope not in nodes :
raise ValueError ( 'Factors defined on clusters of variable not' 'present in model' )
self . factors . append ( factor ) |
def send_data_message ( self , api_key = None , condition = None , collapse_key = None , delay_while_idle = False , time_to_live = None , restricted_package_name = None , low_priority = False , dry_run = False , data_message = None , content_available = None , timeout = 5 , json_encoder = None ) :
"""Send data mess... | if self :
from . fcm import fcm_send_bulk_data_messages
registration_ids = list ( self . filter ( active = True ) . values_list ( 'registration_id' , flat = True ) )
if len ( registration_ids ) == 0 :
return [ { 'failure' : len ( self ) , 'success' : 0 } ]
result = fcm_send_bulk_data_messages ( ... |
def di_power ( self , i , power = 1 ) :
r'''Method to calculate a power of a particle class / bin in a generic
way so as to support when there are as many ` ds ` as ` fractions ` ,
or one more diameter spec than ` fractions ` .
When each bin has a lower and upper bound , the formula is as follows
[1 ] _ .
... | if self . size_classes :
rt = power + 1
return ( ( self . ds [ i + 1 ] ** rt - self . ds [ i ] ** rt ) / ( ( self . ds [ i + 1 ] - self . ds [ i ] ) * rt ) )
else :
return self . ds [ i ] ** power |
def do_storecheck ( self , subcmd , opts ) :
"""$ { cmd _ name } : checks the store for files that may not be in the maildirs .""" | from os . path import basename
from os . path import dirname
from os . path import exists as existspath
from os . path import islink
from os . path import join as joinpath
maildir = self . maildir
cur = joinpath ( maildir , "cur" )
new = joinpath ( maildir , "new" )
store = joinpath ( maildir , "store" )
found_list = [... |
def get ( self ) :
"""Returns the underlying value or raise the underlying exception""" | val = self . pik . unpickle ( )
if self . tb_str :
etype = val . __class__
msg = '\n%s%s: %s' % ( self . tb_str , etype . __name__ , val )
if issubclass ( etype , KeyError ) :
raise RuntimeError ( msg )
# nicer message
else :
raise etype ( msg )
return val |
def colorate ( sequence , colormap = "" , start = 0 , length = None ) :
"""like enumerate , but with colors""" | n = start
colors = color_space ( colormap , sequence , start = 0.1 , stop = 0.9 , length = length )
for elem in sequence :
yield n , colors [ n - start ] , elem
n += 1 |
def put_cancel ( self ) :
"""Sends a cancel request to the server .
Switches connection to IN _ CANCEL state .""" | logger . info ( 'Sending CANCEL' )
self . _writer . begin_packet ( tds_base . PacketType . CANCEL )
self . _writer . flush ( )
self . in_cancel = 1 |
def substitute_partner ( self , state , partners_recp , recp , alloc_id ) :
'''Establish the partnership to recp and , when it is successfull
remove partner with recipient partners _ recp .
Use with caution : The partner which we are removing is not notified
in any way , so he still keeps link in his descript... | partner = state . partners . find ( recipient . IRecipient ( partners_recp ) )
if not partner :
msg = 'subsitute_partner() did not find the partner %r' % partners_recp
self . error ( msg )
return fiber . fail ( partners . FindPartnerError ( msg ) )
return self . establish_partnership ( recp , partner . allo... |
def __hi2lo_multiscale_indexes ( self , mask , orig_shape ) : # , zoom ) :
"""Function computes multiscale indexes of ndarray .
mask : Says where is original resolution ( 0 ) and where is small
resolution ( 1 ) . Mask is in small resolution .
orig _ shape : Original shape of input data .
zoom : Usually numb... | mask_orig = zoom_to_shape ( mask , orig_shape , dtype = np . int8 )
inds_small = np . arange ( mask . size ) . reshape ( mask . shape )
inds_small_in_orig = zoom_to_shape ( inds_small , orig_shape , dtype = np . int8 )
inds_orig = np . arange ( np . prod ( orig_shape ) ) . reshape ( orig_shape )
# inds _ orig = inds _ ... |
def port_has_listener ( address , port ) :
"""Returns True if the address : port is open and being listened to ,
else False .
@ param address : an IP address or hostname
@ param port : integer port
Note calls ' zc ' via a subprocess shell""" | cmd = [ 'nc' , '-z' , address , str ( port ) ]
result = subprocess . call ( cmd )
return not ( bool ( result ) ) |
def diff ( xi , yi , order = 1 ) -> np . ndarray :
"""Take the numerical derivative of a 1D array .
Output is mapped onto the original coordinates using linear interpolation .
Expects monotonic xi values .
Parameters
xi : 1D array - like
Coordinates .
yi : 1D array - like
Values .
order : positive i... | yi = np . array ( yi ) . copy ( )
flip = False
if xi [ - 1 ] < xi [ 0 ] :
xi = np . flipud ( xi . copy ( ) )
yi = np . flipud ( yi )
flip = True
midpoints = ( xi [ 1 : ] + xi [ : - 1 ] ) / 2
for _ in range ( order ) :
d = np . diff ( yi )
d /= np . diff ( xi )
yi = np . interp ( xi , midpoints ,... |
def default_ubuntu_tr ( mod ) :
"""Default translation function for Ubuntu based systems""" | pkg = 'python-%s' % mod . lower ( )
py2pkg = pkg
py3pkg = 'python3-%s' % mod . lower ( )
return ( pkg , py2pkg , py3pkg ) |
def add_users_to_user_group ( self , id , ** kwargs ) : # noqa : E501
"""Add multiple users to a specific user group # noqa : E501
# noqa : E501
This method makes a synchronous HTTP request by default . To make an
asynchronous HTTP request , please pass async _ req = True
> > > thread = api . add _ users _ ... | kwargs [ '_return_http_data_only' ] = True
if kwargs . get ( 'async_req' ) :
return self . add_users_to_user_group_with_http_info ( id , ** kwargs )
# noqa : E501
else :
( data ) = self . add_users_to_user_group_with_http_info ( id , ** kwargs )
# noqa : E501
return data |
def add_health_monitor ( self , loadbalancer , type , delay = 10 , timeout = 10 , attemptsBeforeDeactivation = 3 , path = "/" , statusRegex = None , bodyRegex = None , hostHeader = None ) :
"""Adds a health monitor to the load balancer . If a monitor already
exists , it is updated with the supplied settings .""" | uri = "/loadbalancers/%s/healthmonitor" % utils . get_id ( loadbalancer )
req_body = { "healthMonitor" : { "type" : type , "delay" : delay , "timeout" : timeout , "attemptsBeforeDeactivation" : attemptsBeforeDeactivation , } }
uptype = type . upper ( )
if uptype . startswith ( "HTTP" ) :
lb = self . _get_lb ( loadb... |
def event ( self , name ) :
"""Returns the : class : ` Event ` at ` ` name ` ` .
If no event is registered for ` ` name ` ` creates a new : class : ` Event `
object and returns it .""" | events = self . events ( )
if name not in events :
events [ name ] = Event ( name , self , 0 )
return events [ name ] |
def lfc ( pressure , temperature , dewpt , parcel_temperature_profile = None , dewpt_start = None ) :
r"""Calculate the level of free convection ( LFC ) .
This works by finding the first intersection of the ideal parcel path and
the measured parcel temperature .
Parameters
pressure : ` pint . Quantity `
T... | # Default to surface parcel if no profile or starting pressure level is given
if parcel_temperature_profile is None :
new_stuff = parcel_profile_with_lcl ( pressure , temperature , dewpt )
pressure , temperature , _ , parcel_temperature_profile = new_stuff
temperature = temperature . to ( 'degC' )
parce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.