signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def url_param ( param , default = None ) : """Read a url or post parameter and use it in your SQL Lab query When in SQL Lab , it ' s possible to add arbitrary URL " query string " parameters , and use those in your SQL code . For instance you can alter your url and add ` ? foo = bar ` , as in ` { domain } /...
if request . args . get ( param ) : return request . args . get ( param , default ) # Supporting POST as well as get if request . form . get ( 'form_data' ) : form_data = json . loads ( request . form . get ( 'form_data' ) ) url_params = form_data . get ( 'url_params' ) or { } return url_params . get ( ...
def tobool ( obj , default = False ) : '''Returns a bool representation of ` obj ` : if ` obj ` is not a string , it is returned cast to a boolean by calling ` bool ( ) ` . Otherwise , it is checked for " truthy " or " falsy " values , and that is returned . If it is not truthy or falsy , ` default ` is retur...
if isinstance ( obj , bool ) : return obj if not isstr ( obj ) : return bool ( obj ) lobj = obj . lower ( ) if lobj in truthy : return True if lobj in falsy : return False if default is ValueError : raise ValueError ( 'invalid literal for tobool(): %r' % ( obj , ) ) return default
def get_conf_d_files ( path ) : """Return alphabetical ordered : class : ` list ` of the * . conf * files placed in the path . * path * is a directory path . > > > get _ conf _ d _ files ( ' conf / conf . d / ' ) [ ' conf / conf . d / 10 - base . conf ' , ' conf / conf . d / 99 - dev . conf ' ]"""
if not os . path . isdir ( path ) : raise ValueError ( "'%s' is not a directory" % path ) files_mask = os . path . join ( path , "*.conf" ) return [ f for f in sorted ( glob . glob ( files_mask ) ) if os . path . isfile ( f ) ]
def set_icc_profile ( self , profile = None , name = 'ICC Profile' ) : """Add ICC Profile . Prefered way is tuple ( ` profile _ name ` , ` profile _ bytes ` ) , but only bytes with name as separate argument is also supported ."""
if isinstance ( profile , ( basestring , bytes ) ) : icc_profile = [ name , profile ] # TODO : more check else : icc_profile = profile if not icc_profile [ 0 ] : raise Error ( "ICC profile should have a name" ) elif not isinstance ( icc_profile [ 0 ] , bytes ) : icc_profile [ 0 ] = strtobytes ( icc_prof...
def from_array ( array ) : """Deserialize a new MediaGroupMessage from a given dictionary . : return : new MediaGroupMessage instance . : rtype : MediaGroupMessage"""
if array is None or not array : return None # end if assert_type_or_raise ( array , dict , parameter_name = "array" ) from pytgbot . api_types . sendable . input_media import InputMediaPhoto from pytgbot . api_types . sendable . input_media import InputMediaVideo data = { } if isinstance ( array . get ( 'media' ) ,...
def f1 ( y , z ) : """F1 score : ` 2 * ( p * r ) / ( p + r ) ` , where p = precision and r = recall ."""
_recall = recall ( y , z ) _prec = precision ( y , z ) return 2 * ( _prec * _recall ) / ( _prec + _recall )
def prepare_axes ( wave , flux , fig = None , ax_lower = ( 0.1 , 0.1 ) , ax_dim = ( 0.85 , 0.65 ) ) : """Create fig and axes if needed and layout axes in fig ."""
# Axes location in figure . if not fig : fig = plt . figure ( ) ax = fig . add_axes ( [ ax_lower [ 0 ] , ax_lower [ 1 ] , ax_dim [ 0 ] , ax_dim [ 1 ] ] ) ax . plot ( wave , flux ) return fig , ax
def hybrid_forward ( self , F , scores , offset ) : """Get the single lowest element per sentence from a ` scores ` matrix . Expects that beam size is 1 , for greedy decoding . : param scores : Vocabulary scores for the next beam step . ( batch _ size * beam _ size , target _ vocabulary _ size ) : param offse...
best_word_indices = F . cast ( F . argmin ( scores , axis = 1 ) , dtype = 'int32' ) values = F . pick ( scores , best_word_indices , axis = 1 ) values = F . reshape ( values , shape = ( - 1 , 1 ) ) # for top1 , the best hyp indices are equal to the plain offset best_hyp_indices = offset return best_hyp_indices , best_w...
def find_mappable ( * axes ) : """Find the most recently added mappable layer in the given axes Parameters * axes : ` ~ matplotlib . axes . Axes ` one or more axes to search for a mappable"""
for ax in axes : for aset in ( 'collections' , 'images' ) : try : return getattr ( ax , aset ) [ - 1 ] except ( AttributeError , IndexError ) : continue raise ValueError ( "Cannot determine mappable layer on any axes " "for this colorbar" )
def create_network_interface ( SubnetId = None , Description = None , PrivateIpAddress = None , Groups = None , PrivateIpAddresses = None , SecondaryPrivateIpAddressCount = None , Ipv6Addresses = None , Ipv6AddressCount = None , DryRun = None ) : """Creates a network interface in the specified subnet . For more i...
pass
def generate_id ( cls , prefix = "pelix-" ) : """Generates a random MQTT client ID : param prefix : Client ID prefix ( truncated to 8 chars ) : return : A client ID of 22 or 23 characters"""
if not prefix : # Normalize string prefix = "" else : # Truncate long prefixes prefix = prefix [ : 8 ] # Prepare the missing part nb_bytes = ( 23 - len ( prefix ) ) // 2 random_bytes = os . urandom ( nb_bytes ) if sys . version_info [ 0 ] >= 3 : random_ints = [ char for char in random_bytes ] else : ran...
def _MaybePurgeOrphanedData ( self , event ) : """Maybe purge orphaned data due to a TensorFlow crash . When TensorFlow crashes at step T + O and restarts at step T , any events written after step T are now " orphaned " and will be at best misleading if they are included in TensorBoard . This logic attempts...
if not self . purge_orphaned_data : return # # Check if the event happened after a crash , and purge expired tags . if self . file_version and self . file_version >= 2 : # # If the file _ version is recent enough , use the SessionLog enum # # to check for restarts . self . _CheckForRestartAndMaybePurge ( event ...
def resize ( self , width = None ) : """Resizes image to fit inside terminal Called by the constructor automatically ."""
( iw , ih ) = self . size if width is None : width = min ( iw , utils . term . width ) elif isinstance ( width , basestring ) : percents = dict ( [ ( pct , '%s%%' % ( pct ) ) for pct in range ( 101 ) ] ) width = percents [ width ] height = int ( float ( ih ) * ( float ( width ) / float ( iw ) ) ) height //=...
def cli ( ctx , organism = "" , sequence = "" ) : """Get the features for an organism / sequence Output : A standard apollo feature dictionary ( { " features " : [ { . . . } ] } )"""
return ctx . gi . annotations . get_features ( organism = organism , sequence = sequence )
def _pull_assemble_error_status ( logs ) : '''Given input in this form : : u ' { " status " : " Pulling repository foo / ubuntubox " } : " image ( latest ) from foo / . . . rogress " : " complete " , " id " : " 2c80228370c9 " } ' construct something like that ( load JSON data is possible ) : : [ u ' { " s...
comment = 'An error occurred pulling your image' try : for err_log in logs : if isinstance ( err_log , dict ) : if 'errorDetail' in err_log : if 'code' in err_log [ 'errorDetail' ] : msg = '\n{0}\n{1}: {2}' . format ( err_log [ 'error' ] , err_log [ 'errorDeta...
def use ( node ) : "Set the fabric environment for the specifed node"
try : role = node . tags . get ( "Name" ) . split ( '-' ) [ 1 ] env . roledefs [ role ] += [ ip ( node ) ] except IndexError : pass env . nodes += [ node ] env . hosts += [ ip ( node ) ]
def get_all_spaces ( self , start = 0 , limit = 500 ) : """Get all spaces with provided limit : param start : OPTIONAL : The start point of the collection to return . Default : None ( 0 ) . : param limit : OPTIONAL : The limit of the number of pages to return , this may be restricted by fixed system limits . ...
url = 'rest/api/space' params = { } if limit : params [ 'limit' ] = limit if start : params [ 'start' ] = start return ( self . get ( url , params = params ) or { } ) . get ( 'results' )
def _get_triplet_value ( self , graph , identity , rdf_type ) : """Get a value from an RDF triple"""
value = graph . value ( subject = identity , predicate = rdf_type ) return value . toPython ( ) if value is not None else value
def gdcsreporter ( self , analysistype = 'GDCS' ) : """Creates a report of the GDCS results : param analysistype : The variable to use when accessing attributes in the metadata object"""
logging . info ( 'Creating {} report' . format ( analysistype ) ) # Initialise list to store all the GDCS genes , and genera in the analysis gdcs = list ( ) genera = list ( ) for sample in self . runmetadata . samples : if sample . general . bestassemblyfile != 'NA' : if os . path . isdir ( sample [ analysi...
def getAllKws ( self ) : """extract all keywords into two categories kws _ ele : magnetic elements kws _ bl : beamline elements return ( kws _ ele , kws _ bl )"""
kws_ele = [ ] kws_bl = [ ] for ele in self . all_elements : if ele == '_prefixstr' or ele == '_epics' : continue elif self . getElementType ( ele ) . lower ( ) == u'beamline' : kws_bl . append ( ele ) else : kws_ele . append ( ele ) return tuple ( ( kws_ele , kws_bl ) )
def detect_worktree ( cls , binary = 'git' , subdir = None ) : """Detect the git working tree above cwd and return it ; else , return None . : param string binary : The path to the git binary to use , ' git ' by default . : param string subdir : The path to start searching for a git repo . : returns : path to...
# TODO ( John Sirois ) : This is only used as a factory for a Git instance in # pants . base . build _ environment . get _ scm , encapsulate in a true factory method . cmd = [ binary , 'rev-parse' , '--show-toplevel' ] try : if subdir : with pushd ( subdir ) : process , out = cls . _invoke ( cmd...
def _retry ( self , context , backoff ) : '''A function which determines whether and how to retry . : param ~ azure . storage . models . RetryContext context : The retry context . This contains the request , response , and other data which can be used to determine whether or not to retry . : param function ...
# If the context does not contain a count parameter , this request has not # been retried yet . Add the count parameter to track the number of retries . if not hasattr ( context , 'count' ) : context . count = 0 # Determine whether to retry , and if so increment the count , modify the # request as desired , and ret...
def nse ( sim = None , obs = None , node = None , skip_nan = False ) : """Calculate the efficiency criteria after Nash & Sutcliffe . If the simulated values predict the observed values as well as the average observed value ( regarding the the mean square error ) , the NSE value is zero : > > > from hydpy im...
sim , obs = prepare_arrays ( sim , obs , node , skip_nan ) return 1. - numpy . sum ( ( sim - obs ) ** 2 ) / numpy . sum ( ( obs - numpy . mean ( obs ) ) ** 2 )
def move_back ( columns = 1 , file = sys . stdout ) : """Move the cursor back a number of columns . Esc [ < columns > D : Moves the cursor back by the specified number of columns without changing lines . If the cursor is already in the leftmost column , ANSI . SYS ignores this sequence ."""
move . back ( columns ) . write ( file = file )
def read_pestpp_runstorage ( filename , irun = 0 , with_metadata = False ) : """read pars and obs from a specific run in a pest + + serialized run storage file into pandas . DataFrame ( s ) Parameters filename : str the name of the run storage file irun : int the run id to process . If ' all ' , then al...
header_dtype = np . dtype ( [ ( "n_runs" , np . int64 ) , ( "run_size" , np . int64 ) , ( "p_name_size" , np . int64 ) , ( "o_name_size" , np . int64 ) ] ) try : irun = int ( irun ) except : if irun . lower ( ) == "all" : irun = irun . lower ( ) else : raise Exception ( "unrecognized 'irun':...
def filepaths ( self ) -> List [ str ] : """Absolute path names of the files contained in the current working directory . Files names starting with underscores are ignored : > > > from hydpy . core . filetools import FileManager > > > filemanager = FileManager ( ) > > > filemanager . BASEDIR = ' basename ...
path = self . currentpath return [ os . path . join ( path , name ) for name in self . filenames ]
def initialize ( self , symbolic_vm : LaserEVM ) : """Initializes the mutation pruner Introduces hooks for SSTORE operations : param symbolic _ vm : : return :"""
@ symbolic_vm . pre_hook ( "SSTORE" ) def mutator_hook ( global_state : GlobalState ) : global_state . annotate ( MutationAnnotation ( ) ) @ symbolic_vm . laser_hook ( "add_world_state" ) def world_state_filter_hook ( global_state : GlobalState ) : if And ( * global_state . mstate . constraints [ : ] + [ global...
def register ( self , plugin ) : """Make a plugin known to the CMS . : param plugin : The plugin class , deriving from : class : ` ContentPlugin ` . : type plugin : : class : ` ContentPlugin ` The plugin will be instantiated once , just like Django does this with : class : ` ~ django . contrib . admin . Model...
# Duck - Typing does not suffice here , avoid hard to debug problems by upfront checks . assert issubclass ( plugin , ContentPlugin ) , "The plugin must inherit from `ContentPlugin`" assert plugin . model , "The plugin has no model defined" assert issubclass ( plugin . model , ContentItem ) , "The plugin model must inh...
def remove_all_timers ( self ) : """Remove all waiting timers and terminate any blocking threads ."""
with self . lock : if self . rtimer is not None : self . rtimer . cancel ( ) self . timers = { } self . heap = [ ] self . rtimer = None self . expiring = False
def lockToColumn ( self , index ) : """Sets the column that the tree view will lock to . If None is supplied , then locking will be removed . : param index | < int > | | None"""
self . _lockColumn = index if index is None : self . __destroyLockedView ( ) return else : if not self . _lockedView : view = QtGui . QTreeView ( self . parent ( ) ) view . setModel ( self . model ( ) ) view . setSelectionModel ( self . selectionModel ( ) ) view . setItemDele...
def indentation ( node ) : """Returns the indentation for this node Iff a node is in a suite , then it has indentation ."""
while node . parent is not None and node . parent . type != syms . suite : node = node . parent if node . parent is None : return u"" # The first three children of a suite are NEWLINE , INDENT , ( some other node ) # INDENT . value contains the indentation for this suite # anything after ( some other node ) has...
def select_coins ( target , fee , output_size , min_change , * , absolute_fee = False , consolidate = False , unspents ) : '''Implementation of Branch - and - Bound coin selection defined in Erhart ' s Master ' s thesis An Evaluation of Coin Selection Strategies here : http : / / murch . one / wp - content / up...
# The maximum number of tries for Branch - and - Bound : BNB_TRIES = 1000000 # COST _ OF _ OVERHEAD excludes the return address of output _ size ( last element ) . COST_OF_OVERHEAD = ( 8 + sum ( output_size [ : - 1 ] ) + 1 ) * fee def branch_and_bound ( d , selected_coins , effective_value , target , fee , sorted_unspe...
def load_tool ( tool , tooldir = None ) : '''load _ tool : import a Python module , optionally using several directories . @ param tool [ string ] : name of tool to import . @ param tooldir [ list ] : directories to look for the tool . @ return : the loaded module . Warning : this function is not thread - s...
if tooldir : assert isinstance ( tooldir , list ) sys . path = tooldir + sys . path else : tooldir = [ ] try : return __import__ ( tool ) finally : for dt in tooldir : sys . path . remove ( dt )
def setCurrentSchema ( self , schema ) : """Sets the index for this combobox to the inputed schema instance . : param schema < orb . TableSchema > : return < bool > success"""
if ( not schema in self . _schemas ) : return False index = self . _schemas . index ( schema ) self . setCurrentIndex ( index ) return True
def highPassFilter ( self , threshold ) : '''remove all low frequencies by setting a square in the middle of the Fourier transformation of the size ( 2 * threshold ) ^ 2 to zero threshold = 0 . . . 1'''
if not threshold : return rows , cols = self . img . shape tx = int ( cols * threshold ) ty = int ( rows * threshold ) # middle : crow , ccol = rows // 2 , cols // 2 # square in the middle to zero self . fshift [ crow - tx : crow + tx , ccol - ty : ccol + ty ] = 0
def run ( self , change ) : """runs the report format instances in this reporter . Will call setup if it hasn ' t been called already"""
if self . _formats is None : self . setup ( ) entry = self . entry for fmt in self . _formats : fmt . run ( change , entry ) self . clear ( )
def energy_minimize ( self , forcefield = 'UFF' , steps = 1000 , ** kwargs ) : """Perform an energy minimization on a Compound Default beahvior utilizes Open Babel ( http : / / openbabel . org / docs / dev / ) to perform an energy minimization / geometry optimization on a Compound by applying a generic force ...
tmp_dir = tempfile . mkdtemp ( ) original = clone ( self ) self . _kick ( ) self . save ( os . path . join ( tmp_dir , 'un-minimized.mol2' ) ) extension = os . path . splitext ( forcefield ) [ - 1 ] openbabel_ffs = [ 'MMFF94' , 'MMFF94s' , 'UFF' , 'GAFF' , 'Ghemical' ] if forcefield in openbabel_ffs : self . _energ...
def list_to_raw_list ( poselist ) : """Flatten a normal pose list into a raw list : param poselist : a formatted list [ [ x , y , z ] , [ x , y , z , w ] ] : return : a raw list [ x , y , z , x , y , z , w ]"""
if not ( isinstance ( poselist , list ) or isinstance ( poselist , tuple ) ) : raise TypeError ( "flatten_pose({}) does not accept this type of argument" . format ( str ( type ( poselist ) ) ) ) return [ field for pose in poselist for field in pose ]
def finish_commit ( self , commit ) : """Ends the process of committing data to a Repo and persists the Commit . Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error . Params : * commit : A tuple , string , or Commit object representing the commit ....
req = proto . FinishCommitRequest ( commit = commit_from ( commit ) ) res = self . stub . FinishCommit ( req , metadata = self . metadata ) return res
def selection ( self ) : """Return a datetime representing the current selected date ."""
if not self . _selection : return None year , month = self . _date . year , self . _date . month return self . datetime ( year , month , int ( self . _selection [ 0 ] ) )
def process_command ( self , command ) : '''Processes a user command using aliases Arguments : command A user command list ( e . g . argv ) Returns : A ScubaContext object with the following attributes : script : a list of command line strings image : the docker image name to use'''
result = ScubaContext ( ) result . script = None result . image = self . image result . entrypoint = self . entrypoint result . environment = self . environment . copy ( ) if command : alias = self . aliases . get ( command [ 0 ] ) if not alias : # Command is not an alias ; use it as - is . result . scr...
def channels_replies ( self , * , channel : str , thread_ts : str , ** kwargs ) -> SlackResponse : """Retrieve a thread of messages posted to a channel Args : channel ( str ) : The channel id . e . g . ' C1234567890' thread _ ts ( str ) : The timestamp of an existing message with 0 or more replies . e . g ....
kwargs . update ( { "channel" : channel , "thread_ts" : thread_ts } ) return self . api_call ( "channels.replies" , http_verb = "GET" , params = kwargs )
def stop_listener_thread ( self ) : """Kills sync _ thread greenlet before joining it"""
# when stopping , ` kill ` will cause the ` self . api . sync ` call in _ sync # to raise a connection error . This flag will ensure it exits gracefully then self . should_listen = False if self . sync_thread : self . sync_thread . kill ( ) self . sync_thread . get ( ) if self . _handle_thread is not None : ...
def find_n50 ( self ) : """Calculate the N50 for each strain . N50 is defined as the largest contig such that at least half of the total genome size is contained in contigs equal to or larger than this contig"""
for sample in self . metadata : # Initialise the N50 attribute in case there is no assembly , and the attribute is not created in the loop sample [ self . analysistype ] . n50 = '-' # Initialise a variable to store a running total of contig lengths currentlength = 0 for contig_length in sample [ self . ...
def _update_docstrings ( self ) : """Runs through the operation methods & updates their docstrings if necessary . If the method has the default placeholder docstring , this will replace it with the docstring from the underlying connection ."""
ops = self . _details . resource_data [ 'operations' ] for method_name in ops . keys ( ) : meth = getattr ( self . __class__ , method_name , None ) if not meth : continue if meth . __doc__ != DEFAULT_DOCSTRING : # It already has a custom docstring . Leave it alone . continue # Needs upda...
def date_totals ( entries , by ) : """Yield a user ' s name and a dictionary of their hours"""
date_dict = { } for date , date_entries in groupby ( entries , lambda x : x [ 'date' ] ) : if isinstance ( date , datetime . datetime ) : date = date . date ( ) d_entries = list ( date_entries ) if by == 'user' : name = ' ' . join ( ( d_entries [ 0 ] [ 'user__first_name' ] , d_entries [ 0 ] ...
def save_experiment ( self , name , variants ) : """Persist an experiment and its variants ( unless they already exist ) . : param name a unique string name for the experiment : param variants a list of strings , each with a unique variant name"""
try : model . Experiment ( name = name , started_on = datetime . utcnow ( ) , variants = [ model . Variant ( name = v , order = i ) for i , v in enumerate ( variants ) ] ) self . Session . commit ( ) finally : self . Session . close ( )
def load_shortcuts ( self ) : """Load shortcuts and assign to table model ."""
shortcuts = [ ] for context , name , keystr in iter_shortcuts ( ) : shortcut = Shortcut ( context , name , keystr ) shortcuts . append ( shortcut ) shortcuts = sorted ( shortcuts , key = lambda x : x . context + x . name ) # Store the original order of shortcuts for i , shortcut in enumerate ( shortcuts ) : ...
def to_ ( self , attrvals ) : """Create a list of Attribute instances . : param attrvals : A dictionary of attributes and values : return : A list of Attribute instances"""
attributes = [ ] for key , value in attrvals . items ( ) : key = key . lower ( ) attributes . append ( factory ( saml . Attribute , name = key , name_format = self . name_format , attribute_value = do_ava ( value ) ) ) return attributes
def aes_kdf ( key , rounds , password = None , keyfile = None ) : """Set up a context for AES128 - ECB encryption to find transformed _ key"""
cipher = AES . new ( key , AES . MODE_ECB ) key_composite = compute_key_composite ( password = password , keyfile = keyfile ) # get the number of rounds from the header and transform the key _ composite transformed_key = key_composite for _ in range ( 0 , rounds ) : transformed_key = cipher . encrypt ( transformed_...
def parse_phone ( parts , allow_multiple = False ) : """Parse the phone number from the ad ' s parts parts - > The backpage ad ' s posting _ body , separated into substrings allow _ multiple - > If false , arbitrarily chooses the most commonly occurring phone"""
# Get text substitutions ( ex : ' three ' - > ' 3 ' ) text_subs = misc . phone_text_subs ( ) Small = text_subs [ 'Small' ] Magnitude = text_subs [ 'Magnitude' ] Others = text_subs [ 'Others' ] phone_pattern = r'1?(?:[2-9][0-8][0-9])\s?(?:[2-9][0-9]{2})\s?(?:[0-9]{2})\s?(?:[0-9]{2})' phone_pattern_spaces = r'1?\W?[2-9]\...
def img_encode ( arr , ** kwargs ) : """Encode ndarray to base64 string image data Parameters arr : ndarray ( rows , cols , depth ) kwargs : passed directly to matplotlib . image . imsave"""
sio = BytesIO ( ) imsave ( sio , arr , ** kwargs ) sio . seek ( 0 ) img_format = kwargs [ 'format' ] if kwargs . get ( 'format' ) else 'png' img_str = base64 . b64encode ( sio . getvalue ( ) ) . decode ( ) return 'data:image/{};base64,{}' . format ( img_format , img_str )
def xmlstring ( self , pretty_print = False ) : """Serialises this FoLiA element and all its contents to XML . Returns : str : a string with XML representation for this element and all its children"""
s = ElementTree . tostring ( self . xml ( ) , xml_declaration = False , pretty_print = pretty_print , encoding = 'utf-8' ) if sys . version < '3' : if isinstance ( s , str ) : s = unicode ( s , 'utf-8' ) # pylint : disable = undefined - variable else : if isinstance ( s , bytes ) : s = s...
def write_csv ( filename , data , delimiter = CSV_DELIMITER ) : """Write image data to CSV file : param filename : name of CSV file to write data to : type filename : str : param data : image data to write to CSV file : type data : numpy array : param delimiter : delimiter used in CSV file . Default is ` ...
with open ( filename , 'w' ) as file : csv_writer = csv . writer ( file , delimiter = delimiter ) for line in data : csv_writer . writerow ( line )
def add_ref ( self , wordlist ) : """Adds a reference ."""
refname = wordlist [ 0 ] [ : - 1 ] if ( refname in self . refs ) : raise ReferenceError ( "[line {}]:{} already defined here (word) {} (line) {}" . format ( self . line_count , refname , self . refs [ refname ] [ 0 ] , self . refs [ refname ] [ 1 ] ) ) self . refs [ refname ] = ( self . word_count , self . line_cou...
def run_checks ( collector ) : """Just run the checks for our modules"""
artifact = collector . configuration [ "dashmat" ] . artifact chosen = artifact if chosen in ( None , "" , NotSpecified ) : chosen = None dashmat = collector . configuration [ "dashmat" ] modules = collector . configuration [ "__active_modules__" ] config_root = collector . configuration [ "config_root" ] module_op...
def normalize_value ( value ) : """Convert value to string and make it lower cased ."""
cast = str if six . PY2 : cast = unicode # noqa return cast ( value ) . lower ( )
def _wiggle_interval ( value , wiggle = 0.5 ** 44 ) : r"""Check if ` ` value ` ` is in : math : ` \ left [ 0 , 1 \ right ] ` . Allows a little bit of wiggle room outside the interval . Any value within ` ` wiggle ` ` of ` ` 0.0 ` will be converted to ` ` 0.0 ` and similar for ` ` 1.0 ` ` . . . note : : Th...
if - wiggle < value < wiggle : return 0.0 , True elif wiggle <= value <= 1.0 - wiggle : return value , True elif 1.0 - wiggle < value < 1.0 + wiggle : return 1.0 , True else : return np . nan , False
def sendFuture ( self , future ) : """Send a Future to be executed remotely ."""
try : if shared . getConst ( hash ( future . callable ) , timeout = 0 ) : # Enforce name reference passing if already shared future . callable = SharedElementEncapsulation ( hash ( future . callable ) ) self . socket . send_multipart ( [ b"TASK" , pickle . dumps ( future , pickle . HIGHEST_PROTOCOL ) ] ...
def _get_instance_attributes ( self ) : """Return a generator for instance attributes ' name and value . . . code - block : : python3 for _ name , _ value in self . _ get _ instance _ attributes ( ) : print ( " attribute name : { } " . format ( _ name ) ) print ( " attribute value : { } " . format ( _ value...
for name , value in self . __dict__ . items ( ) : if name in map ( ( lambda x : x [ 0 ] ) , self . get_class_attributes ( ) ) : yield ( name , value )
def to_json ( self ) : """Write Wea to json file " location " : { } , / / ladybug location schema " direct _ normal _ irradiance " : ( ) , / / Tuple of hourly direct normal irradiance " diffuse _ horizontal _ irradiance " : ( ) , / / Tuple of hourly diffuse horizontal irradiance " timestep " : float / /...
return { 'location' : self . location . to_json ( ) , 'direct_normal_irradiance' : self . direct_normal_irradiance . to_json ( ) , 'diffuse_horizontal_irradiance' : self . diffuse_horizontal_irradiance . to_json ( ) , 'timestep' : self . timestep , 'is_leap_year' : self . is_leap_year }
def mktmpenv_cmd ( argv ) : """Create a temporary virtualenv ."""
parser = mkvirtualenv_argparser ( ) env = '.' while ( workon_home / env ) . exists ( ) : env = hex ( random . getrandbits ( 64 ) ) [ 2 : - 1 ] args , rest = parser . parse_known_args ( argv ) mkvirtualenv ( env , args . python , args . packages , requirements = args . requirements , rest = rest ) print ( 'This is a...
def default_capture_file_name ( self ) : """: returns : File name for a capture on this link"""
capture_file_name = "{}_{}-{}_to_{}_{}-{}" . format ( self . _nodes [ 0 ] [ "node" ] . name , self . _nodes [ 0 ] [ "adapter_number" ] , self . _nodes [ 0 ] [ "port_number" ] , self . _nodes [ 1 ] [ "node" ] . name , self . _nodes [ 1 ] [ "adapter_number" ] , self . _nodes [ 1 ] [ "port_number" ] ) return re . sub ( "[...
def support_support_param_password ( self , ** kwargs ) : """Auto Generated Code"""
config = ET . Element ( "config" ) support = ET . SubElement ( config , "support" , xmlns = "urn:brocade.com:mgmt:brocade-ras" ) support_param = ET . SubElement ( support , "support-param" ) password = ET . SubElement ( support_param , "password" ) password . text = kwargs . pop ( 'password' ) callback = kwargs . pop (...
def _get_index ( self ) : """Get the guideline ' s index . This must return an ` ` int ` ` . Subclasses may override this method ."""
glyph = self . glyph if glyph is not None : parent = glyph else : parent = self . font if parent is None : return None return parent . guidelines . index ( self )
def age ( * paths ) : '''Return the minimum age of a set of files . Returns 0 if no paths are given . Returns time . time ( ) if a path does not exist .'''
if not paths : return 0 for path in paths : if not os . path . exists ( path ) : return time . time ( ) return min ( [ ( time . time ( ) - os . path . getmtime ( path ) ) for path in paths ] )
def download ( self , url , location , ** kwargs ) : """Fetch document located at ` ` url ` ` and save to to ` ` location ` ` ."""
doc = self . go ( url , ** kwargs ) with open ( location , 'wb' ) as out : out . write ( doc . body ) return len ( doc . body )
def diff_for_humans ( self , other = None , absolute = False , locale = None ) : """Get the difference in a human readable format in the current locale . When comparing a value in the past to default now : 1 day ago 5 months ago When comparing a value in the future to default now : 1 day from now 5 mont...
is_now = other is None if is_now : other = self . today ( ) diff = self . diff ( other ) return pendulum . format_diff ( diff , is_now , absolute , locale )
def _get_frdata ( stream , num , name , ctype = None ) : """Brute force - ish method to return the FrData structure for a channel This saves on pulling the channel type from the TOC"""
ctypes = ( ctype , ) if ctype else ( 'adc' , 'proc' , 'sim' ) for ctype in ctypes : _reader = getattr ( stream , 'ReadFr{0}Data' . format ( ctype . title ( ) ) ) try : return _reader ( num , name ) except IndexError as exc : if FRERR_NO_CHANNEL_OF_TYPE . match ( str ( exc ) ) : c...
def get_metrics ( predicted : Union [ str , List [ str ] , Tuple [ str , ... ] ] , gold : Union [ str , List [ str ] , Tuple [ str , ... ] ] ) -> Tuple [ float , float ] : """Takes a predicted answer and a gold answer ( that are both either a string or a list of strings ) , and returns exact match and the DROP F1...
predicted_bags = _answer_to_bags ( predicted ) gold_bags = _answer_to_bags ( gold ) exact_match = 1.0 if predicted_bags [ 0 ] == gold_bags [ 0 ] else 0 f1_per_bag = _align_bags ( predicted_bags [ 1 ] , gold_bags [ 1 ] ) f1 = np . mean ( f1_per_bag ) f1 = round ( f1 , 2 ) return exact_match , f1
def load ( cls , build_file , name , target_aliases ) : """A BuildFileManipulator factory class method . Note that BuildFileManipulator requires a very strict formatting of target declaration . In particular , it wants to see a newline after ` target _ type ( ` , ` dependencies = [ ` , and the last param to t...
with open ( build_file . full_path , 'r' ) as f : source = f . read ( ) source_lines = source . split ( '\n' ) tree = ast . parse ( source ) # Since we ' re not told what the last line of an expression is , we have # to figure it out based on the start of the expression after it . # The interval that we consider oc...
def get_share_metadata ( self , share_name , timeout = None ) : '''Returns all user - defined metadata for the specified share . : param str share _ name : Name of existing share . : param int timeout : The timeout parameter is expressed in seconds . : return : A dictionary representing the share metada...
_validate_not_none ( 'share_name' , share_name ) request = HTTPRequest ( ) request . method = 'GET' request . host = self . _get_host ( ) request . path = _get_path ( share_name ) request . query = [ ( 'restype' , 'share' ) , ( 'comp' , 'metadata' ) , ( 'timeout' , _int_to_str ( timeout ) ) , ] response = self . _perfo...
def readcbf ( name , load_header = False , load_data = True , for_nexus = False ) : """Read a cbf ( crystallographic binary format ) file from a Dectris PILATUS detector . Inputs name : string the file name load _ header : bool if the header data is to be loaded . load _ data : bool if the binary da...
with open ( name , 'rb' ) as f : cbfbin = f . read ( ) datastart = cbfbin . find ( b'\x0c\x1a\x04\xd5' ) + 4 hed = [ x . strip ( ) for x in cbfbin [ : datastart ] . split ( b'\n' ) ] header = { } readingmode = None for i in range ( len ( hed ) ) : if not hed [ i ] : # skip empty header lines continue ...
def send_image ( self , user_id , media_id , account = None ) : """发送图片消息 详情请参考 http : / / mp . weixin . qq . com / wiki / 7/12a5a320ae96fecdf0e15cb06123de9f . html : param user _ id : 用户 ID 。 就是你收到的 ` Message ` 的 source : param media _ id : 图片的媒体ID 。 可以通过 : func : ` upload _ media ` 上传 。 : param account ...
data = { 'touser' : user_id , 'msgtype' : 'image' , 'image' : { 'media_id' : media_id } } return self . _send_custom_message ( data , account = account )
def callOrder ( cls , * args ) : # pylint : disable = invalid - name """Checking the inspector is called with given priority Args : SinonSpy , list of inspectors eg . [ spy1 , spy2 , spy3 ] = > spy1 is called before spy2 , spy2 is called before spy3 [ spy1 , spy2 , spy1 ] = > spy1 is called before and after...
for spy in args : cls . __is_spy ( spy ) for idx , val in enumerate ( args ) : if val != args [ 0 ] : if not ( val . calledAfter ( args [ idx - 1 ] ) ) : raise cls . failException ( cls . message ) if val != args [ - 1 ] : if not ( val . calledBefore ( args [ idx + 1 ] ) ) : ...
def clear_input_field ( self , locator , method = 0 ) : """Clears the text field identified by ` locator ` The element . clear ( ) method doesn ' t seem to work properly on all browsers , so this keyword was created to offer alternatives . The ` method ` argument defines the method it should use in order to...
element = self . _element_find ( locator , True , True ) if ( int ( method ) == 0 ) : self . _info ( "Clearing input on element '%s'" % ( locator ) ) element . clear ( ) elif ( int ( method ) == 1 ) : self . _info ( "Clearing input on element '%s' by pressing 'CTRL + A + DELETE'" % ( locator ) ) element...
def collect_variables ( self , variables : MultisetOfVariables ) -> None : """Recursively adds all variables occuring in the expression to the given multiset . This is used internally by ` variables ` . Needs to be overwritten by inheriting container expression classes . This method can be used when gathering t...
if self . variable_name is not None : variables . add ( self . variable_name )
def assert_raises_regex ( expected_exception , expected_regex , extras = None , * args , ** kwargs ) : """Assert that an exception is raised when a function is called . If no exception is raised , test fail . If an exception is raised but not of the expected type , the exception is let through . If an exception...
context = _AssertRaisesContext ( expected_exception , expected_regex , extras = extras ) return context
def parse_from_dict ( json_dict ) : """Given a Unified Uploader message , parse the contents and return a MarketOrderList . : param dict json _ dict : A Unified Uploader message as a JSON dict . : rtype : MarketOrderList : returns : An instance of MarketOrderList , containing the orders within ."""
order_columns = json_dict [ 'columns' ] order_list = MarketOrderList ( upload_keys = json_dict [ 'uploadKeys' ] , order_generator = json_dict [ 'generator' ] , ) for rowset in json_dict [ 'rowsets' ] : generated_at = parse_datetime ( rowset [ 'generatedAt' ] ) region_id = rowset [ 'regionID' ] type_id = row...
def run ( self , run_fit_model = True ) : """Run the Graph Cut segmentation according to preset parameters . : param run _ fit _ model : Allow to skip model fit when the model is prepared before : return :"""
if run_fit_model : self . fit_model ( self . img , self . voxelsize , self . seeds ) self . _start_time = time . time ( ) if self . segparams [ "method" ] . lower ( ) in ( "graphcut" , "gc" ) : self . __single_scale_gc_run ( ) elif self . segparams [ "method" ] . lower ( ) in ( "multiscale_graphcut" , "multisca...
def excel_key ( index ) : """create a key for index by converting index into a base - 26 number , using A - Z as the characters ."""
X = lambda n : ~ n and X ( ( n // 26 ) - 1 ) + chr ( 65 + ( n % 26 ) ) or '' return X ( int ( index ) )
def blast ( self , blastfile = None , outfile = None ) : """convert anchor file to 12 col blast file"""
from jcvi . formats . blast import BlastSlow , BlastLineByConversion if not outfile : outfile = self . filename + ".blast" if blastfile is not None : blasts = BlastSlow ( blastfile ) . to_dict ( ) else : blasts = None fw = must_open ( outfile , "w" , checkexists = True ) nlines = 0 for a , b , id in self . ...
def _build_line ( colwidths , colaligns , linefmt ) : "Return a string which represents a horizontal line ."
if not linefmt : return None if hasattr ( linefmt , "__call__" ) : return linefmt ( colwidths , colaligns ) else : begin , fill , sep , end = linefmt cells = [ fill * w for w in colwidths ] return _build_simple_row ( cells , ( begin , sep , end ) )
def package_files ( directory ) : """Get list of data files to add to the package ."""
paths = [ ] for ( path , _ , file_names ) in walk ( directory ) : for filename in file_names : paths . append ( join ( '..' , path , filename ) ) return paths
def iter_decode ( input , fallback_encoding , errors = 'replace' ) : """" Pull " - based decoder . : param input : An iterable of byte strings . The input is first consumed just enough to determine the encoding based on the precense of a BOM , then consumed on demand when the return value is . : param f...
decoder = IncrementalDecoder ( fallback_encoding , errors ) generator = _iter_decode_generator ( input , decoder ) encoding = next ( generator ) return generator , encoding
def _GetAttributeNames ( self , data_type_definition ) : """Determines the attribute ( or field ) names of the members . Args : data _ type _ definition ( DataTypeDefinition ) : data type definition . Returns : list [ str ] : attribute names . Raises : FormatError : if the attribute names cannot be dete...
if not data_type_definition : raise errors . FormatError ( 'Missing data type definition' ) attribute_names = [ ] for member_definition in data_type_definition . members : attribute_names . append ( member_definition . name ) return attribute_names
def print_device_list ( self , device_list = None ) : """Optional parameter is a list of device objects . If omitted , will just print all portal devices objects ."""
dev_list = device_list if device_list is not None else self . get_all_devices_in_portal ( ) for dev in dev_list : print ( '{0}\t\t{1}\t\t{2}' . format ( dev [ 'info' ] [ 'description' ] [ 'name' ] , dev [ 'sn' ] , dev [ 'portals_aliases' ] if len ( dev [ 'portals_aliases' ] ) != 1 else dev [ 'portals_aliases' ] [ 0...
def add_batch ( self , nlive = 500 , wt_function = None , wt_kwargs = None , maxiter = None , maxcall = None , save_bounds = True , print_progress = True , print_func = None , stop_val = None ) : """Allocate an additional batch of ( nested ) samples based on the combined set of previous samples using the specifie...
# Initialize values . if maxcall is None : maxcall = sys . maxsize if maxiter is None : maxiter = sys . maxsize if wt_function is None : wt_function = weight_function if wt_kwargs is None : wt_kwargs = dict ( ) if print_func is None : print_func = print_fn # If we have either likelihood calls or ite...
def _add_escape_character_for_quote_prime_character ( self , text ) : """Fix for https : / / github . com / openatx / facebook - wda / issues / 33 Returns : string with properly formated quotes , or non changed text"""
if text is not None : if "'" in text : return text . replace ( "'" , "\\'" ) elif '"' in text : return text . replace ( '"' , '\\"' ) else : return text else : return text
def inter ( a , b ) : """Intersect two sets of any data type to form a third set . http : / / naif . jpl . nasa . gov / pub / naif / toolkit _ docs / C / cspice / inter _ c . html : param a : First input set . : type a : spiceypy . utils . support _ types . SpiceCell : param b : Second input set . : type ...
assert isinstance ( a , stypes . SpiceCell ) assert isinstance ( b , stypes . SpiceCell ) assert a . dtype == b . dtype # Next line was redundant with [ raise NotImpImplementedError ] below # assert a . dtype = = 0 or a . dtype = = 1 or a . dtype = = 2 if a . dtype is 0 : c = stypes . SPICECHAR_CELL ( max ( a . siz...
def absent ( name , tags = None , region = None , key = None , keyid = None , profile = None ) : '''Ensure VPC with passed properties is absent . name Name of the VPC . tags A list of tags . All tags must match . region Region to connect to . key Secret key to be used . keyid Access key to be us...
ret = { 'name' : name , 'result' : True , 'comment' : '' , 'changes' : { } } r = __salt__ [ 'boto_vpc.get_id' ] ( name = name , tags = tags , region = region , key = key , keyid = keyid , profile = profile ) if 'error' in r : ret [ 'result' ] = False ret [ 'comment' ] = 'Failed to delete VPC: {0}.' . format ( r...
def get_or_generate_vocab_inner ( data_dir , vocab_filename , vocab_size , generator , max_subtoken_length = None , reserved_tokens = None ) : """Inner implementation for vocab generators . Args : data _ dir : The base directory where data and vocab files are stored . If None , then do not save the vocab even...
if data_dir and vocab_filename : vocab_filepath = os . path . join ( data_dir , vocab_filename ) if tf . gfile . Exists ( vocab_filepath ) : tf . logging . info ( "Found vocab file: %s" , vocab_filepath ) return text_encoder . SubwordTextEncoder ( vocab_filepath ) else : vocab_filepath = Non...
def get_neighbor_names ( self , node_name : str , order : int = 1 ) -> list : """Get the names of all neighbors of a node , and the node itself . : param node _ name : Node whose neighbor names are requested . : return : A list of names of all neighbors of a node , and the node itself ."""
logger . info ( "In get_neighbor_names()" ) node = self . graph . vs . find ( name = node_name ) neighbors = self . graph . neighborhood ( node , order = order ) names = self . graph . vs [ neighbors ] [ "name" ] names . append ( node_name ) return list ( names )
def get_nova_endpoint ( cls , json_resp , nova_api_version = None ) : """Parse the service catalog returned by the Identity API for an endpoint matching the Nova service with the requested version Sends a CRITICAL service check when no viable candidates are found in the Catalog"""
nova_version = nova_api_version or DEFAULT_NOVA_API_VERSION catalog = json_resp . get ( 'token' , { } ) . get ( 'catalog' , [ ] ) nova_match = 'novav21' if nova_version == V21_NOVA_API_VERSION else 'nova' for entry in catalog : if entry [ 'name' ] == nova_match or 'Compute' in entry [ 'name' ] : # Collect any endpo...
def factor_cumulative_returns ( factor_data , period , long_short = True , group_neutral = False , equal_weight = False , quantiles = None , groups = None ) : """Simulate a portfolio using the factor in input and returns the cumulative returns of the simulated portfolio Parameters factor _ data : pd . DataFra...
fwd_ret_cols = utils . get_forward_returns_columns ( factor_data . columns ) if period not in fwd_ret_cols : raise ValueError ( "Period '%s' not found" % period ) todrop = list ( fwd_ret_cols ) todrop . remove ( period ) portfolio_data = factor_data . drop ( todrop , axis = 1 ) if quantiles is not None : portfo...
def transmit_metrics ( self ) : """Keep metrics updated about how long time ago each filetype was successfully uploaded . Transmits max once per ten seconds , regardless of how many threads are running ."""
global _last_stats_transmit_time # pylint : disable = global - statement with _STATS_LOCK : # pylint : disable = not - context - manager if time . monotonic ( ) - _last_stats_transmit_time < 10.0 : return for site in self . state : for filetype , prop in self . state [ site ] [ "upload" ] . item...
def shape_factors ( n , dim = 2 ) : """Returns a : obj : ` numpy . ndarray ` of factors : samp : ` f ` such that : samp : ` ( len ( f ) = = { dim } ) and ( numpy . product ( f ) = = { n } ) ` . The returned factors are as * square * ( * cubic * , etc ) as possible . For example : : > > > shape _ factors ( 2...
if dim <= 1 : factors = [ n , ] else : for f in range ( int ( n ** ( 1.0 / float ( dim ) ) ) + 1 , 0 , - 1 ) : if ( n % f ) == 0 : factors = [ f , ] + list ( shape_factors ( n // f , dim = dim - 1 ) ) break factors . sort ( ) return _np . array ( factors )
def bsp_resize ( node : tcod . bsp . BSP , x : int , y : int , w : int , h : int ) -> None : """. . deprecated : : 2.0 Assign directly to : any : ` BSP ` attributes instead ."""
node . x = x node . y = y node . width = w node . height = h
def get_statements ( self , filter = False ) : """Return the combined list of statements from BEL and Pathway Commons . Internally calls : py : meth : ` get _ biopax _ stmts ` and : py : meth : ` get _ bel _ stmts ` . Parameters filter : bool If True , includes only those statements that exclusively menti...
bp_stmts = self . get_biopax_stmts ( filter = filter ) bel_stmts = self . get_bel_stmts ( filter = filter ) return bp_stmts + bel_stmts
def prune_dupes ( self ) : """Remove all but the last entry for a given resource URI . Returns the number of entries removed . Also removes all entries for a given URI where the first entry is a create and the last entry is a delete ."""
n = 0 pruned1 = [ ] seen = set ( ) deletes = { } for r in reversed ( self . resources ) : if ( r . uri in seen ) : n += 1 if ( r . uri in deletes ) : deletes [ r . uri ] = r . change else : pruned1 . append ( r ) seen . add ( r . uri ) if ( r . change == 'dele...