signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def bulk_log ( self , log_message = u"Еще одна пачка обработана" , total = None , part_log_time_minutes = 5 ) :
"""Возвращает инстант логгера для обработки списокв данных
: param log _ message : То , что будет написано , когда время придет
: param total : Общее кол - во объектов , если вы знаете его
: param p... | return BulkLogger ( log = self . log , log_message = log_message , total = total , part_log_time_minutes = part_log_time_minutes ) |
def parse ( self , fd ) :
"""very simple parser - but why would we want it to be complex ?""" | def resolve_args ( args ) : # FIXME break this out , it ' s in common with the templating stuff elsewhere
root = self . sections [ 0 ]
val_dict = dict ( ( '<' + t + '>' , u ) for ( t , u ) in root . get_variables ( ) . items ( ) )
resolved_args = [ ]
for arg in args :
for subst , value in val_di... |
def flags ( self ) :
"""Return set of flags .""" | return set ( ( name . lower ( ) for name in sorted ( TIFF . FILE_FLAGS ) if getattr ( self , 'is_' + name ) ) ) |
def addToLayout ( self , analysis , position = None ) :
"""Adds the analysis passed in to the worksheet ' s layout""" | # TODO Redux
layout = self . getLayout ( )
container_uid = self . get_container_for ( analysis )
if IRequestAnalysis . providedBy ( analysis ) and not IDuplicateAnalysis . providedBy ( analysis ) :
container_uids = map ( lambda slot : slot [ 'container_uid' ] , layout )
if container_uid in container_uids :
... |
def visit ( folder , provenance_id , step_name , previous_step_id = None , config = None , db_url = None , is_organised = True ) :
"""Record all files from a folder into the database .
Note :
If a file has been copied from a previous processing step without any transformation , it will be detected and
marked ... | config = config if config else [ ]
logging . info ( "Visiting %s" , folder )
logging . info ( "-> is_organised=%s" , str ( is_organised ) )
logging . info ( "-> config=%s" , str ( config ) )
logging . info ( "Connecting to database..." )
db_conn = connection . Connection ( db_url )
step_id = _create_step ( db_conn , st... |
def add ( self , child ) :
"""Adds a typed child object to the event handler .
@ param child : Child object to be added .""" | if isinstance ( child , Action ) :
self . add_action ( child )
else :
raise ModelError ( 'Unsupported child element' ) |
def flash_file ( self , path , addr , on_progress = None , power_on = False ) :
"""Flashes the target device .
The given ` ` on _ progress ` ` callback will be called as
` ` on _ progress ( action , progress _ string , percentage ) ` ` periodically as the
data is written to flash . The action is one of ` ` Co... | if on_progress is not None : # Set the function to be called on flash programming progress .
func = enums . JLinkFunctions . FLASH_PROGRESS_PROTOTYPE ( on_progress )
self . _dll . JLINK_SetFlashProgProgressCallback ( func )
else :
self . _dll . JLINK_SetFlashProgProgressCallback ( 0 )
# First power on the d... |
def start ( self , channel ) :
"""Start running this virtual device including any necessary worker threads .
Args :
channel ( IOTilePushChannel ) : the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface""" | super ( TileBasedVirtualDevice , self ) . start ( channel )
for tile in self . _tiles . values ( ) :
tile . start ( channel = channel ) |
def Read ( self , expected_ids , read_data = True ) :
"""Read ADB messages and return FileSync packets .""" | if self . send_idx :
self . _Flush ( )
# Read one filesync packet off the recv buffer .
header_data = self . _ReadBuffered ( self . recv_header_len )
header = struct . unpack ( self . recv_header_format , header_data )
# Header is ( ID , . . . ) .
command_id = self . wire_to_id [ header [ 0 ] ]
if command_id not in... |
def _sig_handler ( self , signum , stack ) :
'''Handle process INT signal .''' | log_debug ( "Got SIGINT." )
if signum == signal . SIGINT :
LLNetReal . running = False
if self . _pktqueue . qsize ( ) == 0 : # put dummy pkt in queue to unblock a
# possibly stuck user thread
self . _pktqueue . put ( ( None , None , None ) ) |
def parse ( self , inputstring , parser , preargs , postargs ) :
"""Use the parser to parse the inputstring with appropriate setup and teardown .""" | self . reset ( )
pre_procd = None
with logger . gather_parsing_stats ( ) :
try :
pre_procd = self . pre ( inputstring , ** preargs )
parsed = parse ( parser , pre_procd )
out = self . post ( parsed , ** postargs )
except ParseBaseException as err :
raise self . make_parse_err ( e... |
def create_main_frame ( self ) :
self . resize ( 800 , 1000 )
self . main_frame = QWidget ( )
self . dpi = 128
self . fig = Figure ( ( 12 , 11 ) , dpi = self . dpi )
self . fig . subplots_adjust ( hspace = 0.5 , wspace = 0.5 , left = 0.1 , bottom = 0.2 , right = 0.7 , top = 0.9 )
# 8 * np . sqrt... | self . detail_cb = QCheckBox ( '&Detail' )
self . detail_cb . setChecked ( True )
self . detail_cb . stateChanged . connect ( self . QAPF )
# int
# Layout with box sizers
self . hbox = QHBoxLayout ( )
for w in [ self . save_button , self . detail_cb , self . legend_cb , self . slider_left_label , self . slider , self .... |
def get ( self ) :
"""Return sbo arch""" | if self . arch . startswith ( "i" ) and self . arch . endswith ( "86" ) :
self . arch = self . x86
elif self . meta . arch . startswith ( "arm" ) :
self . arch = self . arm
return self . arch |
def _drawContents ( self , currentRti = None ) :
"""Draws the attributes of the currentRTI""" | # logger . debug ( " _ drawContents : { } " . format ( currentRti ) )
table = self . table
table . setUpdatesEnabled ( False )
try :
table . clearContents ( )
verticalHeader = table . verticalHeader ( )
verticalHeader . setSectionResizeMode ( QtWidgets . QHeaderView . Fixed )
attributes = currentRti . a... |
def get_package_from_string ( txt , paths = None ) :
"""Get a package given a string .
Args :
txt ( str ) : String such as ' foo ' , ' bah - 1.3 ' .
paths ( list of str , optional ) : paths to search for package , defaults
to ` config . packages _ path ` .
Returns :
` Package ` instance , or None if no ... | o = VersionedObject ( txt )
return get_package ( o . name , o . version , paths = paths ) |
def label_from_instance ( self , obj ) :
"""Creates labels which represent the tree level of each node when
generating option labels .""" | level = getattr ( obj , obj . _mptt_meta . level_attr )
level_indicator = mark_safe ( conditional_escape ( self . level_indicator ) * level )
return mark_safe ( u'%s %s' % ( level_indicator , conditional_escape ( smart_unicode ( obj ) ) ) ) |
def do_help ( self , arg ) :
"""Sets up the header for the help command that explains the background on how to use
the script generally . Help for each command then stands alone in the context of this
documentation . Although we could have documented this on the wiki , it is better served
when shipped with th... | if arg == "" :
lines = [ ( "The fortpy unit testing analysis shell makes it easy to analyze the results " "of multiple test cases, make plots of trends and tabulate values for use in " "other applications. This documentation will provide an overview of the basics. " "Use 'help <command>' to get specific command hel... |
def _getSensorLimits ( self ) :
"""Returns a list of 2 - tuples , e . g . [ ( - 3.14 , 3.14 ) , ( - 0.001 , 0.001 ) ] ,
one tuple per parameter , giving min and max for that parameter .""" | limits = [ ]
limits . extend ( self . _getTotalDemandLimits ( ) )
# limits . extend ( self . _ getDemandLimits ( ) )
# limits . extend ( self . _ getPriceLimits ( ) )
# limits . extend ( self . _ getVoltageSensorLimits ( ) )
# limits . extend ( self . _ getVoltageMagnitudeLimits ( ) )
# limits . extend ( self . _ getVo... |
def get_trace ( self , reference = None ) :
"""Returns a generator of parents up to : reference : , including reference
If : reference : is * None * root is assumed
Closest ancestor goes first""" | item = self
while item :
yield item
if item == reference :
return
item = item . parent
if reference is not None :
raise Exception ( 'Reference {} is not in Ancestry' . format ( reference ) ) |
def open_file ( self , fname , length = None , offset = None , swap = None , block = None , peek = None ) :
'''Opens the specified file with all pertinent configuration settings .''' | if length is None :
length = self . length
if offset is None :
offset = self . offset
if swap is None :
swap = self . swap_size
return binwalk . core . common . BlockFile ( fname , subclass = self . subclass , length = length , offset = offset , swap = swap , block = block , peek = peek ) |
def generate_public_key ( self ) :
"""Generates a public key from the hex - encoded private key using elliptic
curve cryptography . The private key is multiplied by a predetermined point
on the elliptic curve called the generator point , G , resulting in the
corresponding private key . The generator point is ... | private_key = int ( self . private_key , 16 )
if private_key >= self . N :
raise Exception ( 'Invalid private key.' )
G = JacobianPoint ( self . Gx , self . Gy , 1 )
public_key = G * private_key
x_hex = '{0:0{1}x}' . format ( public_key . X , 64 )
y_hex = '{0:0{1}x}' . format ( public_key . Y , 64 )
return '04' + x... |
def createSummaryFile ( results , maf , prefix ) :
"""Creat the final summary file containing plate bias results .
: param results : the list of all the significant results .
: param maf : the minor allele frequency of the significant results .
: param prefix : the prefix of all the files .
: type results :... | o_filename = prefix + ".significant_SNPs.summary"
try :
with open ( o_filename , "w" ) as o_file :
print >> o_file , "\t" . join ( ( "chrom" , "pos" , "name" , "maf" , "p" , "odds" , "plate" ) )
for row in results :
print >> o_file , "\t" . join ( ( row . chrom , row . pos , row . name ,... |
def count_comments_handler ( sender , ** kwargs ) :
"""Update Entry . comment _ count when a public comment was posted .""" | comment = kwargs [ 'comment' ]
if comment . is_public :
entry = comment . content_object
if isinstance ( entry , Entry ) :
entry . comment_count = F ( 'comment_count' ) + 1
entry . save ( update_fields = [ 'comment_count' ] ) |
def requestBusName ( self , newName , allowReplacement = False , replaceExisting = False , doNotQueue = True , errbackUnlessAcquired = True ) :
"""Calls org . freedesktop . DBus . RequestName to request that the specified
bus name be associated with the connection .
@ type newName : C { string }
@ param newNa... | flags = 0
if allowReplacement :
flags |= 0x1
if replaceExisting :
flags |= 0x2
if doNotQueue :
flags |= 0x4
d = self . callRemote ( '/org/freedesktop/DBus' , 'RequestName' , interface = 'org.freedesktop.DBus' , signature = 'su' , body = [ newName , flags ] , destination = 'org.freedesktop.DBus' , )
def on_r... |
def _init_map ( self ) :
"""stub""" | super ( SimpleDifficultyItemFormRecord , self ) . _init_map ( )
self . my_osid_object_form . _my_map [ 'texts' ] [ 'difficulty' ] = self . _difficulty_metadata [ 'default_string_values' ] [ 0 ] |
def filter_index ( collection , predicate = None , index = None ) :
"""Filter collection with predicate function and index .
If index is not found , returns None .
: param collection :
: type collection : collection supporting iteration and slicing
: param predicate : function to filter the collection with ... | if index is None and isinstance ( predicate , int ) :
index = predicate
predicate = None
if predicate :
collection = collection . __class__ ( filter ( predicate , collection ) )
if index is not None :
try :
collection = collection [ index ]
except IndexError :
collection = None
retur... |
def asBinary ( self ) :
"""Get | ASN . 1 | value as a text string of bits .""" | binString = binary . bin ( self . _value ) [ 2 : ]
return '0' * ( len ( self . _value ) - len ( binString ) ) + binString |
def quit ( self ) :
"""This could be called from another thread , so let ' s do this via alarm""" | def q ( * args ) :
raise urwid . ExitMainLoop ( )
self . worker . shutdown ( wait = False )
self . ui_worker . shutdown ( wait = False )
self . loop . set_alarm_in ( 0 , q ) |
def interface_ip ( interface ) :
"""Determine the IP assigned to us by the given network interface .""" | sock = socket . socket ( socket . AF_INET , socket . SOCK_DGRAM )
return socket . inet_ntoa ( fcntl . ioctl ( sock . fileno ( ) , 0x8915 , struct . pack ( '256s' , interface [ : 15 ] ) ) [ 20 : 24 ] ) |
def hexists ( self , name , key ) :
"""Returns ` ` True ` ` if the field exists , ` ` False ` ` otherwise .
: param name : str the name of the redis key
: param key : the member of the hash
: return : Future ( )""" | with self . pipe as pipe :
return pipe . hexists ( self . redis_key ( name ) , self . memberparse . encode ( key ) ) |
def send_request ( self , * args , ** kwargs ) :
"""Intercept connection errors which suggest that a managed host has
crashed and raise an exception indicating the location of the log""" | try :
return super ( JSHost , self ) . send_request ( * args , ** kwargs )
except RequestsConnectionError as e :
if ( self . manager and self . has_connected and self . logfile and 'unsafe' not in kwargs ) :
raise ProcessError ( '{} appears to have crashed, you can inspect the log file at {}' . format (... |
def start ( name , call = None ) :
'''Start a node
CLI Examples :
. . code - block : : bash
salt - cloud - a start myinstance''' | if call != 'action' :
raise SaltCloudSystemExit ( 'The stop action must be called with -a or --action.' )
log . info ( 'Starting node %s' , name )
instanceId = _get_node ( name ) [ 'InstanceId' ]
params = { 'Action' : 'StartInstance' , 'InstanceId' : instanceId }
result = query ( params )
return result |
def _dateversion ( self ) : # type : ( ) - > int
"""Return the build / revision date as an integer " yyyymmdd " .""" | import re
if self . _head :
ma = re . search ( r'(?<=\()(.*)(?=\))' , self . _head )
if ma :
s = re . split ( r'[, ]+' , ma . group ( 0 ) )
if len ( s ) >= 3 : # month
month_names = ( 'Jan' , 'Feb' , 'Mar' , 'Apr' , 'May' , 'Jun' , 'Jul' , 'Aug' , 'Sep' , 'Oct' , 'Nov' , 'Dec' )
... |
def merge_mhc_peptide_calls ( job , antigen_predictions , transgened_files , univ_options ) :
"""Merge all the calls generated by spawn _ antigen _ predictors .
: param dict antigen _ predictions : The return value from running : meth : ` spawn _ antigen _ predictors `
: param dict transgened _ files : The tran... | job . fileStore . logToMaster ( 'Merging MHC calls' )
work_dir = os . getcwd ( )
pept_files = { '10_mer.faa' : transgened_files [ 'transgened_tumor_10_mer_peptides.faa' ] , '10_mer.faa.map' : transgened_files [ 'transgened_tumor_10_mer_peptides.faa.map' ] , '15_mer.faa' : transgened_files [ 'transgened_tumor_15_mer_pep... |
def on_connect ( client ) :
"""Sample on _ connect function .
Handles new connections .""" | print "++ Opened connection to %s" % client . addrport ( )
broadcast ( '%s joins the conversation.\n' % client . addrport ( ) )
CLIENT_LIST . append ( client )
client . send ( "Welcome to the Chat Server, %s.\n" % client . addrport ( ) ) |
def delete ( access_key ) :
"""Delete an existing keypair .
ACCESSKEY : ACCESSKEY for a keypair to delete .""" | with Session ( ) as session :
try :
data = session . KeyPair . delete ( access_key )
except Exception as e :
print_error ( e )
sys . exit ( 1 )
if not data [ 'ok' ] :
print_fail ( 'KeyPair deletion has failed: {0}' . format ( data [ 'msg' ] ) )
sys . exit ( 1 )
pr... |
def _dump_json ( self , data , new_line = False ) :
"""Helper function to marshal object into JSON string .
Additionally a sha256sum of the created JSON string is generated .""" | # We do not want any spaces between keys and values in JSON
json_data = json . dumps ( data , separators = ( ',' , ':' ) )
if new_line :
json_data = "%s\n" % json_data
# Generate sha256sum of the JSON data , may be handy
sha = hashlib . sha256 ( json_data . encode ( 'utf-8' ) ) . hexdigest ( )
return json_data , sh... |
def build ( self , tokenlist ) :
"""Build a Wikicode object from a list tokens and return it .""" | self . _tokens = tokenlist
self . _tokens . reverse ( )
self . _push ( )
while self . _tokens :
node = self . _handle_token ( self . _tokens . pop ( ) )
self . _write ( node )
return self . _pop ( ) |
def share_application_with_accounts ( application_id , account_ids , sar_client = None ) :
"""Share the application privately with given AWS account IDs .
: param application _ id : The Amazon Resource Name ( ARN ) of the application
: type application _ id : str
: param account _ ids : List of AWS account ID... | if not application_id or not account_ids :
raise ValueError ( 'Require application id and list of AWS account IDs to share the app' )
if not sar_client :
sar_client = boto3 . client ( 'serverlessrepo' )
application_policy = ApplicationPolicy ( account_ids , [ ApplicationPolicy . DEPLOY ] )
application_policy . ... |
def RY ( angle , qubit ) :
"""Produces the RY gate : :
RY ( phi ) = [ [ cos ( phi / 2 ) , - sin ( phi / 2 ) ] ,
[ sin ( phi / 2 ) , cos ( phi / 2 ) ] ]
This gate is a single qubit Y - rotation .
: param angle : The angle to rotate around the y - axis on the bloch sphere .
: param qubit : The qubit apply t... | return Gate ( name = "RY" , params = [ angle ] , qubits = [ unpack_qubit ( qubit ) ] ) |
def set_state ( self , site , timestamp = None ) :
"""Write status dict to client status file .
FIXME - should have some file lock to avoid race""" | parser = ConfigParser ( )
parser . read ( self . status_file )
status_section = 'incremental'
if ( not parser . has_section ( status_section ) ) :
parser . add_section ( status_section )
if ( timestamp is None ) :
parser . remove_option ( status_section , self . config_site_to_name ( site ) )
else :
parser ... |
def _guess_type_from_validator ( validator ) :
"""Utility method to return the declared type of an attribute or None . It handles _ OptionalValidator and _ AndValidator
in order to unpack the validators .
: param validator :
: return : the type of attribute declared in an inner ' instance _ of ' validator ( i... | if isinstance ( validator , _OptionalValidator ) : # Optional : look inside
return _guess_type_from_validator ( validator . validator )
elif isinstance ( validator , _AndValidator ) : # Sequence : try each of them
for v in validator . validators :
typ = _guess_type_from_validator ( v )
if typ is... |
def _accumulate ( data_list , no_concat = ( ) ) :
"""Concatenate a list of dicts ` ( name , array ) ` .
You can specify some names which arrays should not be concatenated .
This is necessary with lists of plots with different sizes .""" | acc = Accumulator ( )
for data in data_list :
for name , val in data . items ( ) :
acc . add ( name , val )
out = { name : acc [ name ] for name in acc . names if name not in no_concat }
# Some variables should not be concatenated but should be kept as lists .
# This is when there can be several arrays of v... |
def func_args_as_dict ( func , args , kwargs ) :
"""Return given function ' s positional and key value arguments as an ordered
dictionary .""" | if six . PY2 :
_getargspec = inspect . getargspec
else :
_getargspec = inspect . getfullargspec
arg_names = list ( OrderedDict . fromkeys ( itertools . chain ( _getargspec ( func ) [ 0 ] , kwargs . keys ( ) ) ) )
return OrderedDict ( list ( six . moves . zip ( arg_names , args ) ) + list ( kwargs . items ( ) ) ... |
def set_order ( self , order ) :
"""Takes a list of dictionaries . Those correspond to the arguments of
` list . sort ` and must contain the keys ' key ' and ' reverse ' ( a boolean ) .
You must call ` set _ labels ` before this !""" | m = gtk . ListStore ( bool , str )
for item in order :
m . append ( ( item [ 'reverse' ] , item [ 'key' ] ) )
# TODO fill with _ _ labels missing in order .
self . set_model ( m ) |
def _resize ( self , shape , format = None , internalformat = None ) :
"""Internal method for resize .""" | shape = self . _normalize_shape ( shape )
# Check
if not self . _resizable :
raise RuntimeError ( "Texture is not resizable" )
# Determine format
if format is None :
format = self . _formats [ shape [ - 1 ] ]
# Keep current format if channels match
if self . _format and self . _inv_formats [ self . _for... |
def pca ( data : Union [ AnnData , np . ndarray , spmatrix ] , n_comps : int = N_PCS , zero_center : Optional [ bool ] = True , svd_solver : str = 'auto' , random_state : int = 0 , return_info : bool = False , use_highly_variable : Optional [ bool ] = None , dtype : str = 'float32' , copy : bool = False , chunked : boo... | # chunked calculation is not randomized , anyways
if svd_solver in { 'auto' , 'randomized' } and not chunked :
logg . info ( 'Note that scikit-learn\'s randomized PCA might not be exactly ' 'reproducible across different computational platforms. For exact ' 'reproducibility, choose `svd_solver=\'arpack\'.` This wil... |
def _BuildUrl ( self , url , path_elements = None , extra_params = None ) :
"""Taken from : https : / / github . com / bear / python - twitter / blob / master / twitter / api . py # L3814 - L3836
: param url :
: param path _ elements :
: param extra _ params :
: return :""" | # Break url into constituent parts
( scheme , netloc , path , params , query , fragment ) = urlparse ( url )
# Add any additional path elements to the path
if path_elements : # Filter out the path elements that have a value of None
p = [ i for i in path_elements if i ]
if not path . endswith ( '/' ) :
p... |
def fill_tree_from_xml ( tag , ar_tree , namespace ) : # type : ( _ Element , ArTree , str ) - > None
"""Parse the xml tree into ArTree objects .""" | for child in tag : # type : _ Element
name_elem = child . find ( './' + namespace + 'SHORT-NAME' )
# long _ name = child . find ( ' . / ' + namespace + ' LONG - NAME ' )
if name_elem is not None and child is not None :
fill_tree_from_xml ( child , ar_tree . append_child ( name_elem . text , child ) ... |
def filter_transcription_factor ( stmts_in , ** kwargs ) :
"""Filter out RegulateAmounts where subject is not a transcription factor .
Parameters
stmts _ in : list [ indra . statements . Statement ]
A list of statements to filter .
save : Optional [ str ]
The name of a pickle file to save the results ( st... | logger . info ( 'Filtering %d statements to remove ' % len ( stmts_in ) + 'amount regulations by non-transcription-factors...' )
path = os . path . dirname ( os . path . abspath ( __file__ ) )
tf_table = read_unicode_csv ( path + '/../resources/transcription_factors.csv' )
gene_names = [ lin [ 1 ] for lin in list ( tf_... |
def fix_line_range ( source_code , start , end , options ) :
"""Apply autopep8 ( and docformatter ) between the lines start and end of
source .""" | # TODO confirm behaviour outside range ( indexing starts at 1)
start = max ( start , 1 )
options . line_range = [ start , end ]
from autopep8 import fix_code
fixed = fix_code ( source_code , options )
try :
if options . docformatter :
from docformatter import format_code
fixed = format_code ( fixed ... |
def create ( self ) :
"""Launches a new server instance .""" | self . server_attrs = self . consul . create_server ( "%s-%s" % ( self . stack . name , self . name ) , self . disk_image_id , self . instance_type , self . ssh_key_name , tags = self . tags , availability_zone = self . availability_zone , timeout_s = self . launch_timeout_s , security_groups = self . security_groups ,... |
def plotE ( self , * args , ** kwargs ) :
"""NAME :
plotE
PURPOSE :
plot E ( . ) along the orbit
INPUT :
pot = Potential instance or list of instances in which the orbit was integrated
d1 = plot Ez vs d1 : e . g . , ' t ' , ' z ' , ' R ' , ' vR ' , ' vT ' , ' vz '
normed = if set , plot E ( t ) / E ( ... | if not kwargs . get ( 'pot' , None ) is None :
kwargs [ 'pot' ] = flatten_potential ( kwargs . get ( 'pot' ) )
return self . _orb . plotE ( * args , ** kwargs ) |
def _runcog ( options , files , uncog = False ) :
"""Common function for the cog and runcog tasks .""" | options . order ( 'cog' , 'sphinx' , add_rest = True )
c = Cog ( )
if uncog :
c . options . bNoGenerate = True
c . options . bReplace = True
c . options . bDeleteCode = options . get ( "delete_code" , False )
includedir = options . get ( 'includedir' , None )
if includedir :
include = Includer ( includedir , co... |
def iglob ( pathname , * , recursive = False ) :
"""Return an iterator which yields the paths matching a pathname pattern .
The pattern may contain simple shell - style wildcards a la
fnmatch . However , unlike fnmatch , filenames starting with a
dot are special cases that are not matched by ' * ' and ' ? '
... | it = _iglob ( pathname , recursive )
if recursive and _isrecursive ( pathname ) :
s = next ( it )
# skip empty string
assert not s
return it |
def _remove_redundancy_routers ( self , context , router_ids , ports , delete_ha_groups = False ) :
"""Deletes all interfaces of the specified redundancy routers
and then the redundancy routers themselves .""" | subnets_info = [ { 'subnet_id' : port [ 'fixed_ips' ] [ 0 ] [ 'subnet_id' ] } for port in ports ]
for r_id in router_ids :
for i in range ( len ( subnets_info ) ) :
self . remove_router_interface ( context , r_id , subnets_info [ i ] )
LOG . debug ( "Removed interface on %(s_id)s to redundancy route... |
def _load_resource ( self , source_r , abs_path = False ) :
"""The CSV package has no reseources , so we just need to resolve the URLs to them . Usually , the
CSV package is built from a file system ackage on a publically acessible server .""" | r = self . doc . resource ( source_r . name )
r . url = self . resource_root . join ( r . url ) . inner |
def tagcount ( sam , out , genemap , output_evidence_table , positional , minevidence , cb_histogram , cb_cutoff , no_scale_evidence , subsample , sparse , parse_tags , gene_tags ) :
'''Count up evidence for tagged molecules''' | from pysam import AlignmentFile
from io import StringIO
import pandas as pd
from utils import weigh_evidence
logger . info ( 'Reading optional files' )
gene_map = None
if genemap :
with open ( genemap ) as fh :
try :
gene_map = dict ( p . strip ( ) . split ( ) for p in fh )
except ValueE... |
def add_all ( self , items , overflow_policy = OVERFLOW_POLICY_OVERWRITE ) :
"""Adds all of the item in the specified collection to the tail of the Ringbuffer . An add _ all is likely to
outperform multiple calls to add ( object ) due to better io utilization and a reduced number of executed
operations . The it... | check_not_empty ( items , "items can't be empty" )
if len ( items ) > MAX_BATCH_SIZE :
raise AssertionError ( "Batch size can't be greater than %d" % MAX_BATCH_SIZE )
for item in items :
check_not_none ( item , "item can't be None" )
item_list = [ self . _to_data ( x ) for x in items ]
return self . _encode_inv... |
def print_table ( rows , override_headers = None , uppercase_headers = True ) :
"""All rows need to be a list of dictionaries , all with the same keys .""" | if len ( rows ) == 0 :
return
keys = list ( rows [ 0 ] . keys ( ) )
headers = override_headers or keys
if uppercase_headers :
rows = [ dict ( zip ( keys , map ( lambda x : x . upper ( ) , headers ) ) ) , None ] + rows
else :
rows = [ dict ( zip ( keys , headers ) ) , None ] + rows
lengths = [ max ( len ( st... |
def decrypt ( self , encrypted_wrapped_data_key , encryption_context ) :
"""Decrypts a wrapped , encrypted , data key .
: param encrypted _ wrapped _ data _ key : Encrypted , wrapped , data key
: type encrypted _ wrapped _ data _ key : aws _ encryption _ sdk . internal . structures . EncryptedData
: param dic... | if self . wrapping_key_type is EncryptionKeyType . PUBLIC :
raise IncorrectMasterKeyError ( "Public key cannot decrypt" )
if self . wrapping_key_type is EncryptionKeyType . PRIVATE :
return self . _wrapping_key . decrypt ( ciphertext = encrypted_wrapped_data_key . ciphertext , padding = self . wrapping_algorith... |
def requires ( self ) :
"""Index all pages .""" | for url in NEWSPAPERS :
yield IndexPage ( url = url , date = self . date ) |
def sniff_extension ( file_path , verbose = True ) :
'''sniff _ extension will attempt to determine the file type based on the extension ,
and return the proper mimetype
: param file _ path : the full path to the file to sniff
: param verbose : print stuff out''' | mime_types = { "xls" : 'application/vnd.ms-excel' , "xlsx" : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' , "xml" : 'text/xml' , "ods" : 'application/vnd.oasis.opendocument.spreadsheet' , "csv" : 'text/plain' , "tmpl" : 'text/plain' , "pdf" : 'application/pdf' , "php" : 'application/x-httpd-php' ... |
def update ( self ) :
"""Update layout to match the layout as described in the
WindowArrangement .""" | # Start with an empty frames list everytime , to avoid memory leaks .
existing_frames = self . _frames
self . _frames = { }
def create_layout_from_node ( node ) :
if isinstance ( node , window_arrangement . Window ) : # Create frame for Window , or reuse it , if we had one already .
key = ( node , node . ed... |
def is_absolute ( self ) :
"""Return True if xllcorner = = yllcorner = = 0 indicating that points
in question are absolute .""" | # FIXME ( Ole ) : It is unfortunate that decision about whether points
# are absolute or not lies with the georeference object . Ross pointed this out .
# Moreover , this little function is responsible for a large fraction of the time
# using in data fitting ( something in like 40 - 50 % .
# This was due to the repeate... |
def folderName ( self , folder ) :
"""gets / set the current folder""" | if folder == "" or folder == "/" :
self . _currentURL = self . _url
self . _services = None
self . _description = None
self . _folderName = None
self . _webEncrypted = None
self . __init ( )
self . _folderName = folder
elif folder in self . folders :
self . _currentURL = self . _url + "/... |
def list ( self , ** params ) :
"""Retrieve all deals
Returns all deals available to the user according to the parameters provided
: calls : ` ` get / deals ` `
: param dict params : ( optional ) Search options .
: return : List of dictionaries that support attriubte - style access , which represent collect... | _ , _ , deals = self . http_client . get ( "/deals" , params = params )
for deal in deals :
deal [ 'value' ] = Coercion . to_decimal ( deal [ 'value' ] )
return deals |
def read ( self , count = None , block = None , consumer = None ) :
"""Read unseen messages from all streams in the consumer group . Wrapper
for : py : class : ` Database . xreadgroup ` method .
: param int count : limit number of messages returned
: param int block : milliseconds to block , 0 for indefinitel... | if consumer is None :
consumer = self . _consumer
return self . database . xreadgroup ( self . name , consumer , self . _read_keys , count , block ) |
def tokenize ( self , tokenizer = None ) :
"""Return a list of tokens , using ` ` tokenizer ` ` .
: param tokenizer : ( optional ) A tokenizer object . If None , defaults to
this blob ' s default tokenizer .""" | t = tokenizer if tokenizer is not None else self . tokenizer
return WordList ( t . tokenize ( self . raw ) ) |
def get_json_schema ( filename ) :
"""Get a JSON Schema by filename .""" | file_path = os . path . join ( "schemas" , filename )
with open ( file_path ) as f :
schema = yaml . load ( f )
return schema |
def outputpairedstats ( fname , writemode , name1 , n1 , m1 , se1 , min1 , max1 , name2 , n2 , m2 , se2 , min2 , max2 , statname , stat , prob ) :
"""Prints or write to a file stats for two groups , using the name , n ,
mean , sterr , min and max for each group , as well as the statistic name ,
its value , and ... | suffix = ''
# for * s after the p - value
try :
x = prob . shape
prob = prob [ 0 ]
except :
pass
if prob < 0.001 :
suffix = ' ***'
elif prob < 0.01 :
suffix = ' **'
elif prob < 0.05 :
suffix = ' *'
title = [ [ 'Name' , 'N' , 'Mean' , 'SD' , 'Min' , 'Max' ] ]
lofl = title + [ [ name1 , n1 , ro... |
def complete_query ( self , name , query , page_size , language_codes = None , company_name = None , scope = None , type_ = None , retry = google . api_core . gapic_v1 . method . DEFAULT , timeout = google . api_core . gapic_v1 . method . DEFAULT , metadata = None , ) :
"""Completes the specified prefix with keywor... | # Wrap the transport method to add retry and timeout logic .
if "complete_query" not in self . _inner_api_calls :
self . _inner_api_calls [ "complete_query" ] = google . api_core . gapic_v1 . method . wrap_method ( self . transport . complete_query , default_retry = self . _method_configs [ "CompleteQuery" ] . retr... |
def request_token ( self ) -> None :
"""Requests a new Client Credentials Flow authentication token from the Spotify API
and stores it in the ` token ` property of the object .
Raises :
requests . HTTPError : If an HTTP error occurred during the request .""" | response : requests . Response = requests . post ( self . _TOKEN_URL , auth = HTTPBasicAuth ( self . _client_id , self . _client_key ) , data = { "grant_type" : self . _GRANT_TYPE } , verify = True )
response . raise_for_status ( )
self . _token = response . json ( )
self . _token_expires_at = time . time ( ) + self . ... |
def dict_to_json ( xcol , ycols , labels , value_columns ) :
"""Converts a list of dicts from datamodel query results
to google chart json data .
: param xcol :
The name of a string column to be used has X axis on chart
: param ycols :
A list with the names of series cols , that can be used as numeric
:... | json_data = dict ( )
json_data [ 'cols' ] = [ { 'id' : xcol , 'label' : as_unicode ( labels [ xcol ] ) , 'type' : 'string' } ]
for ycol in ycols :
json_data [ 'cols' ] . append ( { 'id' : ycol , 'label' : as_unicode ( labels [ ycol ] ) , 'type' : 'number' } )
json_data [ 'rows' ] = [ ]
for value in value_columns :
... |
def value ( self , new_value ) :
"""Set the value of this measurement .
Raises :
AttributeError : if the new value isn ' t of the correct units .""" | if self . unit != units . Undefined and new_value . unit != self . unit :
raise AttributeError ( "%s must be in %s" % ( self . __class__ , self . unit ) )
self . _value = new_value |
def or_filter ( self , ** filters ) :
"""Works like " filter " but joins given filters with OR operator .
Args :
* * filters : Query filters as keyword arguments .
Returns :
Self . Queryset object .
Example :
> > > Person . objects . or _ filter ( age _ _ gte = 16 , name _ _ startswith = ' jo ' )""" | clone = copy . deepcopy ( self )
clone . adapter . add_query ( [ ( "OR_QRY" , filters ) ] )
return clone |
def fixed_point_density_preserving ( points , cells , * args , ** kwargs ) :
"""Idea :
Move interior mesh points into the weighted averages of the circumcenters
of their adjacent cells . If a triangle cell switches orientation in the
process , don ' t move quite so far .""" | def get_new_points ( mesh ) : # Get circumcenters everywhere except at cells adjacent to the boundary ;
# barycenters there .
cc = mesh . cell_circumcenters
bc = mesh . cell_barycenters
# Find all cells with a boundary edge
boundary_cell_ids = mesh . edges_cells [ 1 ] [ : , 0 ]
cc [ boundary_cell_id... |
def append_rez_path ( self ) :
"""Append rez path to $ PATH .""" | if system . rez_bin_path :
self . env . PATH . append ( system . rez_bin_path ) |
def print_genl_hdr ( ofd , start ) :
"""https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L821.
Positional arguments :
ofd - - function to call with arguments similar to ` logging . debug ` .
start - - bytearray ( ) or bytearray _ ptr ( ) instance .""" | ghdr = genlmsghdr ( start )
ofd ( ' [GENERIC NETLINK HEADER] %d octets' , GENL_HDRLEN )
ofd ( ' .cmd = %d' , ghdr . cmd )
ofd ( ' .version = %d' , ghdr . version )
ofd ( ' .unused = %#d' , ghdr . reserved ) |
def followers_qs ( self , actor , flag = '' ) :
"""Returns a queryset of User objects who are following the given actor ( eg my followers ) .""" | check ( actor )
queryset = self . filter ( content_type = ContentType . objects . get_for_model ( actor ) , object_id = actor . pk ) . select_related ( 'user' )
if flag :
queryset = queryset . filter ( flag = flag )
return queryset |
def to_bytes ( instance , encoding = 'utf-8' , error = 'strict' ) :
'''Convert an instance recursively to bytes .''' | if isinstance ( instance , bytes ) :
return instance
elif hasattr ( instance , 'encode' ) :
return instance . encode ( encoding , error )
elif isinstance ( instance , list ) :
return list ( [ to_bytes ( item , encoding , error ) for item in instance ] )
elif isinstance ( instance , tuple ) :
return tupl... |
def disable_cpu ( self , rg ) :
'''Disable cpus
rg : range or list of threads to disable''' | if type ( rg ) == int :
rg = [ rg ]
to_disable = set ( rg ) & set ( self . __get_ranges ( "online" ) )
for cpu in to_disable :
fpath = path . join ( "cpu%i" % cpu , "online" )
self . __write_cpu_file ( fpath , b"0" ) |
def updateJoin ( self ) :
"""Updates the joining method used by the system .""" | text = self . uiJoinSBTN . currentAction ( ) . text ( )
if text == 'AND' :
joiner = QueryCompound . Op . And
else :
joiner = QueryCompound . Op . Or
self . _containerWidget . setCurrentJoiner ( self . joiner ( ) ) |
def __recognize_user_classes ( self , node : yaml . Node , expected_type : Type ) -> RecResult :
"""Recognize a user - defined class in the node .
This returns a list of classes from the inheritance hierarchy headed by expected _ type which match the given node and which do not have a registered derived class tha... | # Let the user override with an explicit tag
if node . tag in self . __registered_classes :
return [ self . __registered_classes [ node . tag ] ] , ''
recognized_subclasses = [ ]
message = ''
for other_class in self . __registered_classes . values ( ) :
if expected_type in other_class . __bases__ :
sub_... |
def get_sort_cmd ( tmp_dir = None ) :
"""Retrieve GNU coreutils sort command , using version - sort if available .
Recent versions of sort have alpha - numeric sorting , which provides
more natural sorting of chromosomes ( chr1 , chr2 ) instead of ( chr1 , chr10 ) .
This also fixes versions of sort , like 8.2... | has_versionsort = subprocess . check_output ( "sort --help | grep version-sort; exit 0" , shell = True ) . strip ( )
if has_versionsort :
cmd = "sort -V"
else :
cmd = "sort"
if tmp_dir and os . path . exists ( tmp_dir ) and os . path . isdir ( tmp_dir ) :
cmd += " -T %s" % tmp_dir
return cmd |
def import_from_stdlib ( name ) :
"""Copied from pdbpp https : / / bitbucket . org / antocuni / pdb""" | import os
import types
import code
# arbitrary module which stays in the same dir as pdb
stdlibdir , _ = os . path . split ( code . __file__ )
pyfile = os . path . join ( stdlibdir , name + '.py' )
result = types . ModuleType ( name )
exec ( compile ( open ( pyfile ) . read ( ) , pyfile , 'exec' ) , result . __dict__ )... |
def count_letters_digits ( input_string : str ) -> tuple :
"""Function to calculate the quantity of alphabetic characters and numeric digits in a string .
Args :
input _ string : A string that can contain any type of characters .
Returns :
A tuple of two integers . The first is the count of alphabetic chara... | letters = digits = 0
for char in input_string :
if char . isalpha ( ) :
letters += 1
elif char . isdigit ( ) :
digits += 1
return ( letters , digits ) |
def _scope_vars ( scope , trainable_only = False ) :
"""Get variables inside a scope
The scope can be specified as a string
Parameters
scope : str or VariableScope
scope in which the variables reside .
trainable _ only : bool
whether or not to return only the variables that were marked as
trainable . ... | return tf . get_collection ( tf . GraphKeys . TRAINABLE_VARIABLES if trainable_only else tf . GraphKeys . VARIABLES , scope = scope if isinstance ( scope , str ) else scope . name ) |
def check_array_struct ( array ) :
"""Check to ensure arrays are symmetrical , for example :
[ [ 1 , 2 , 3 ] , [ 1 , 2 ] ] is invalid""" | # If a list is transformed into a numpy array and the sub elements
# of this array are still lists , then numpy failed to fully convert
# the list , meaning it is not symmetrical .
try :
arr = np . array ( array )
except :
raise HydraError ( "Array %s is not valid." % ( array , ) )
if type ( arr [ 0 ] ) is list... |
def autoLayout ( self ) :
"""Automatically lays out the contents for this widget .""" | try :
direction = self . currentSlide ( ) . scene ( ) . direction ( )
except AttributeError :
direction = QtGui . QBoxLayout . TopToBottom
size = self . size ( )
self . _slideshow . resize ( size )
prev = self . _previousButton
next = self . _nextButton
if direction == QtGui . QBoxLayout . BottomToTop :
y =... |
def rpc ( self , cmd , ** kwargs ) :
"""Generic helper function to call an RPC method .""" | func = getattr ( self . client , cmd )
try :
if self . credentials is None :
return func ( kwargs )
else :
return func ( self . credentials , kwargs )
except socket . error as e :
raise BackendConnectionError ( e )
except ( xmlrpclib . ProtocolError , BadStatusLine ) as e :
log . error (... |
def create_withdrawal ( self , asset , amount , private_key ) :
"""Function to create a withdrawal request by generating a withdrawal ID request from the Switcheo API .
Execution of this function is as follows : :
create _ withdrawal ( asset = " SWTH " , amount = 1.1 , private _ key = kp )
The expected return... | signable_params = { 'blockchain' : self . blockchain , 'asset_id' : asset , 'amount' : str ( self . blockchain_amount [ self . blockchain ] ( amount ) ) , 'timestamp' : get_epoch_milliseconds ( ) , 'contract_hash' : self . contract_hash }
api_params = self . sign_create_withdrawal_function [ self . blockchain ] ( signa... |
def _extgrad ( xarr , alpha = 100 , axis = None ) :
'''Given an array xarr of values , return the gradient of the smooth min / max
swith respect to each entry in the array''' | term1 = ( np . exp ( alpha * xarr ) / np . sum ( np . exp ( alpha * xarr ) , axis = axis , keepdims = True ) )
term2 = 1 + alpha * ( xarr - _extalg ( xarr , alpha , axis = axis ) )
return term1 * term2 |
def sort_buses ( self , tokens ) :
"""Sorts bus list according to name ( bus _ no ) .""" | self . case . buses . sort ( key = lambda obj : obj . name ) |
def contextDoc ( self ) :
"""Get the doc from an xpathContext""" | ret = libxml2mod . xmlXPathGetContextDoc ( self . _o )
if ret is None :
raise xpathError ( 'xmlXPathGetContextDoc() failed' )
__tmp = xmlDoc ( _obj = ret )
return __tmp |
def _destinations_in_two_columns ( pdf , destinations , cutoff = 3 ) :
"""Check if the named destinations are organized along two columns ( heuristic )
@ param pdf : a PdfFileReader object
@ param destinations :
' cutoff ' is used to tune the heuristic : if ' cutoff ' destinations in the
would - be second c... | # iterator for the x coordinates of refs in the would - be second column
xpositions = ( _destination_position ( pdf , dest ) [ 3 ] for ( _ , dest ) in destinations if _destination_position ( pdf , dest ) [ 1 ] == 1 )
xpos_count = { }
for xpos in xpositions :
xpos_count [ xpos ] = xpos_count . get ( xpos , 0 ) + 1
... |
def install_wic ( self , wic_slot_id , wic ) :
"""Installs a WIC on this adapter .
: param wic _ slot _ id : WIC slot ID ( integer )
: param wic : WIC instance""" | self . _wics [ wic_slot_id ] = wic
# Dynamips WICs ports start on a multiple of 16 + port number
# WIC1 port 1 = 16 , WIC1 port 2 = 17
# WIC2 port 1 = 32 , WIC2 port 2 = 33
# WIC3 port 1 = 48 , WIC3 port 2 = 49
base = 16 * ( wic_slot_id + 1 )
for wic_port in range ( 0 , wic . interfaces ) :
port_number = base + wic... |
def path ( self , which = None ) :
"""Extend ` ` nailgun . entity _ mixins . Entity . path ` ` .
The format of the returned path depends on the value of ` ` which ` ` :
sync
/ products / < product _ id > / sync
` ` super ` ` is called otherwise .""" | if which == 'sync' :
return '{0}/{1}' . format ( super ( Product , self ) . path ( which = 'self' ) , which , )
return super ( Product , self ) . path ( which ) |
def compute_video_metrics_from_png_files ( output_dirs , problem_name , video_length , frame_shape ) :
"""Computes the average of all the metric for one decoding .
This function assumes that all the predicted and target frames
have been saved on the disk and sorting them by name will result
to consecutive fra... | ssim_all_decodes , psnr_all_decodes = [ ] , [ ]
for output_dir in output_dirs :
output_files , target_files = get_target_and_output_filepatterns ( output_dir , problem_name )
args = get_zipped_dataset_from_png_files ( output_files , target_files , video_length , frame_shape )
psnr_single , ssim_single = com... |
def convert_to_experiment_list ( experiments ) :
"""Produces a list of Experiment objects .
Converts input from dict , single experiment , or list of
experiments to list of experiments . If input is None ,
will return an empty list .
Arguments :
experiments ( Experiment | list | dict ) : Experiments to ru... | exp_list = experiments
# Transform list if necessary
if experiments is None :
exp_list = [ ]
elif isinstance ( experiments , Experiment ) :
exp_list = [ experiments ]
elif type ( experiments ) is dict :
exp_list = [ Experiment . from_json ( name , spec ) for name , spec in experiments . items ( ) ]
# Valida... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.