signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def binned_bitsets_by_chrom ( f , chrom , chrom_col = 0 , start_col = 1 , end_col = 2 ) :
"""Read a file by chrom name into a bitset""" | bitset = BinnedBitSet ( MAX )
for line in f :
if line . startswith ( "#" ) :
continue
fields = line . split ( )
if fields [ chrom_col ] == chrom :
start , end = int ( fields [ start_col ] ) , int ( fields [ end_col ] )
bitset . set_range ( start , end - start )
return bitset |
def get_installation_order ( self , req_set ) : # type : ( RequirementSet ) - > List [ InstallRequirement ]
"""Create the installation order .
The installation order is topological - requirements are installed
before the requiring thing . We break cycles at an arbitrary point ,
and make no other guarantees ."... | # The current implementation , which we may change at any point
# installs the user specified things in the order given , except when
# dependencies must come earlier to achieve topological order .
order = [ ]
ordered_reqs = set ( )
# type : Set [ InstallRequirement ]
def schedule ( req ) :
if req . satisfied_by or... |
def nvmlDeviceGetAccountingPids ( handle ) :
r"""* Queries list of processes that can be queried for accounting stats . The list of processes returned
* can be in running or terminated state .
* For Kepler & tm ; or newer fully supported devices .
* To just query the number of processes ready to be queried , ... | count = c_uint ( nvmlDeviceGetAccountingBufferSize ( handle ) )
pids = ( c_uint * count . value ) ( )
fn = _nvmlGetFunctionPointer ( "nvmlDeviceGetAccountingPids" )
ret = fn ( handle , byref ( count ) , pids )
_nvmlCheckReturn ( ret )
return list ( map ( int , pids [ 0 : count . value ] ) ) |
def set_workdir ( self , workdir , chroot = False ) :
"""Set the working directory . Cannot be set more than once unless chroot is True""" | if not chroot and hasattr ( self , "workdir" ) and self . workdir != workdir :
raise ValueError ( "self.workdir != workdir: %s, %s" % ( self . workdir , workdir ) )
self . workdir = os . path . abspath ( workdir )
# Files required for the execution .
self . input_file = File ( os . path . join ( self . workdir , "r... |
def parse_create_zone ( prs , conn ) :
"""Create zone .
Arguments :
prs : parser object of argparse
conn : dictionary of connection information""" | prs_zone_create = prs . add_parser ( 'zone_create' , help = 'create zone' )
prs_zone_create . add_argument ( '--domain' , action = 'store' , required = True , help = 'specify zone' )
prs_zone_create . add_argument ( '--dnsaddr' , action = 'store' , required = True , help = 'specify IP address of DNS master' )
group_zon... |
def restore ( ctx , filename ) :
"""Restore the database from a zipped file .
Default is to restore from db dump in loqusdb / resources /""" | filename = filename or background_path
if not os . path . isfile ( filename ) :
LOG . warning ( "File {} does not exist. Please point to a valid file" . format ( filename ) )
ctx . abort ( )
call = [ 'mongorestore' , '--gzip' , '--db' , 'loqusdb' , '--archive={}' . format ( filename ) ]
LOG . info ( 'Restoring ... |
def server_session ( user , password , salt , A , B , b ) :
"""Server session secret
Both : u = H ( A , B )
Host : S = ( Av ^ u ) ^ b ( computes session key )
Host : K = H ( S )""" | N , g , k = get_prime ( )
u = get_scramble ( A , B )
v = get_verifier ( user , password , salt )
vu = pow ( v , u , N )
# v ^ u
Avu = ( A * vu ) % N
# Av ^ u
session_secret = pow ( Avu , b , N )
# ( Av ^ u ) ^ b
K = hash_digest ( hashlib . sha1 , session_secret )
if DEBUG_PRINT :
print ( 'server session_secret=' , ... |
def _supported_baremetal_transaction ( self , context ) :
"""Verify transaction is complete and for us .""" | port = context . current
if self . trunk . is_trunk_subport_baremetal ( port ) :
return self . _baremetal_set_binding ( context )
if not nexus_help . is_baremetal ( port ) :
return False
if bc . portbindings . PROFILE not in port :
return False
profile = port [ bc . portbindings . PROFILE ]
if 'local_link_i... |
def mix2PL_wsse ( mean , estimator , m ) :
"""Description :
Calculates the weighted Sum of Squared Errors ( WSSE )
of an estimator of a mixture of 2 Plackett - Luce models ,
on flat numpy ndarrays , where the first element is
the mixing proportion of the first model defined
as the minimum WSSE over the in... | def wsse ( mean1 , est1 , m1 ) :
return ( ( ( est1 [ 0 ] - mean1 [ 0 ] ) ** 2 ) + ( mean1 [ 0 ] * np . sum ( ( np . asarray ( est1 [ 1 : m1 + 1 ] ) - np . asarray ( mean1 [ 1 : m1 + 1 ] ) ) ** 2 ) ) + ( ( 1 - mean1 [ 0 ] ) * np . sum ( ( np . asarray ( est1 [ m1 + 1 : ] ) - np . asarray ( mean1 [ m1 + 1 : ] ) ) ** ... |
def build_altseq ( self ) :
"""given a variant and a sequence , incorporate the variant and return the new sequence
Data structure returned is analogous to the data structure used to return the variant sequence ,
but with an additional parameter denoting the start of a frameshift that should affect all bases
... | NOT_CDS = "not_cds_variant"
WHOLE_GENE_DELETED = "whole_gene_deleted"
type_map = { NARefAlt : self . _incorporate_delins , Dup : self . _incorporate_dup , Inv : self . _incorporate_inv , Repeat : self . _incorporate_repeat , NOT_CDS : self . _create_alt_equals_ref_noncds , WHOLE_GENE_DELETED : self . _create_no_protein... |
def _executor_internal ( self , host ) :
'''executes any module one or more times''' | host_variables = self . inventory . get_variables ( host )
if self . transport in [ 'paramiko' , 'ssh' ] :
port = host_variables . get ( 'ansible_ssh_port' , self . remote_port )
if port is None :
port = C . DEFAULT_REMOTE_PORT
else : # fireball , local , etc
port = self . remote_port
inject = { }
i... |
def token ( config , token ) :
"""Store and fetch a GitHub access token""" | if not token :
info_out ( "To generate a personal API token, go to:\n\n\t" "https://github.com/settings/tokens\n\n" "To read more about it, go to:\n\n\t" "https://help.github.com/articles/creating-an-access" "-token-for-command-line-use/\n\n" 'Remember to enable "repo" in the scopes.' )
token = getpass . getpas... |
def save ( self , * args , ** kwargs ) :
"""sets the ` slug ` values as the name
: param args : inline arguments ( optional )
: param kwargs : keyword arguments ( optional )
: return : ` super . save ( ) `""" | self . slug = slugify ( self . name ) [ : 50 ]
return super ( Tag , self ) . save ( * args , ** kwargs ) |
def put ( self , job , result ) :
"Perform a job by a member in the pool and return the result ." | self . job . put ( job )
r = result . get ( )
return r |
def looks_like_a_filename ( kernel_source ) :
"""attempt to detect whether source code or a filename was passed""" | logging . debug ( 'looks_like_a_filename called' )
result = False
if isinstance ( kernel_source , str ) :
result = True
# test if not too long
if len ( kernel_source ) > 250 :
result = False
# test if not contains special characters
for c in "();{}\\" :
if c in kernel_source :
... |
def fft_transpose_numpy ( vec ) :
"""Perform a numpy transpose from vec into outvec .
( Alex to provide more details in a write - up . )
Parameters
vec : array
Input array .
Returns
outvec : array
Transposed output array .""" | N1 , N2 = splay ( vec )
return pycbc . types . Array ( vec . data . copy ( ) . reshape ( N2 , N1 ) . transpose ( ) . reshape ( len ( vec ) ) . copy ( ) ) |
def build_swagger_spec ( user , repo , sha , serverName ) :
"""Build grlc specification for the given github user / repo in swagger format""" | if user and repo : # Init provenance recording
prov_g = grlcPROV ( user , repo )
else :
prov_g = None
swag = swagger . get_blank_spec ( )
swag [ 'host' ] = serverName
try :
loader = getLoader ( user , repo , sha , prov_g )
except Exception as e : # If repo does not exits
swag [ 'info' ] = { 'title' : 'E... |
def _auto_install ( self ) :
"""Automatically detects images and installs them in the manifest if they
are not there already""" | template = Template ( template = self . manifest )
sections = template . sections ( )
images = self . d_client . images . list ( filters = { 'label' : 'vent' } )
add_sections = [ ]
status = ( True , None )
for image in images :
ignore = False
if ( 'Labels' in image . attrs [ 'Config' ] and 'vent.section' in ima... |
def date_parse ( s ) :
"""Parses value of a DATE type .
: param s : string to parse into date
: return : an instance of datetime . date
: raises NotSupportedError when a date Before Christ is encountered""" | s = as_str ( s )
if s . endswith ( ' BC' ) :
raise errors . NotSupportedError ( 'Dates Before Christ are not supported. Got: {0}' . format ( s ) )
# Value error , year might be over 9999
return date ( * map ( lambda x : min ( int ( x ) , 9999 ) , s . split ( '-' ) ) ) |
def _check_import_source ( ) :
"""Check if tlgu imported , if not import it .""" | path_rel = '~/cltk_data/greek/software/greek_software_tlgu/tlgu.h'
path = os . path . expanduser ( path_rel )
if not os . path . isfile ( path ) :
try :
corpus_importer = CorpusImporter ( 'greek' )
corpus_importer . import_corpus ( 'greek_software_tlgu' )
except Exception as exc :
logger... |
def load_tmy3_hourly_temp_data ( self , start , end , read_from_cache = True , write_to_cache = True ) :
"""Load hourly TMY3 temperature data from start date to end date ( inclusive ) .
This is the primary convenience method for loading hourly TMY3 temperature data .
Parameters
start : datetime . datetime
T... | return load_tmy3_hourly_temp_data ( self . usaf_id , start , end , read_from_cache = read_from_cache , write_to_cache = write_to_cache , ) |
def _req_files_edit ( self , fid , file_name = None , is_mark = 0 ) :
"""Edit a file or directory""" | url = self . web_api_url + '/edit'
data = locals ( )
del data [ 'self' ]
req = Request ( method = 'POST' , url = url , data = data )
res = self . http . send ( req )
if res . state :
return True
else :
raise RequestFailure ( 'Failed to access files API.' ) |
def _patch_magic ( self , buffer , orig ) :
"""Overwrite some probably wrong detections by mime libraries
: param buffer : bytes of the file to detect
: param orig : guess by mime libary
: return : corrected guess""" | if ( "Zip" in orig ) or ( '(JAR)' in orig ) :
val = is_android_raw ( buffer )
if val == "APK" :
return "Android application package file"
return orig |
def workflow_states_column ( self , obj ) :
"""Return text description of workflow states assigned to object""" | workflow_states = models . WorkflowState . objects . filter ( content_type = self . _get_obj_ct ( obj ) , object_id = obj . pk , )
return ', ' . join ( [ unicode ( wfs ) for wfs in workflow_states ] ) |
def add_cmd_handler ( self , cmd , func ) :
"""Adds a command handler for a command .""" | len_args = len ( inspect . getargspec ( func ) [ 0 ] )
def add_meta ( f ) :
def decorator ( * args , ** kwargs ) :
f ( * args , ** kwargs )
decorator . bytes_needed = len_args - 1
# exclude self
decorator . __name__ = f . __name__
return decorator
func = add_meta ( func )
self . _command_han... |
def get_http_connection ( self , host , is_secure ) :
"""Gets a connection from the pool for the named host . Returns
None if there is no connection that can be reused . It ' s the caller ' s
responsibility to call close ( ) on the connection when it ' s no longer
needed .""" | self . clean ( )
with self . mutex :
key = ( host , is_secure )
if key not in self . host_to_pool :
return None
return self . host_to_pool [ key ] . get ( ) |
def write ( self , stream ) :
"""Writes the topology to a stream or file .""" | topology = self . createTopology ( )
def write_it ( stream ) :
transportOut = TMemoryBuffer ( )
protocolOut = TBinaryProtocol . TBinaryProtocol ( transportOut )
topology . write ( protocolOut )
bytes = transportOut . getvalue ( )
stream . write ( bytes )
if isinstance ( stream , six . string_types )... |
def gapply ( grouped_data , func , schema , * cols ) :
"""Applies the function ` ` func ` ` to data grouped by key . In particular , given a dataframe
grouped by some set of key columns key1 , key2 , . . . , keyn , this method groups all the values
for each row with the same key columns into a single Pandas dat... | import pandas as pd
minPandasVersion = '0.7.1'
if LooseVersion ( pd . __version__ ) < LooseVersion ( minPandasVersion ) :
raise ImportError ( 'Pandas installed but version is {}, {} required' . format ( pd . __version__ , minPandasVersion ) )
# Do a null aggregation to retrieve the keys first ( should be no computa... |
def get_forwarding_information_base ( self , filter = '' ) :
"""Gets the forwarding information base data for a logical interconnect . A maximum of 100 entries is returned .
Optional filtering criteria might be specified .
Args :
filter ( list or str ) :
Filtering criteria may be specified using supported a... | uri = "{}{}" . format ( self . data [ "uri" ] , self . FORWARDING_INFORMATION_PATH )
return self . _helper . get_collection ( uri , filter = filter ) |
def _fetchAllChildren ( self ) :
"""Adds an ArrayRti per column as children so that they can be inspected easily""" | childItems = [ ]
if self . _array . ndim == 2 :
_nRows , nCols = self . _array . shape if self . _array is not None else ( 0 , 0 )
for col in range ( nCols ) :
colItem = SliceRti ( self . _array [ : , col ] , nodeName = "channel-{}" . format ( col ) , fileName = self . fileName , iconColor = self . icon... |
def createURL ( self , word , mode = "phonefy" ) :
"""Method to create the URL replacing the word in the appropriate URL .
Args :
word : Word to be searched .
mode : Mode to be executed .
Return :
The URL to be queried .""" | try :
return self . modes [ mode ] [ "url" ] . format ( placeholder = urllib . pathname2url ( word ) )
except :
if mode == "base" :
if word [ 0 ] == "/" :
return self . baseURL + word [ 1 : ] , word
else :
return self . baseURL + word
else :
try :
... |
def iter_gff3 ( path , attributes = None , region = None , score_fill = - 1 , phase_fill = - 1 , attributes_fill = '.' , tabix = 'tabix' ) :
"""Iterate over records in a GFF3 file .
Parameters
path : string
Path to input file .
attributes : list of strings , optional
List of columns to extract from the " ... | # prepare fill values for attributes
if attributes is not None :
attributes = list ( attributes )
if isinstance ( attributes_fill , ( list , tuple ) ) :
if len ( attributes ) != len ( attributes_fill ) :
raise ValueError ( 'number of fills does not match attributes' )
else :
attr... |
def find_default ( self , filename ) :
"""A generate which looks in common folders for the default configuration
file . The paths goes from system defaults to user specific files .
: param filename : The name of the file to find
: return : The complete path to the found files""" | for path in self . DEFAULT_PATH : # Normalize path
path = os . path . expanduser ( os . path . expandvars ( path ) )
fullname = os . path . realpath ( os . path . join ( path , filename ) )
if os . path . exists ( fullname ) and os . path . isfile ( fullname ) :
yield fullname |
def derive_fields ( self ) :
"""Derives our fields .""" | if self . fields :
return self . fields
else :
fields = [ ]
for field in self . object_list . model . _meta . fields :
if field . name != 'id' :
fields . append ( field . name )
return fields |
def _collapse_author ( s ) :
"""Split author string back into organized dictionary
: param str s : Formatted names string " Last , F . ; Last , F . ; etc . . "
: return list of dict : One dictionary per author name""" | logger_ts . info ( "enter collapse_author" )
l = [ ]
authors = s . split ( ';' )
for author in authors :
l . append ( { 'name' : author } )
return l |
def get_or_create ( cls , spec , defaults = None ) :
'''Find or create single document . Return ( doc , created _ now ) .''' | docs = list ( cls . find ( spec ) . limit ( 2 ) )
assert len ( docs ) < 2 , 'multiple docs returned'
if docs :
return docs [ 0 ] , False
else :
kwargs = defaults or { }
kwargs . update ( spec )
doc = cls ( ** kwargs )
doc . save ( )
return doc , True |
def predicted_obs_vec ( self ) :
'''The predicted observation vector
The observation vector for the next step in the filter .''' | if not self . has_cached_obs_vec :
self . obs_vec = dot_n ( self . observation_matrix , self . predicted_state_vec [ : , : , np . newaxis ] ) [ : , : , 0 ]
return self . obs_vec |
def fade_to_color ( self , fade_milliseconds , color ) :
"""Fade the light to a known colour in a
: param fade _ milliseconds : Duration of the fade in milliseconds
: param color : Named color to fade to
: return : None""" | red , green , blue = self . color_to_rgb ( color )
return self . fade_to_rgb ( fade_milliseconds , red , green , blue ) |
def _send_and_wait ( self , ** kwargs ) :
"""Send a frame to either the local ZigBee or a remote device and wait
for a pre - defined amount of time for its response .""" | frame_id = self . next_frame_id
kwargs . update ( dict ( frame_id = frame_id ) )
self . _send ( ** kwargs )
timeout = datetime . now ( ) + const . RX_TIMEOUT
while datetime . now ( ) < timeout :
try :
frame = self . _rx_frames . pop ( frame_id )
raise_if_error ( frame )
return frame
exce... |
def Upload ( self , directory , filename ) :
"""Uploads / Updates / Replaces files""" | if self . _isMediaFile ( filename ) :
return self . _upload_media ( directory , filename )
elif self . _isConfigFile ( filename ) :
return self . _update_config ( directory , filename )
print "Not handled!"
return False |
def variable_map_items ( variable_map ) :
"""Yields an iterator over ( string , variable ) pairs in the variable map .
In general , variable maps map variable names to either a ` tf . Variable ` , or
list of ` tf . Variable ` s ( in case of sliced variables ) .
Args :
variable _ map : dict , variable map ov... | for key , var_or_vars in six . iteritems ( variable_map ) :
if isinstance ( var_or_vars , ( list , tuple ) ) :
for variable in var_or_vars :
yield key , variable
else :
yield key , var_or_vars |
def save ( self , model_file , save_dir , verbose = True ) :
"""Save current model .
: param model _ file : Saved model file name .
: type model _ file : str
: param save _ dir : Saved model directory .
: type save _ dir : str
: param verbose : Print log or not
: type verbose : bool""" | # Check existence of model saving directory and create if does not exist .
if not os . path . exists ( save_dir ) :
os . makedirs ( save_dir )
params = { "model" : self . state_dict ( ) , "cardinality" : self . cardinality , "name" : self . name , "config" : self . settings , }
try :
torch . save ( params , f"{... |
def maf_somatic_variant_stats ( variant , variant_metadata ) :
"""Parse out the variant calling statistics for a given variant from a MAF file
Assumes the MAF format described here : https : / / www . biostars . org / p / 161298 / # 161777
Parameters
variant : varcode . Variant
variant _ metadata : dict
D... | tumor_stats = None
normal_stats = None
if "t_ref_count" in variant_metadata :
tumor_stats = _maf_variant_stats ( variant , variant_metadata , prefix = "t" )
if "n_ref_count" in variant_metadata :
normal_stats = _maf_variant_stats ( variant , variant_metadata , prefix = "n" )
return SomaticVariantStats ( tumor_s... |
def get_roles ( server_context , container_path = None ) :
"""Gets the set of permissions and roles available from the server
: param server _ context : A LabKey server context . See utils . create _ server _ context .
: param container _ path :
: return :""" | url = server_context . build_url ( security_controller , 'getRoles.api' , container_path = container_path )
return server_context . make_request ( url , None ) |
def strip_head ( sequence , values ) :
"""Strips elements of ` values ` from the beginning of ` sequence ` .""" | values = set ( values )
return list ( itertools . dropwhile ( lambda x : x in values , sequence ) ) |
def list ( path = '.' ) :
"""generator that returns all files of * path *""" | import os
for f in os . listdir ( path ) :
if isfile ( join ( path , f ) ) :
yield join ( path , f ) if path != '.' else f |
def to_dict ( self , encoding = 'base64' ) :
'''Return a dictionary version of the report
: param encoding : required encoding for the string values ( default : ' base64 ' )
: rtype : dictionary
: return : dictionary representation of the report''' | res = { }
for k , v in self . _data_fields . items ( ) :
if isinstance ( v , ( bytes , bytearray , six . string_types ) ) :
v = StrEncodeEncoder ( encoding ) . encode ( v ) . tobytes ( ) . decode ( )
res [ k ] = v
for k , v in self . _sub_reports . items ( ) :
res [ k ] = v . to_dict ( encoding )
re... |
def create ( self , ** kwargs ) :
"""Custom create method to implement monitor parameter formatting .""" | if 'monitor' in kwargs :
value = self . _format_monitor_parameter ( kwargs [ 'monitor' ] )
kwargs [ 'monitor' ] = value
return super ( Pool , self ) . _create ( ** kwargs ) |
def slugify ( cls , s ) :
"""Return the slug version of the string ` ` s ` `""" | slug = re . sub ( "[^0-9a-zA-Z-]" , "-" , s )
return re . sub ( "-{2,}" , "-" , slug ) . strip ( '-' ) |
def _readFromUrl ( cls , url , writable ) :
"""Writes the contents of a file to a source ( writes url to writable )
using a ~ 10Mb buffer .
: param str url : A path as a string of the file to be read from .
: param object writable : An open file object to write to .""" | # we use a ~ 10Mb buffer to improve speed
with open ( cls . _extractPathFromUrl ( url ) , 'rb' ) as readable :
shutil . copyfileobj ( readable , writable , length = cls . BUFFER_SIZE ) |
def load_installed_plugins ( ) :
"""Search and load every installed plugin through entry points .""" | providers = { }
checkers = { }
for entry_point in pkg_resources . iter_entry_points ( group = 'archan' ) :
obj = entry_point . load ( )
if issubclass ( obj , Provider ) :
providers [ entry_point . name ] = obj
elif issubclass ( obj , Checker ) :
checkers [ entry_point . name ] = obj
return c... |
def generate_mail ( self ) :
"""Generate the email as MIMEText""" | # Script info
msg = "Script info : \r\n"
msg = msg + "%-9s: %s" % ( 'Script' , SOURCEDIR ) + "\r\n"
msg = msg + "%-9s: %s" % ( 'User' , USER ) + "\r\n"
msg = msg + "%-9s: %s" % ( 'Host' , HOST ) + "\r\n"
msg = msg + "%-9s: %s" % ( 'PID' , PID ) + "\r\n"
# Current trace
msg = msg + "\r\nCurrent trace : \r\n"
for record ... |
def wait_for_net ( self , timeout = None , wait_polling_interval = None ) :
"""Wait for the device to be assigned an IP address .
: param timeout : Maximum time to wait for an IP address to be defined
: param wait _ polling _ interval : Interval at which to poll for ip address .""" | if timeout is None :
timeout = self . _timeout
if wait_polling_interval is None :
wait_polling_interval = self . _wait_polling_interval
self . _logger . info ( "Waiting for network connection" )
poll_wait ( self . get_ip_address , timeout = timeout ) |
def list_stacks ( awsclient ) :
"""Print out the list of stacks deployed at AWS cloud .
: param awsclient :
: return :""" | client_cf = awsclient . get_client ( 'cloudformation' )
response = client_cf . list_stacks ( StackStatusFilter = [ 'CREATE_IN_PROGRESS' , 'CREATE_COMPLETE' , 'ROLLBACK_IN_PROGRESS' , 'ROLLBACK_COMPLETE' , 'DELETE_IN_PROGRESS' , 'DELETE_FAILED' , 'UPDATE_IN_PROGRESS' , 'UPDATE_COMPLETE_CLEANUP_IN_PROGRESS' , 'UPDATE_COM... |
def init_entity ( self , entity = None , input_data_frame = None , period = None , simulation = None ) :
"""Initialize the simulation period with current input _ data _ frame""" | assert entity is not None
assert input_data_frame is not None
assert period is not None
assert simulation is not None
used_as_input_variables = self . used_as_input_variables_by_entity [ entity ]
variables_mismatch = set ( used_as_input_variables ) . difference ( set ( input_data_frame . columns ) ) if used_as_input_va... |
def get_default_config_help ( self ) :
"""Return help text""" | config_help = super ( IcingaStatsCollector , self ) . get_default_config_help ( )
config_help . update ( { "status_path" : "Path to Icinga status.dat file" } )
return config_help |
def _isLikelyNotPhrase ( self , headVerbRoot , headVerbWID , nomAdvWID , widToToken ) :
'''Kontrollib , et nom / adv ei kuuluks mingi suurema fraasi kooseisu ( poleks fraasi peas6na ) .
Tagastab True , kui :
* ) nom / adv j2rgneb vahetult peaverbile
* ) või nom / adv on vahetult osalause alguses
* ) või n... | minWID = min ( widToToken . keys ( ) )
nomAdvToken = widToToken [ nomAdvWID ]
isNom = self . wtNom . matches ( nomAdvToken )
if headVerbWID + 1 == nomAdvWID : # 1 ) Kui nom / adv j2rgneb vahetult verbile , siis on ysna turvaline arvata ,
# et need kuuluvad kokku , nt :
# ja seda tunnet on _ 0 raske _ 0 millegi vastu va... |
def _write ( self , session , openFile , replaceParamFile ) :
"""Precipitation File Write to File Method""" | # Retrieve the events associated with this PrecipFile
events = self . precipEvents
# Write each event to file
for event in events :
openFile . write ( 'EVENT "%s"\nNRGAG %s\nNRPDS %s\n' % ( event . description , event . nrGag , event . nrPds ) )
if event . nrGag > 0 :
values = event . values
val... |
def extra_context ( self ) :
"""Add site _ name to context""" | from django . conf import settings
return { "site_name" : ( lambda r : settings . LEONARDO_SITE_NAME if getattr ( settings , 'LEONARDO_SITE_NAME' , '' ) != '' else settings . SITE_NAME ) , "debug" : lambda r : settings . TEMPLATE_DEBUG } |
def http_query ( self , method , path , data = { } , params = { } , timeout = 300 ) :
"""Make a query to the docker daemon
: param method : HTTP method
: param path : Endpoint in API
: param data : Dictionnary with the body . Will be transformed to a JSON
: param params : Parameters added as a query arg
:... | data = json . dumps ( data )
if timeout is None :
timeout = 60 * 60 * 24 * 31
# One month timeout
if path == 'version' :
url = "http://docker/v1.12/" + path
# API of docker v1.0
else :
url = "http://docker/v" + DOCKER_MINIMUM_API_VERSION + "/" + path
try :
if path != "version" : # version is use by ... |
def callproc ( self , procname , args = ( ) ) :
"""Execute stored procedure procname with args
procname - - string , name of procedure to execute on server
args - - Sequence of parameters to use with procedure
Returns the original args .
Compatibility warning : PEP - 249 specifies that any modified
parame... | db = self . _get_db ( )
if isinstance ( procname , unicode ) :
procname = procname . encode ( db . encoding )
if args :
fmt = b'@_' + procname + b'_%d=%s'
q = b'SET %s' % b',' . join ( fmt % ( index , db . literal ( arg ) ) for index , arg in enumerate ( args ) )
self . _query ( q )
self . nextset (... |
def _default ( cls , opts ) :
"""Setup default logger""" | level = getattr ( logging , opts . log_level , logging . DEBUG )
logger = logging . getLogger ( 'luigi-interface' )
logger . setLevel ( level )
stream_handler = logging . StreamHandler ( )
stream_handler . setLevel ( level )
formatter = logging . Formatter ( '%(levelname)s: %(message)s' )
stream_handler . setFormatter ... |
def _ELtowRRapRperi ( self , E , L ) :
"""NAME :
_ ELtowRRapRperi
PURPOSE :
calculate the radial frequency based on E , L , also return rap and
rperi
INPUT :
E - energy
L - angular momentum
OUTPUT :
wR ( E . L )
HISTORY :
2010-07-11 - Written - Bovy ( NYU )""" | if self . _beta == 0. :
xE = sc . exp ( E - .5 )
else : # non - flat rotation curve
xE = ( 2. * E / ( 1. + 1. / self . _beta ) ) ** ( 1. / 2. / self . _beta )
rperi , rap = self . _aA . calcRapRperi ( xE , 0. , L / xE , 0. , 0. )
# Replace the above w /
aA = actionAngleAxi ( xE , 0. , L / xE , pot = PowerSpheri... |
def list_volumes ( ) :
'''List configured volumes
CLI Example :
. . code - block : : bash
salt ' * ' glusterfs . list _ volumes''' | root = _gluster_xml ( 'volume list' )
if not _gluster_ok ( root ) :
return None
results = [ x . text for x in _iter ( root , 'volume' ) ]
return results |
def submit ( self , target = None , task = None , args = ( ) , kwargs = None , front = False , dispose_inputs = None ) :
"""Submit a new # Job to the ThreadPool .
# Arguments
task ( function , Job ) : Either a function that accepts a # Job , * args * and
* kwargs * or a # Job object that is in # ~ Job . PENDI... | if not self . __running :
raise RuntimeError ( "ThreadPool ain't running" )
if dispose_inputs is None :
dispose_inputs = self . dispose_inputs
if isinstance ( task , Job ) :
if args or kwargs :
raise TypeError ( 'can not provide additional arguments for Job' )
if task . state != Job . PENDING :
... |
def center ( self ) :
"""The cartesian center of the Compound based on its Particles .
Returns
np . ndarray , shape = ( 3 , ) , dtype = float
The cartesian center of the Compound based on its Particles""" | if np . all ( np . isfinite ( self . xyz ) ) :
return np . mean ( self . xyz , axis = 0 ) |
def show_inventory ( self , pretty = False ) :
"""Satisfies the ` ` - - list ` ` portion of ansible ' s external inventory API .
Allows ` ` bang ` ` to be used as an external inventory script , for example
when running ad - hoc ops tasks . For more details , see :
http : / / ansible . cc / docs / api . html #... | inv_lists = copy . deepcopy ( self . groups_and_vars . lists )
# sort the host lists to help consumers of the inventory ( e . g . ansible
# playbooks )
for l in inv_lists . values ( ) :
l . sort ( )
# new in ansible 1.3 : add hostvars directly into ` ` - - list ` ` output
inv_lists [ '_meta' ] = { 'hostvars' : self... |
def produce_frequency_explorer ( corpus , category , category_name = None , not_category_name = None , term_ranker = termranking . AbsoluteFrequencyRanker , alpha = 0.01 , use_term_significance = False , term_scorer = None , not_categories = None , grey_threshold = 1.96 , y_axis_values = None , frequency_transform = la... | if not_categories is None :
not_categories = [ c for c in corpus . get_categories ( ) if c != category ]
if term_scorer is None :
term_scorer = LogOddsRatioUninformativeDirichletPrior ( alpha )
my_term_ranker = term_ranker ( corpus )
if kwargs . get ( 'use_non_text_features' , False ) :
my_term_ranker . use... |
def enable_static_ip_config ( self , ip_address , network_mask ) :
"""sets and enables the static IP V4 configuration for the given interface .
in ip _ address of type str
IP address .
in network _ mask of type str
network mask .""" | if not isinstance ( ip_address , basestring ) :
raise TypeError ( "ip_address can only be an instance of type basestring" )
if not isinstance ( network_mask , basestring ) :
raise TypeError ( "network_mask can only be an instance of type basestring" )
self . _call ( "enableStaticIPConfig" , in_p = [ ip_address ... |
def make_plus_fields ( obj ) :
"""Add a ' + ' to the key of non - standard fields .
dispatch to recursive _ make _ plus _ helper based on _ type field""" | fields = standard_fields . get ( obj [ '_type' ] , dict ( ) )
return _make_plus_helper ( obj , fields ) |
def as_dataframe ( self , pattern = '*' , max_rows = None ) :
"""Creates a pandas dataframe from the groups that match the filters .
Args :
pattern : An optional pattern to further filter the groups . This can
include Unix shell - style wildcards . E . g . ` ` " Production * " ` ` ,
` ` " * - backend " ` ` ... | data = [ ]
for i , group in enumerate ( self . list ( pattern ) ) :
if max_rows is not None and i >= max_rows :
break
parent = self . _group_dict . get ( group . parent_id )
parent_display_name = '' if parent is None else parent . display_name
data . append ( [ group . id , group . display_name ... |
def p40baro ( msg ) :
"""Barometric pressure setting
Args :
msg ( String ) : 28 bytes hexadecimal message ( BDS40 ) string
Returns :
float : pressure in millibar""" | d = hex2bin ( data ( msg ) )
if d [ 26 ] == '0' :
return None
p = bin2int ( d [ 27 : 39 ] ) * 0.1 + 800
# millibar
return p |
def _update_alpha ( self , event = None ) :
"""Update display after a change in the alpha spinbox .""" | a = self . alpha . get ( )
hexa = self . hexa . get ( )
hexa = hexa [ : 7 ] + ( "%2.2x" % a ) . upper ( )
self . hexa . delete ( 0 , 'end' )
self . hexa . insert ( 0 , hexa )
self . alphabar . set ( a )
self . _update_preview ( ) |
def generate_data_key ( key_id , encryption_context = None , number_of_bytes = None , key_spec = None , grant_tokens = None , region = None , key = None , keyid = None , profile = None ) :
'''Generate a secure data key .
CLI example : :
salt myminion boto _ kms . generate _ data _ key ' alias / mykey ' number _... | conn = _get_conn ( region = region , key = key , keyid = keyid , profile = profile )
r = { }
try :
data_key = conn . generate_data_key ( key_id , encryption_context = encryption_context , number_of_bytes = number_of_bytes , key_spec = key_spec , grant_tokens = grant_tokens )
r [ 'data_key' ] = data_key
except b... |
def update_items ( portal_type = None , uid = None , endpoint = None , ** kw ) :
"""update items
1 . If the uid is given , the user wants to update the object with the data
given in request body
2 . If no uid is given , the user wants to update a bunch of objects .
- > each record contains either an UID , p... | # disable CSRF
req . disable_csrf_protection ( )
# the data to update
records = req . get_request_data ( )
# we have an uid - > try to get an object for it
obj = get_object_by_uid ( uid )
if obj :
record = records [ 0 ]
# ignore other records if we got an uid
obj = update_object_with_data ( obj , record )
... |
def create ( self , metadata , publisher_account , service_descriptors = None , providers = None , use_secret_store = True ) :
"""Register an asset in both the keeper ' s DIDRegistry ( on - chain ) and in the Metadata store (
Aquarius ) .
: param metadata : dict conforming to the Metadata accepted by Ocean Prot... | assert isinstance ( metadata , dict ) , f'Expected metadata of type dict, got {type(metadata)}'
if not metadata or not Metadata . validate ( metadata ) :
raise OceanInvalidMetadata ( 'Metadata seems invalid. Please make sure' ' the required metadata values are filled in.' )
# copy metadata so we don ' t change the ... |
def metadata ( self , key = None , database = None , table = None , fallback = True ) :
"""Looks up metadata , cascading backwards from specified level .
Returns None if metadata value is not found .""" | assert not ( database is None and table is not None ) , "Cannot call metadata() with table= specified but not database="
databases = self . _metadata . get ( "databases" ) or { }
search_list = [ ]
if database is not None :
search_list . append ( databases . get ( database ) or { } )
if table is not None :
table... |
def _shape_union ( shapes ) :
"""A shape containing the union of all dimensions in the input shapes .
Args :
shapes : a list of Shapes
Returns :
a Shape""" | return Shape ( sorted ( list ( set ( sum ( [ s . dims for s in shapes ] , [ ] ) ) ) ) ) |
def dn_cn_of_certificate_with_san ( domain ) :
'''Return the Common Name ( cn ) from the Distinguished Name ( dn ) of the
certificate which contains the ` domain ` in its Subject Alternativ Name ( san )
list .
Needs repo ~ / . fabsetup - custom .
Return None if no certificate is configured with ` domain ` i... | cn_dn = None
from config import domain_groups
cns = [ domains [ 0 ] for domains in domain_groups if domain in domains ]
if cns :
if len ( cns ) > 1 :
print_msg ( yellow ( flo ( 'Several certificates are configured to ' 'contain {domain} ' '(You should clean-up your config.py)\n' ) ) )
cn_dn = cns [ 0 ]
... |
def reference ( language , word ) :
'''Returns the articles ( singular and plural ) combined with singular and plural for a given noun .''' | sg , pl , art = word , '/' . join ( plural ( language , word ) or [ '-' ] ) , [ [ '' ] , [ '' ] ]
art [ 0 ] , art [ 1 ] = articles ( language , word ) or ( [ '-' ] , [ '-' ] )
result = [ '%s %s' % ( '/' . join ( art [ 0 ] ) , sg ) , '%s %s' % ( '/' . join ( art [ 1 ] ) , pl ) ]
result = [ None if x == '- -' else x for ... |
def minimise_xyz ( xyz ) :
"""Minimise an ( x , y , z ) coordinate .""" | x , y , z = xyz
m = max ( min ( x , y ) , min ( max ( x , y ) , z ) )
return ( x - m , y - m , z - m ) |
def build ( self , builder ) :
"""Build XML by appending to builder""" | params = dict ( LabelOID = self . oid , OrderNumber = str ( self . order_number ) )
builder . start ( "mdsol:LabelRef" , params )
builder . end ( "mdsol:LabelRef" ) |
def is_wrapped_arg ( self , * args , ** kwargs ) :
"""decide if this decorator was called with arguments ( eg , @ dec ( . . . ) ) or
without ( eg , @ dec ) so we can take the correct path when the decorator is
invoked
for the most part this works except for the case where you have one callback
or class as t... | ret = False
if len ( args ) == 1 and len ( kwargs ) == 0 : # pout . v ( args , self , isinstance ( args [ 0 ] , type ) , isinstance ( args [ 0 ] , FuncDecorator ) )
ret = inspect . isfunction ( args [ 0 ] ) or isinstance ( args [ 0 ] , type ) or isinstance ( args [ 0 ] , Decorator )
if ret :
ret = not s... |
def read_same_samples_file ( filename , out_prefix ) :
"""Reads a file containing same samples .""" | # The same samples
same_samples = [ ]
# Creating the extraction files
gold_file = None
try :
gold_file = open ( out_prefix + ".gold_samples2keep" , 'w' )
except IOError :
msg = "{}: can't create file" . format ( out_prefix + ".gold_samples2keep" )
raise ProgramError ( msg )
source_file = None
try :
sour... |
def provision ( self , instance_id : str , service_details : ProvisionDetails , async_allowed : bool ) -> ProvisionedServiceSpec :
"""Further readings ` CF Broker API # Provisioning < https : / / docs . cloudfoundry . org / services / api . html # provisioning > ` _
: param instance _ id : Instance id provided by... | raise NotImplementedError ( ) |
def _ProcessGrepSource ( self , source ) :
"""Find files fulfilling regex conditions .""" | attributes = source . base_source . attributes
paths = artifact_utils . InterpolateListKbAttributes ( attributes [ "paths" ] , self . knowledge_base , self . ignore_interpolation_errors )
regex = utils . RegexListDisjunction ( attributes [ "content_regex_list" ] )
condition = rdf_file_finder . FileFinderCondition . Con... |
def atlasdb_remove_peer ( peer_hostport , con = None , path = None , peer_table = None ) :
"""Remove a peer from the peer db and ( if given ) peer table .""" | # remove from db
with AtlasDBOpen ( con = con , path = path ) as dbcon :
log . debug ( "Delete peer '%s'" % peer_hostport )
sql = "DELETE FROM peers WHERE peer_hostport = ?;"
args = ( peer_hostport , )
cur = dbcon . cursor ( )
res = atlasdb_query_execute ( cur , sql , args )
dbcon . commit ( )
#... |
def is_bored_of ( self , board ) :
"""Return whether the simulation is probably in a loop .
This is a stochastic guess . Basically , it detects whether the
simulation has had the same number of cells a lot lately . May have
false positives ( like if you just have a screen full of gliders ) or
take awhile to... | self . iteration += 1
if len ( board ) == self . num :
self . times += 1
is_bored = self . times > self . REPETITIONS
if self . iteration > self . REPETITIONS * self . PATTERN_LENGTH or is_bored : # A little randomness in case things divide evenly into each other :
self . iteration = randint ( - 2 , 0 )
sel... |
def schedule_entities_reindex ( entities ) :
""": param entities : as returned by : func : ` get _ entities _ for _ reindex `""" | entities = [ ( e [ 0 ] , e [ 1 ] , e [ 2 ] , dict ( e [ 3 ] ) ) for e in entities ]
return index_update . apply_async ( kwargs = { "index" : "default" , "items" : entities } ) |
def get_lr_scheduler ( learning_rate , lr_refactor_step , lr_refactor_ratio , num_example , batch_size , begin_epoch ) :
"""Compute learning rate and refactor scheduler
Parameters :
learning _ rate : float
original learning rate
lr _ refactor _ step : comma separated str
epochs to change learning rate
l... | assert lr_refactor_ratio > 0
iter_refactor = [ int ( r ) for r in lr_refactor_step . split ( ',' ) if r . strip ( ) ]
if lr_refactor_ratio >= 1 :
return ( learning_rate , None )
else :
lr = learning_rate
epoch_size = num_example // batch_size
for s in iter_refactor :
if begin_epoch >= s :
... |
def _to_dict ( self ) :
"""Return a json dictionary representing this model .""" | _dict = { }
if hasattr ( self , 'feedback_id' ) and self . feedback_id is not None :
_dict [ 'feedback_id' ] = self . feedback_id
if hasattr ( self , 'user_id' ) and self . user_id is not None :
_dict [ 'user_id' ] = self . user_id
if hasattr ( self , 'comment' ) and self . comment is not None :
_dict [ 'co... |
def allowed_error_messages ( * error_messages ) :
"""Decorator ignoring defined error messages at the end of test method . As
param use what
: py : meth : ` ~ . WebdriverWrapperErrorMixin . get _ error _ messages `
returns .
. . versionadded : : 2.0
Before this decorator was called ` ` CanBeError ` ` .""" | def wrapper ( func ) :
setattr ( func , ALLOWED_ERROR_MESSAGES , error_messages )
return func
return wrapper |
def rename ( args ) :
"""% prog rename in . gff3 switch . ids > reindexed . gff3
Change the IDs within the gff3.""" | p = OptionParser ( rename . __doc__ )
opts , args = p . parse_args ( args )
if len ( args ) != 2 :
sys . exit ( not p . print_help ( ) )
ingff3 , switch = args
switch = DictFile ( switch )
gff = Gff ( ingff3 )
for g in gff :
id , = g . attributes [ "ID" ]
newname = switch . get ( id , id )
g . attribute... |
def append ( self , other ) :
"""Append a collection of Index options together
Parameters
other : Index or list / tuple of indices
Returns
appended : Index""" | if not isinstance ( other , ( list , tuple ) ) :
other = [ other ]
if all ( ( isinstance ( o , MultiIndex ) and o . nlevels >= self . nlevels ) for o in other ) :
arrays = [ ]
for i in range ( self . nlevels ) :
label = self . _get_level_values ( i )
appended = [ o . _get_level_values ( i ) ... |
def start ( self ) :
'''Start the actual master .
If sub - classed , don ' t * * ever * * forget to run :
super ( YourSubClass , self ) . start ( )
NOTE : Run any required code before calling ` super ( ) ` .''' | super ( SaltAPI , self ) . start ( )
if check_user ( self . config [ 'user' ] ) :
log . info ( 'The salt-api is starting up' )
self . api . run ( ) |
def receive ( cfg , code , ** kwargs ) :
"""Receive a text message , file , or directory ( from ' wormhole send ' )""" | for name , value in kwargs . items ( ) :
setattr ( cfg , name , value )
with cfg . timing . add ( "import" , which = "cmd_receive" ) :
from . import cmd_receive
if len ( code ) == 1 :
cfg . code = code [ 0 ]
elif len ( code ) > 1 :
print ( "Pass either no code or just one code; you passed" " {}: {}" . f... |
def _on_enter ( self , event ) :
"""Creates a delayed callback for the : obj : ` < Enter > ` event .""" | self . _id = self . master . after ( int ( self . _timeout * 1000 ) , func = self . show ) |
def get_default_config ( self ) :
"""Returns the default collector settings""" | config = super ( SoftInterruptCollector , self ) . get_default_config ( )
config . update ( { 'path' : 'softirq' } )
return config |
def is_valid_code ( self , code ) :
""": param code : a string stock code
: return : Boolean""" | if code :
stock_codes = self . get_stock_codes ( )
if code . upper ( ) in stock_codes . keys ( ) :
return True
else :
return False |
def deleteRating ( self ) :
"""Removes the rating the calling user added for the specified item
( POST only ) .""" | url = "%s/deleteRating" % self . root
params = { "f" : "json" , }
return self . _post ( url , params , securityHandler = self . _securityHandler , proxy_port = self . _proxy_port , proxy_url = self . _proxy_url ) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.