signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def inject_func_as_property ( self , func , method_name = None , class_ = None ) :
"""WARNING :
properties are more safely injected using metaclasses
References :
http : / / stackoverflow . com / questions / 13850114 / dynamically - adding - methods - with - or - without - metaclass - in - python""" | if method_name is None :
method_name = get_funcname ( func )
# new _ method = func . _ _ get _ _ ( self , self . _ _ class _ _ )
new_property = property ( func )
setattr ( self . __class__ , method_name , new_property ) |
def _ParseMRUListExEntryValue ( self , parser_mediator , registry_key , entry_index , entry_number , codepage = 'cp1252' , ** kwargs ) :
"""Parses the MRUListEx entry value .
Args :
parser _ mediator ( ParserMediator ) : mediates interactions between parsers
and other components , such as storage and dfvfs . ... | value_string = ''
value = registry_key . GetValueByName ( '{0:d}' . format ( entry_number ) )
if value is None :
parser_mediator . ProduceExtractionWarning ( 'missing MRUListEx value: {0:d} in key: {1:s}.' . format ( entry_number , registry_key . path ) )
elif not value . DataIsBinaryData ( ) :
logger . debug (... |
def context ( self , key , method ) :
"""A helper method to attach a value within context .
: param key : the key attached to the context .
: param method : the constructor function .
: return : the value attached to the context .""" | ctx = stack . top
if ctx is not None :
if not hasattr ( ctx , key ) :
setattr ( ctx , key , method ( ) )
return getattr ( ctx , key ) |
def set_kwargs ( self , code ) :
"""Sets widget from kwargs string
Parameters
code : String
\t Code representation of kwargs value""" | kwargs = { }
kwarglist = list ( parse_dict_strings ( code [ 1 : - 1 ] ) )
for kwarg , val in zip ( kwarglist [ : : 2 ] , kwarglist [ 1 : : 2 ] ) :
kwargs [ unquote_string ( kwarg ) ] = val
for key in kwargs :
if key == "color" :
color = code2color ( kwargs [ key ] )
self . colorselect . SetOwnFo... |
def mergeSplitsOnInterfaces ( root : LNode ) :
"""collect all split / concatenation nodes and group them by target interface""" | for ch in root . children :
if ch . children :
mergeSplitsOnInterfaces ( ch )
ctx = MergeSplitsOnInterfacesCtx ( )
for ch in root . children :
srcPorts = None
try :
if ch . name == "CONCAT" :
p = single ( ch . east , lambda x : True )
e = single ( p . outgoingEdges , ... |
def _highlight ( html ) :
"""Syntax - highlights HTML - rendered Markdown .
Plucks sections to highlight that conform the the GitHub fenced code info
string as defined at https : / / github . github . com / gfm / # info - string .
Args :
html ( str ) : The rendered HTML .
Returns :
str : The HTML with P... | formatter = pygments . formatters . HtmlFormatter ( nowrap = True )
code_expr = re . compile ( r'<pre><code class="language-(?P<lang>.+?)">(?P<code>.+?)' r'</code></pre>' , re . DOTALL )
def replacer ( match ) :
try :
lang = match . group ( 'lang' )
lang = _LANG_ALIASES . get ( lang , lang )
... |
def get_row_height ( self , row , tab ) :
"""Returns row height""" | try :
return self . row_heights [ ( row , tab ) ]
except KeyError :
return config [ "default_row_height" ] |
def create_from_fitsfile ( cls , fitsfile ) :
"""Read a fits file and use it to make a mapping""" | from fermipy . skymap import Map
index_map = Map . create_from_fits ( fitsfile )
mult_map = Map . create_from_fits ( fitsfile , hdu = 1 )
ff = fits . open ( fitsfile )
hpx = HPX . create_from_hdu ( ff [ 0 ] )
mapping_data = dict ( ipixs = index_map . counts , mult_val = mult_map . counts , npix = mult_map . counts . sh... |
def get_html ( grafs ) :
"""Renders the grafs provided in HTML by wrapping them in < p > tags .
Linebreaks are replaced with < br > tags .""" | html = [ format_html ( '<p>{}</p>' , p ) for p in grafs ]
html = [ p . replace ( "\n" , "<br>" ) for p in html ]
return format_html ( six . text_type ( '\n\n' . join ( html ) ) ) |
def createTileUrl ( self , x , y , z ) :
'''returns new tile url based on template''' | return self . tileTemplate . replace ( '{{x}}' , str ( x ) ) . replace ( '{{y}}' , str ( y ) ) . replace ( '{{z}}' , str ( z ) ) |
def is_zipfile ( filename ) :
"""Quickly see if file is a ZIP file by checking the magic number .""" | try :
fpin = open ( filename , "rb" )
endrec = _EndRecData ( fpin )
fpin . close ( )
if endrec :
return True
# file has correct magic number
except IOError :
pass
return False |
def _py3_crc16 ( value ) :
"""Calculate the CRC for the value in Python 3
: param bytes value : The value to return for the CRC Checksum
: rtype : int""" | crc = 0
for byte in value :
crc = ( ( crc << 8 ) & 0xffff ) ^ _CRC16_LOOKUP [ ( ( crc >> 8 ) ^ byte ) & 0xff ]
return crc |
def education ( self ) :
"""A list of structures describing the user ' s education history .
Each structure has attributes ` ` school ` ` , ` ` year ` ` , ` ` concentration ` ` and ` ` type ` ` .
` ` school ` ` , ` ` year ` ` reference ` ` Page ` ` instances , while ` ` concentration ` ` is a list of ` ` Page `... | educations = [ ]
for education in self . cache [ 'education' ] :
school = Page ( ** education . get ( 'school' ) )
year = Page ( ** education . get ( 'year' ) )
type = education . get ( 'type' )
if 'concentration' in education :
concentration = map ( lambda c : Page ( ** c ) , education . get ( ... |
def decrypt_ige ( cipher_text , key , iv ) :
"""Decrypts the given text in 16 - bytes blocks by using the
given key and 32 - bytes initialization vector .""" | if cryptg :
return cryptg . decrypt_ige ( cipher_text , key , iv )
if libssl . decrypt_ige :
return libssl . decrypt_ige ( cipher_text , key , iv )
iv1 = iv [ : len ( iv ) // 2 ]
iv2 = iv [ len ( iv ) // 2 : ]
aes = pyaes . AES ( key )
plain_text = [ ]
blocks_count = len ( cipher_text ) // 16
cipher_text_block ... |
def list_ ( prefix = None , bin_env = None , user = None , cwd = None , env_vars = None , ** kwargs ) :
'''Filter list of installed apps from ` ` freeze ` ` and check to see if
` ` prefix ` ` exists in the list of packages installed .
. . note : :
If the version of pip available is older than 8.0.3 , the pack... | packages = { }
if prefix is None or 'pip' . startswith ( prefix ) :
packages [ 'pip' ] = version ( bin_env )
for line in freeze ( bin_env = bin_env , user = user , cwd = cwd , env_vars = env_vars , ** kwargs ) :
if line . startswith ( '-f' ) or line . startswith ( '#' ) : # ignore - f line as it contains - - fi... |
def append ( self , data ) :
"""Appends the given data to the buffer , and triggers all connected
monitors , if any of them match the buffer content .
: type data : str
: param data : The data that is appended .""" | self . io . write ( data )
if not self . monitors :
return
# Check whether any of the monitoring regular expressions matches .
# If it does , we need to disable that monitor until the matching
# data is no longer in the buffer . We accomplish this by keeping
# track of the position of the last matching byte .
buf =... |
def reverse_transform ( self , col ) :
"""Converts data back into original format .
Args :
col ( pandas . DataFrame ) : Data to transform .
Returns :
pandas . DataFrame""" | output = pd . DataFrame ( )
output [ self . col_name ] = self . get_category ( col [ self . col_name ] )
return output |
def get_next_step ( self ) :
"""Find the proper step when user clicks the Next button .
: returns : The step to be switched to
: rtype : WizardStep instance or None""" | if is_raster_layer ( self . parent . layer ) :
new_step = self . parent . step_kw_band_selector
else :
new_step = self . parent . step_kw_layermode
return new_step |
def path_yield ( path ) :
"""Yield on all path parts .""" | for part in ( x for x in path . strip ( SEP ) . split ( SEP ) if x not in ( None , '' ) ) :
yield part |
def get_hash ( self , ireq , ireq_hashes = None ) :
"""Retrieve hashes for a specific ` ` InstallRequirement ` ` instance .
: param ireq : An ` ` InstallRequirement ` ` to retrieve hashes for
: type ireq : : class : ` ~ pip _ shims . InstallRequirement `
: return : A set of hashes .
: rtype : Set""" | # We _ ALWAYS MUST PRIORITIZE _ the inclusion of hashes from local sources
# PLEASE * DO NOT MODIFY THIS * TO CHECK WHETHER AN IREQ ALREADY HAS A HASH
# RESOLVED . The resolver will pull hashes from PyPI and only from PyPI .
# The entire purpose of this approach is to include missing hashes .
# This fixes a race condit... |
def generate_output_list ( self , source , key , val , line = '2' , hr = True , show_name = False , colorize = True ) :
"""The function for generating CLI output RDAP list results .
Args :
source ( : obj : ` str ` ) : The parent key ' network ' or ' objects '
( required ) .
key ( : obj : ` str ` ) : The eve... | output = generate_output ( line = line , short = HR_RDAP [ source ] [ key ] [ '_short' ] if hr else key , name = HR_RDAP [ source ] [ key ] [ '_name' ] if ( hr and show_name ) else None , is_parent = False if ( val is None or len ( val ) == 0 ) else True , value = 'None' if ( val is None or len ( val ) == 0 ) else None... |
def p_field_optional2_3 ( self , p ) :
"""field : name arguments directives""" | p [ 0 ] = Field ( name = p [ 1 ] , arguments = p [ 2 ] , directives = p [ 3 ] ) |
def _reset ( self ) :
"""Reset internal flags and entry lists .""" | self . entries = [ ]
self . default_entry = None
self . disallow_all = False
self . allow_all = False
self . last_checked = 0
# list of tuples ( sitemap url , line number )
self . sitemap_urls = [ ] |
def as_condition ( cls , obj ) :
"""Convert obj into : class : ` Condition `""" | if isinstance ( obj , cls ) :
return obj
else :
return cls ( cmap = obj ) |
def innerLoop ( self ) :
"""The main loop for processing jobs by the leader .""" | self . timeSinceJobsLastRescued = time . time ( )
while self . toilState . updatedJobs or self . getNumberOfJobsIssued ( ) or self . serviceManager . jobsIssuedToServiceManager :
if self . toilState . updatedJobs :
self . _processReadyJobs ( )
# deal with service - related jobs
self . _startServiceJ... |
def normalize_per_cell_weinreb16_deprecated ( X , max_fraction = 1 , mult_with_mean = False , ) -> np . ndarray :
"""Normalize each cell [ Weinreb17 ] _ .
This is a deprecated version . See ` normalize _ per _ cell ` instead .
Normalize each cell by UMI count , so that every cell has the same total
count .
... | if max_fraction < 0 or max_fraction > 1 :
raise ValueError ( 'Choose max_fraction between 0 and 1.' )
counts_per_cell = X . sum ( 1 ) . A1 if issparse ( X ) else X . sum ( 1 )
gene_subset = np . all ( X <= counts_per_cell [ : , None ] * max_fraction , axis = 0 )
if issparse ( X ) :
gene_subset = gene_subset . A... |
def _ascii_find_urls ( bytes , mimetype , extra_tokens = True ) :
"""This function finds URLs inside of ASCII bytes .""" | tokens = _tokenize ( bytes , mimetype , extra_tokens = extra_tokens )
return tokens |
def fromDatetime ( klass , dtime ) :
"""Return a new Time instance from a datetime . datetime instance .
If the datetime instance does not have an associated timezone , it is
assumed to be UTC .""" | self = klass . __new__ ( klass )
if dtime . tzinfo is not None :
self . _time = dtime . astimezone ( FixedOffset ( 0 , 0 ) ) . replace ( tzinfo = None )
else :
self . _time = dtime
self . resolution = datetime . timedelta . resolution
return self |
def request_error_header ( exception ) :
"""Generates the error header for a request using a Bearer token based on a given OAuth exception .""" | from . conf import options
header = "Bearer realm=\"%s\"" % ( options . realm , )
if hasattr ( exception , "error" ) :
header = header + ", error=\"%s\"" % ( exception . error , )
if hasattr ( exception , "reason" ) :
header = header + ", error_description=\"%s\"" % ( exception . reason , )
return header |
def set_XY ( self , X = None , Y = None ) :
"""Set the input / output data of the model
This is useful if we wish to change our existing data but maintain the same model
: param X : input observations
: type X : np . ndarray
: param Y : output observations
: type Y : np . ndarray""" | self . update_model ( False )
if Y is not None :
if self . normalizer is not None :
self . normalizer . scale_by ( Y )
self . Y_normalized = ObsAr ( self . normalizer . normalize ( Y ) )
self . Y = Y
else :
self . Y = ObsAr ( Y )
self . Y_normalized = self . Y
if X is not... |
def find_recursive_dependency ( self ) :
"""Return a list of nodes that have a recursive dependency .""" | nodes_on_path = [ ]
def helper ( nodes ) :
for node in nodes :
cycle = node in nodes_on_path
nodes_on_path . append ( node )
if cycle or helper ( self . deps . get ( node , [ ] ) ) :
return True
nodes_on_path . pop ( )
return False
helper ( self . unordered )
return n... |
def _preoptimize_model ( self ) :
"""Preoptimizes the model by estimating a Gaussian state space models
Returns
- Gaussian model latent variable object""" | gaussian_model = DynReg ( formula = self . formula , data = self . data_original )
gaussian_model . fit ( )
for i in range ( self . z_no - self . family_z_no ) :
self . latent_variables . z_list [ i ] . start = gaussian_model . latent_variables . get_z_values ( ) [ i + 1 ]
if self . model_name2 == 't' :
def tem... |
def populate_keys_tree ( self ) :
"""Reads the HOTKEYS global variable and insert all data in
the TreeStore used by the preferences window treeview .""" | for group in HOTKEYS :
parent = self . store . append ( None , [ None , group [ 'label' ] , None , None ] )
for item in group [ 'keys' ] :
if item [ 'key' ] == "show-hide" or item [ 'key' ] == "show-focus" :
accel = self . settings . keybindingsGlobal . get_string ( item [ 'key' ] )
... |
def topic ( self , channel , topic = None ) :
"""change or request the topic of a channel""" | if topic :
channel += ' :' + topic
self . send_line ( 'TOPIC %s' % channel ) |
def attrgetter_atom_split ( tokens ) :
"""Split attrgetter _ atom _ tokens into ( attr _ or _ method _ name , method _ args _ or _ none _ if _ attr ) .""" | if len ( tokens ) == 1 : # . attr
return tokens [ 0 ] , None
elif len ( tokens ) >= 2 and tokens [ 1 ] == "(" : # . method ( . . .
if len ( tokens ) == 2 : # . method ( )
return tokens [ 0 ] , ""
elif len ( tokens ) == 3 : # . method ( args )
return tokens [ 0 ] , tokens [ 2 ]
else :
... |
def tokml ( self ) :
"""Generate a KML Placemark element subtree .
Returns :
etree . Element : KML Placemark element""" | placemark = create_elem ( 'Placemark' )
if self . name :
placemark . set ( 'id' , self . name )
placemark . name = create_elem ( 'name' , text = self . name )
if self . description :
placemark . description = create_elem ( 'description' , text = self . description )
placemark . Point = create_elem ( 'Point'... |
def get_content ( self , obj ) :
"""All content for office ' s page on an election day .""" | election_day = ElectionDay . objects . get ( date = self . context [ 'election_date' ] )
return PageContent . objects . office_content ( election_day , obj ) |
def db_for_write ( self , model , ** hints ) :
"""If given some hints [ ' instance ' ] that is saved in a db , use related
fields from the same db . Otherwise if passed a class or instance to
model , return the salesforce alias if it ' s a subclass of SalesforceModel .""" | if 'instance' in hints :
db = hints [ 'instance' ] . _state . db
if db :
return db
if getattr ( model , '_salesforce_object' , False ) :
return self . sf_alias |
def get_stream ( self , stream_name : str ) -> StreamWrapper :
"""Get a : py : class : ` StreamWrapper ` with the given name .
: param stream _ name : stream name
: return : dataset function name providing the respective stream
: raise AttributeError : if the dataset does not provide the function creating the... | if stream_name not in self . _streams :
stream_fn_name = '{}_stream' . format ( stream_name )
try :
stream_fn = getattr ( self . _dataset , stream_fn_name )
stream_epoch_limit = - 1
if self . _fixed_epoch_size is not None and stream_name == self . _train_stream_name :
stream_... |
def reverse_point ( self , latitude , longitude , ** kwargs ) :
"""Method for identifying an address from a geographic point""" | fields = "," . join ( kwargs . pop ( "fields" , [ ] ) )
point_param = "{0},{1}" . format ( latitude , longitude )
response = self . _req ( verb = "reverse" , params = { "q" : point_param , "fields" : fields } )
if response . status_code != 200 :
return error_response ( response )
return Location ( response . json (... |
def draw_pegasus_yield ( G , ** kwargs ) :
"""Draws the given graph G with highlighted faults , according to layout .
Parameters
G : NetworkX graph
The graph to be parsed for faults
unused _ color : tuple or color string ( optional , default ( 0.9,0.9,0.9,1.0 ) )
The color to use for nodes and edges of G ... | try :
assert ( G . graph [ "family" ] == "pegasus" )
m = G . graph [ 'columns' ]
offset_lists = ( G . graph [ 'vertical_offsets' ] , G . graph [ 'horizontal_offsets' ] )
coordinates = G . graph [ "labels" ] == "coordinate"
# Can ' t interpret fabric _ only from graph attributes
except :
raise Va... |
def critical ( self , text ) :
"""Posts a critical message adding a timestamp and logging level to it for both file and console handlers .
Logger uses a redraw rate because of console flickering . That means it will not draw new messages or progress
at the very time they are being logged but their timestamp wil... | self . queue . put ( dill . dumps ( LogMessageCommand ( text = text , level = logging . CRITICAL ) ) ) |
def LR_predict ( w , b , X ) :
"""Predict whether the label is 0 or 1 using learned logistic regression parameters ( w , b )
Arguments :
w - - weights , a numpy array of size ( num _ px * num _ px * 3 , 1)
b - - bias , a scalar
X - - data of size ( num _ px * num _ px * 3 , number of examples )
Returns : ... | m = X . shape [ 1 ]
Y_prediction = np . zeros ( ( 1 , m ) )
w = w . reshape ( X . shape [ 0 ] , 1 )
A = sigmoid ( np . dot ( w . T , X ) + b )
for i in range ( A . shape [ 1 ] ) :
if A [ 0 , i ] > 0.5 :
Y_prediction [ 0 , i ] = 1.0
else :
Y_prediction [ 0 , i ] = 0.0
assert ( Y_prediction . shap... |
def is_null ( value ) :
"""Check if the scalar value or tuple / list value is NULL .
: param value : Value to check .
: type value : a scalar or tuple or list
: return : Returns ` ` True ` ` if and only if the value is NULL ( scalar value is None
or _ any _ tuple / list elements are None ) .
: rtype : boo... | if type ( value ) in ( tuple , list ) :
for v in value :
if v is None :
return True
return False
else :
return value is None |
def match ( self , props = None , rng = None , offset = None ) :
"""Provide any of the args and match or dont .
: param props : Should be a subset of my props .
: param rng : Exactly match my range .
: param offset : I start after this offset .
: returns : True if all the provided predicates match or are No... | if rng :
s , e = rng
else :
e = s = None
return ( ( e is None or self . end == e ) and ( s is None or self . start == s ) ) and ( props is None or props . issubset ( self . props ) ) and ( offset is None or self . start >= offset ) |
def send_private_message ( self , user_id , message ) :
"""Send a message to a specific client .
Returns True if successful , False otherwise""" | try :
client = self . channels [ 'private' ] [ str ( user_id ) ]
except KeyError :
print '====debug===='
print self . channels [ 'private' ]
print 'client with id %s not found' % user_id
return False
client . send_message ( message )
print 'message sent to client #%s' % user_id
return True |
def _update_metadata ( self , data , ds_info ) :
"""Update metadata of the given DataArray""" | # Metadata from the dataset definition
data . attrs . update ( ds_info )
# If the file _ type attribute is a list and the data is xarray
# the concat of the dataset will not work . As the file _ type is
# not needed this will be popped here .
if 'file_type' in data . attrs :
data . attrs . pop ( 'file_type' )
# Met... |
def GetNewSessionID ( self , ** _ ) :
"""Returns a random integer session ID for this hunt .
All hunts are created under the aff4 : / hunts namespace .
Returns :
a formatted session id string .""" | return rdfvalue . SessionID ( base = "aff4:/hunts" , queue = self . runner_args . queue ) |
def destroy ( self , request , pk = None , parent_lookup_seedteam = None , parent_lookup_seedteam__organization = None ) :
'''Remove a permission from a team .''' | self . check_team_permissions ( request , parent_lookup_seedteam , parent_lookup_seedteam__organization )
return super ( TeamPermissionViewSet , self ) . destroy ( request , pk , parent_lookup_seedteam , parent_lookup_seedteam__organization ) |
def search_in_hdx ( query , configuration = None , ** kwargs ) : # type : ( str , Optional [ Configuration ] , Any ) - > List [ ' Resource ' ]
"""Searches for resources in HDX . NOTE : Does not search dataset metadata !
Args :
query ( str ) : Query
configuration ( Optional [ Configuration ] ) : HDX configurat... | resources = [ ]
resource = Resource ( configuration = configuration )
success , result = resource . _read_from_hdx ( 'resource' , query , 'query' , Resource . actions ( ) [ 'search' ] )
if result :
count = result . get ( 'count' , None )
if count :
for resourcedict in result [ 'results' ] :
... |
def corr ( dataset , column , method = "pearson" ) :
"""Compute the correlation matrix with specified method using dataset .
: param dataset :
A Dataset or a DataFrame .
: param column :
The name of the column of vectors for which the correlation coefficient needs
to be computed . This must be a column of... | sc = SparkContext . _active_spark_context
javaCorrObj = _jvm ( ) . org . apache . spark . ml . stat . Correlation
args = [ _py2java ( sc , arg ) for arg in ( dataset , column , method ) ]
return _java2py ( sc , javaCorrObj . corr ( * args ) ) |
def save_to_json ( self ) :
"""The method saves DatasetUpload to json from object""" | requestvalues = { 'DatasetId' : self . dataset , 'Name' : self . name , 'Description' : self . description , 'Source' : self . source , 'PubDate' : self . publication_date , 'AccessedOn' : self . accessed_on , 'Url' : self . dataset_ref , 'UploadFormatType' : self . upload_format_type , 'Columns' : self . columns , 'Fi... |
def _cooked_fields ( self , dj_fields ) :
"""Returns a tuple of cooked fields
: param dj _ fields : a list of django name fields
: return :""" | from django . db import models
valids = [ ]
for field in dj_fields :
try :
dj_field , _ , _ , _ = self . model . _meta . get_field_by_name ( field )
if isinstance ( dj_field , models . ForeignKey ) :
valids . append ( ( field + "_id" , field , dj_field ) )
else :
vali... |
def sent_tokenize ( text : str , engine : str = "whitespace+newline" ) -> List [ str ] :
"""This function does not yet automatically recognize when a sentence actually ends . Rather it helps split text where white space and a new line is found .
: param str text : the text to be tokenized
: param str engine : c... | if not text or not isinstance ( text , str ) :
return [ ]
sentences = [ ]
if engine == "whitespace" :
sentences = re . split ( r" +" , text , re . U )
else : # default , use whitespace + newline
sentences = text . split ( )
return sentences |
def validate_node_sign ( signature_node , elem , cert = None , fingerprint = None , fingerprintalg = 'sha1' , validatecert = False , debug = False ) :
"""Validates a signature node .
: param signature _ node : The signature node
: type : Node
: param xml : The element we should validate
: type : Document
... | if ( cert is None or cert == '' ) and fingerprint :
x509_certificate_nodes = OneLogin_Saml2_XML . query ( signature_node , '//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate' )
if len ( x509_certificate_nodes ) > 0 :
x509_certificate_node = x509_certificate_nodes [ 0 ]
x509_cert_value = O... |
def Churchill_1977 ( Re , eD ) :
r'''Calculates Darcy friction factor using the method in Churchill and
(1977 ) [ 2 ] _ as shown in [ 1 ] _ .
. . math : :
f _ f = 2 \ left [ ( \ frac { 8 } { Re } ) ^ { 12 } + ( A _ 2 + A _ 3 ) ^ { - 1.5 } \ right ] ^ { 1/12}
. . math : :
A _ 2 = \ left \ { 2.457 \ ln \ le... | A3 = ( 37530 / Re ) ** 16
A2 = ( 2.457 * log ( ( 7. / Re ) ** 0.9 + 0.27 * eD ) ) ** 16
ff = 2 * ( ( 8 / Re ) ** 12 + 1 / ( A2 + A3 ) ** 1.5 ) ** ( 1 / 12. )
return 4 * ff |
def parse_list_parts ( data , bucket_name , object_name , upload_id ) :
"""Parser for list parts response .
: param data : Response data for list parts .
: param bucket _ name : Response for the bucket .
: param object _ name : Response for the object .
: param upload _ id : Upload id of object name for
t... | root = S3Element . fromstring ( 'ListPartsResult' , data )
is_truncated = root . get_child_text ( 'IsTruncated' ) . lower ( ) == 'true'
part_marker = root . get_child_text ( 'NextPartNumberMarker' , strict = False )
parts = [ UploadPart ( bucket_name , object_name , upload_id , part . get_int_elem ( 'PartNumber' ) , pa... |
def _registerHandler ( self , handler ) :
"""Registers a handler .
: param handler : A handler object .""" | self . _logger . addHandler ( handler )
self . _handlers . append ( handler ) |
def getServiceMessages ( self , remote ) :
"""Get service messages from CCU / Homegear""" | try :
return self . proxies [ "%s-%s" % ( self . _interface_id , remote ) ] . getServiceMessages ( )
except Exception as err :
LOG . debug ( "ServerThread.getServiceMessages: Exception: %s" % str ( err ) ) |
def float_str ( f , min_digits = 2 , max_digits = 6 ) :
"""Returns a string representing a float , where the number of
significant digits is min _ digits unless it takes more digits
to hit a non - zero digit ( and the number is 0 < x < 1 ) .
We stop looking for a non - zero digit after max _ digits .""" | if f >= 1 or f <= 0 :
return str ( round_float ( f , min_digits ) )
start_str = str ( round_float ( f , max_digits ) )
digits = start_str . split ( "." ) [ 1 ]
non_zero_indices = [ ]
for i , digit in enumerate ( digits ) :
if digit != "0" :
non_zero_indices . append ( i + 1 )
# Only saw 0s .
if len ( no... |
def strides ( self , time = None , spatial = None ) :
"""Set time and / or spatial ( horizontal ) strides .
This is only used on grid requests . Used to skip points in the returned data .
This modifies the query in - place , but returns ` self ` so that multiple queries
can be chained together on one line .
... | if time :
self . add_query_parameter ( timeStride = time )
if spatial :
self . add_query_parameter ( horizStride = spatial )
return self |
def reload ( self ) :
"""Reload notmuch and alot config files""" | self . read_notmuch_config ( self . _notmuchconfig . filename )
self . read_config ( self . _config . filename ) |
def get ( no_create = False , server = None , port = None , force_uuid = None ) :
"""Get the thread local singleton""" | pid = os . getpid ( )
thread = threading . current_thread ( )
wdb = Wdb . _instances . get ( ( pid , thread ) )
if not wdb and not no_create :
wdb = object . __new__ ( Wdb )
Wdb . __init__ ( wdb , server , port , force_uuid )
wdb . pid = pid
wdb . thread = thread
Wdb . _instances [ ( pid , thread ) ... |
def truncate ( text , length = 50 , ellipsis = '...' ) :
"""Returns a truncated version of the inputted text .
: param text | < str >
length | < int >
ellipsis | < str >
: return < str >""" | text = nativestring ( text )
return text [ : length ] + ( text [ length : ] and ellipsis ) |
def cached ( key = None , extradata = { } ) :
'''Decorator used for caching .''' | def decorator ( f ) :
@ wraps ( f )
def wrapper ( * args , ** kwargs ) :
uid = key
if not uid :
from hashlib import md5
arguments = list ( args ) + [ ( a , kwargs [ a ] ) for a in sorted ( kwargs . keys ( ) ) ]
uid = md5 ( str ( arguments ) ) . hexdigest ( )
... |
def _encode_mapping ( name , value , check_keys , opts ) :
"""Encode a mapping type .""" | data = b"" . join ( [ _element_to_bson ( key , val , check_keys , opts ) for key , val in iteritems ( value ) ] )
return b"\x03" + name + _PACK_INT ( len ( data ) + 5 ) + data + b"\x00" |
def cosmetics ( flat1 , flat2 = None , mask = None , lowercut = 6.0 , uppercut = 6.0 , siglev = 2.0 ) :
"""Find cosmetic defects in a detector using two flat field images .
Two arrays representing flat fields of different exposure times are
required . Cosmetic defects are selected as points that deviate
signi... | if flat2 is None :
flat1 , flat2 = flat2 , flat1
flat1 = numpy . ones_like ( flat2 )
if type ( mask ) is not numpy . ndarray :
mask = numpy . zeros ( flat1 . shape , dtype = 'int' )
ratio , mask = comp_ratio ( flat1 , flat2 , mask )
fratio1 = ratio [ ~ mask ]
central = numpy . median ( fratio1 )
std = robus... |
def _validate_fname ( fname , arg_name ) :
"""Validate that a string is a valid file name .""" | if fname is not None :
msg = "Argument `{0}` is not valid" . format ( arg_name )
if ( not isinstance ( fname , str ) ) or ( isinstance ( fname , str ) and ( "\0" in fname ) ) :
raise RuntimeError ( msg )
try :
if not os . path . exists ( fname ) :
os . access ( fname , os . W_OK ... |
def setNetworkIDTimeout ( self , iNwkIDTimeOut ) :
"""set networkid timeout for Thread device
Args :
iNwkIDTimeOut : a given NETWORK _ ID _ TIMEOUT
Returns :
True : successful to set NETWORK _ ID _ TIMEOUT
False : fail to set NETWORK _ ID _ TIMEOUT""" | print '%s call setNetworkIDTimeout' % self . port
print iNwkIDTimeOut
iNwkIDTimeOut /= 1000
try :
cmd = 'networkidtimeout %s' % str ( iNwkIDTimeOut )
print cmd
return self . __sendCommand ( cmd ) [ 0 ] == 'Done'
except Exception , e :
ModuleHelper . WriteIntoDebugLogger ( "setNetworkIDTimeout() Error: "... |
def all ( cls ) :
"""Get all informations about this account""" | account = cls . info ( )
creditusage = cls . creditusage ( )
if not creditusage :
return account
left = account [ 'credits' ] / creditusage
years , hours = divmod ( left , 365 * 24 )
months , hours = divmod ( hours , 31 * 24 )
days , hours = divmod ( hours , 24 )
account . update ( { 'credit_usage' : creditusage , ... |
def pxform ( fromstr , tostr , et ) :
"""Return the matrix that transforms position vectors from one
specified frame to another at a specified epoch .
http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / pxform _ c . html
: param fromstr : Name of the frame to transform from .
: t... | et = ctypes . c_double ( et )
tostr = stypes . stringToCharP ( tostr )
fromstr = stypes . stringToCharP ( fromstr )
rotatematrix = stypes . emptyDoubleMatrix ( )
libspice . pxform_c ( fromstr , tostr , et , rotatematrix )
return stypes . cMatrixToNumpy ( rotatematrix ) |
def standard_deviation ( data , period ) :
"""Standard Deviation .
Formula :
std = sqrt ( avg ( abs ( x - avg ( x ) ) ^ 2 ) )""" | catch_errors . check_for_period_error ( data , period )
stds = [ np . std ( data [ idx + 1 - period : idx + 1 ] , ddof = 1 ) for idx in range ( period - 1 , len ( data ) ) ]
stds = fill_for_noncomputable_vals ( data , stds )
return stds |
def add_semantic_hub_layout ( cx , hub ) :
"""Attach a layout aspect to a CX network given a hub node .""" | graph = cx_to_networkx ( cx )
hub_node = get_node_by_name ( graph , hub )
node_classes = classify_nodes ( graph , hub_node )
layout_aspect = get_layout_aspect ( hub_node , node_classes )
cx [ 'cartesianLayout' ] = layout_aspect |
def message ( self , phone_number , message , message_type , ** params ) :
"""Send a message to the target phone _ number .
See https : / / developer . telesign . com / docs / messaging - api for detailed API documentation .""" | return self . post ( MESSAGING_RESOURCE , phone_number = phone_number , message = message , message_type = message_type , ** params ) |
def jsName ( path , name ) :
'''Returns a name string without \ , - , and . so that
the string will play nicely with javascript .''' | shortPath = path . replace ( "C:\\Users\\scheinerbock\\Desktop\\" + "ideogram\\scrapeSource\\test\\" , "" )
noDash = shortPath . replace ( "-" , "_dash_" )
jsPath = noDash . replace ( "\\" , "_slash_" ) . replace ( "." , "_dot_" )
jsName = jsPath + '_slash_' + name
return jsName |
def sequence_to_alignment_coords ( self , seq_name , start , end , trim = False ) :
"""convert an interval in one of the sequences into an interval in the
alignment . Alignment intervals are inclusive of start , but not end . They
are one - based . Hence the full alignment has coords [ 1 , N + 1 ) , where N is ... | # check for valid order of start / end
if end <= start :
raise InvalidSequenceCoordinatesError ( "invalid region: " + str ( start ) + ", " + str ( end ) )
seq = self [ seq_name ]
s_start = seq . start
s_end = seq . end
pos_strand = seq . is_positive_strand ( )
# check that the start and end coords are at least part... |
def main ( argv = None ) :
'''Execute the " intake " command line program .''' | from intake . cli . bootstrap import main as _main
return _main ( 'Intake Catalog CLI' , subcommands . all , argv or sys . argv ) |
def add_it ( workbench , file_list , labels ) :
"""Add the given file _ list to workbench as samples , also add them as nodes .
Args :
workbench : Instance of Workbench Client .
file _ list : list of files .
labels : labels for the nodes .
Returns :
A list of md5s .""" | md5s = [ ]
for filename in file_list :
if filename != '.DS_Store' :
with open ( filename , 'rb' ) as pe_file :
base_name = os . path . basename ( filename )
md5 = workbench . store_sample ( pe_file . read ( ) , base_name , 'exe' )
workbench . add_node ( md5 , md5 [ : 6 ] ... |
def mutate ( self ) :
"""Mutates code .""" | # Choose a random position
if len ( self . code ) == 0 :
return
index = random . randint ( 0 , len ( self . code ) - 1 )
mutation_type = random . random ( )
if mutation_type < 0.5 : # Change
self . code [ index ] = self . new ( ) . randomize ( ) . code [ 0 ]
elif mutation_type < 0.75 : # Deletion
del self .... |
def get_relation_count_query ( self , query , parent ) :
"""Add the constraints for a relationship count query .
: type query : orator . orm . Builder
: type parent : orator . orm . Builder
: rtype : orator . orm . Builder""" | if parent . get_query ( ) . from__ == query . get_query ( ) . from__ :
return self . get_relation_count_query_for_self_join ( query , parent )
self . _set_join ( query )
return super ( BelongsToMany , self ) . get_relation_count_query ( query , parent ) |
def _uncythonized_model ( self , beta ) :
"""Creates the structure of the model
Parameters
beta : np . array
Contains untransformed starting values for latent variables
Returns
theta : np . array
Contains the predicted values for the time series
Y : np . array
Contains the length - adjusted time ser... | parm = np . array ( [ self . latent_variables . z_list [ k ] . prior . transform ( beta [ k ] ) for k in range ( beta . shape [ 0 ] ) ] )
theta = np . zeros ( self . model_Y . shape [ 0 ] )
model_scale , model_shape , model_skewness = self . _get_scale_and_shape ( parm )
# Loop over time series
theta , self . model_sco... |
def ray_triangle_id ( triangles , ray_origins , ray_directions , triangles_normal = None , tree = None , multiple_hits = True ) :
"""Find the intersections between a group of triangles and rays
Parameters
triangles : ( n , 3 , 3 ) float
Triangles in space
ray _ origins : ( m , 3 ) float
Ray origin points ... | triangles = np . asanyarray ( triangles , dtype = np . float64 )
ray_origins = np . asanyarray ( ray_origins , dtype = np . float64 )
ray_directions = np . asanyarray ( ray_directions , dtype = np . float64 )
# if we didn ' t get passed an r - tree for the bounds of each
# triangle create one here
if tree is None :
... |
def flatten ( l ) :
'''Flatten a multi - deminision list and return a iterable
Note that dict and str will not be expanded , instead , they will be kept as a single element .
Args :
l ( list ) : The list needs to be flattened
Returns :
A iterable of flattened list . To have a list instead use ` ` list ( f... | for el in l : # I don ; t want dict to be flattened
if isinstance ( el , Iterable ) and not isinstance ( el , ( str , bytes ) ) and not isinstance ( el , dict ) :
yield from flatten ( el )
else :
yield el |
def old_format ( self , content : BeautifulSoup ) -> List [ str ] :
"""Extracts email message information if it uses the old Mailman format
Args :
content : BeautifulSoup
Returns : List [ str ]""" | b = content . find ( 'body' )
sender , date , nxt , rep_to = None , None , None , None
strongs = b . findAll ( 'strong' , recursive = False )
for s in strongs :
field = str ( s ) . split ( ">" ) [ 1 ] . split ( "<" ) [ 0 ]
if 'From' in field :
sender = s . next_sibling . split ( "(" ) [ 0 ] . strip ( )
... |
def hex_color_to_tuple ( hex ) :
"""convent hex color to tuple
" # fffff " - > ( 255 , 255 , 255)
" # ffff00ff " - > ( 255 , 255 , 0 , 255)""" | hex = hex [ 1 : ]
length = len ( hex ) // 2
return tuple ( int ( hex [ i * 2 : i * 2 + 2 ] , 16 ) for i in range ( length ) ) |
def run_track ( track , result_hosts = None , crate_root = None , output_fmt = None , logfile_info = None , logfile_result = None , failfast = False , sample_mode = 'reservoir' ) :
"""Execute a track file""" | with Logger ( output_fmt = output_fmt , logfile_info = logfile_info , logfile_result = logfile_result ) as log :
executor = Executor ( track_dir = os . path . dirname ( track ) , log = log , result_hosts = result_hosts , crate_root = crate_root , fail_fast = failfast , sample_mode = sample_mode )
error = execut... |
def consume_all ( self , max_loops = None ) :
"""Consume the streamed responses until there are no more .
. . warning : :
This method will be removed in future releases . Please use this
class as a generator instead .
: type max _ loops : int
: param max _ loops : ( Optional ) Maximum number of times to t... | for row in self :
self . rows [ row . row_key ] = row |
def _check ( self ) :
"""Validates model parameters prior to fitting .
Raises
ValueError
If any of the parameters are invalid , e . g . if : attr : ` startprob _ `
don ' t sum to 1.""" | self . startprob_ = np . asarray ( self . startprob_ )
if len ( self . startprob_ ) != self . n_components :
raise ValueError ( "startprob_ must have length n_components" )
if not np . allclose ( self . startprob_ . sum ( ) , 1.0 ) :
raise ValueError ( "startprob_ must sum to 1.0 (got {:.4f})" . format ( self .... |
def deployment_delete ( name , resource_group , ** kwargs ) :
'''. . versionadded : : 2019.2.0
Delete a deployment .
: param name : The name of the deployment to delete .
: param resource _ group : The resource group name assigned to the
deployment .
CLI Example :
. . code - block : : bash
salt - call... | result = False
resconn = __utils__ [ 'azurearm.get_client' ] ( 'resource' , ** kwargs )
try :
deploy = resconn . deployments . delete ( deployment_name = name , resource_group_name = resource_group )
deploy . wait ( )
result = True
except CloudError as exc :
__utils__ [ 'azurearm.log_cloud_error' ] ( 'r... |
def zstack_array ( self , s = 0 , c = 0 , t = 0 ) :
"""Return zstack as a : class : ` numpy . ndarray ` .
: param s : series
: param c : channel
: param t : timepoint
: returns : zstack as a : class : ` numpy . ndarray `""" | return np . dstack ( [ x . image for x in self . zstack_proxy_iterator ( s = s , c = c , t = t ) ] ) |
def param_set_send ( self , parm_name , parm_value , parm_type = None ) :
'''wrapper for parameter set''' | if self . mavlink10 ( ) :
if parm_type == None :
parm_type = mavlink . MAVLINK_TYPE_FLOAT
self . mav . param_set_send ( self . target_system , self . target_component , parm_name , parm_value , parm_type )
else :
self . mav . param_set_send ( self . target_system , self . target_component , parm_nam... |
def _loads ( self , string ) :
"""If : prop : serialized is True , @ string will be unserialized
using : prop : serializer""" | if not self . serialized :
return self . _decode ( string )
if string is not None :
try :
return self . serializer . loads ( string )
except TypeError : # : catches bytes errors with the builtin json library
return self . serializer . loads ( self . _decode ( string ) )
except pickle . U... |
def import_events ( self , source = 'wonambi' ) :
"""action : import events from text file ( Wonambi or RemLogic ) .""" | if self . annot is None : # remove if buttons are disabled
self . parent . statusBar ( ) . showMessage ( 'No score file loaded' )
return
if 'wonambi' == source :
format_str = 'CSV File (*.csv)'
rec_start = None
elif 'remlogic' == source :
format_str = 'Text file (*.txt)'
rec_start = self . paren... |
def configure_scraper ( self , scraper_config ) :
"""Configures a PrometheusScaper object with query credentials
: param scraper : valid PrometheusScaper object
: param endpoint : url that will be scraped""" | endpoint = scraper_config [ 'prometheus_url' ]
scraper_config . update ( { 'ssl_ca_cert' : self . _ssl_verify , 'ssl_cert' : self . _ssl_cert , 'ssl_private_key' : self . _ssl_private_key , 'extra_headers' : self . headers ( endpoint ) or { } , } ) |
def _get_args ( self , kwargs ) :
'''Discard all keywords which aren ' t function - specific from the kwargs .
: param kwargs :
: return :''' | _args = list ( )
_kwargs = salt . utils . args . clean_kwargs ( ** kwargs )
return _args , _kwargs |
def _build_endpoint ( self , endpoint_name ) :
"""Generate an enpoint url from a setting name .
Args :
endpoint _ name ( str ) : setting name for the enpoint to build
Returns :
( str ) url enpoint""" | endpoint_relative = settings . get ( 'asmaster_endpoints' , endpoint_name )
return '%s%s' % ( self . host , endpoint_relative ) |
def _asStr ( self ) :
'''_ asStr - Get the string representation of this style
@ return < str > - A string representation of this style ( semicolon separated , key : value format )''' | styleDict = self . _styleDict
if styleDict :
return '; ' . join ( [ name + ': ' + value for name , value in styleDict . items ( ) ] )
return '' |
def fmt_ac_sia ( ac_sia ) :
"""Format a AcSystemIrreducibilityAnalysis .""" | body = ( '{ALPHA} = {alpha}\n' 'direction: {ac_sia.direction}\n' 'transition: {ac_sia.transition}\n' 'before state: {ac_sia.before_state}\n' 'after state: {ac_sia.after_state}\n' 'cut:\n{ac_sia.cut}\n' '{account}\n' '{partitioned_account}' . format ( ALPHA = ALPHA , alpha = round ( ac_sia . alpha , 4 ) , ac_sia = ac_si... |
def nl_cb_err ( cb , kind , func , arg ) :
"""Set up an error callback . Updates ` cb ` in place .
https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / handlers . c # L343
Positional arguments :
cb - - nl _ cb class instance .
kind - - kind of callback ( integer ) .
func - - callback fu... | if kind < 0 or kind > NL_CB_KIND_MAX :
return - NLE_RANGE
if kind == NL_CB_CUSTOM :
cb . cb_err = func
cb . cb_err_arg = arg
else :
cb . cb_err = cb_err_def [ kind ]
cb . cb_err_arg = arg
return 0 |
def _create_signing_params ( self , url , keypair_id , expire_time = None , valid_after_time = None , ip_address = None , policy_url = None , private_key_file = None , private_key_string = None ) :
"""Creates the required URL parameters for a signed URL .""" | params = { }
# Check if we can use a canned policy
if expire_time and not valid_after_time and not ip_address and not policy_url : # we manually construct this policy string to ensure formatting
# matches signature
policy = self . _canned_policy ( url , expire_time )
params [ "Expires" ] = str ( expire_time )
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.