signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_access_token ( self ) : """Extract the secret and token values from the access _ token file"""
access_file = os . path . join ( self . file_path , 'access_token' ) # Ensure that the access _ token file exists if os . path . isfile ( access_file ) : # Initialise a list to store the secret and token access_list = list ( ) with open ( access_file , 'r' ) as access_token : for line in access_token : ...
def dispatch_to_awaiting ( self , result ) : """Send dat ato the appropriate queues"""
# If we are awaiting to login , then we might also get # an abort message . Handle that here . . . . if self . _state == STATE_AUTHENTICATING : # If the authentication message is something unexpected , # we ' ll just ignore it for now if result == WAMP_ABORT or result == WAMP_WELCOME or result == WAMP_GOODBYE : ...
def _or_join ( self , terms ) : """Joins terms using OR operator . Args : terms ( list ) : terms to join Examples : self . _ or _ join ( [ ' term1 ' , ' term2 ' ] ) - > ' term1 OR term2' Returns : str"""
if isinstance ( terms , ( tuple , list ) ) : if len ( terms ) > 1 : return '(' + ' OR ' . join ( terms ) + ')' else : return terms [ 0 ] else : return terms
def make_serviceitem_servicedllsignatureexists ( dll_sig_exists , condition = 'is' , negate = False ) : """Create a node for ServiceItem / serviceDLLSignatureExists : return : A IndicatorItem represented as an Element node"""
document = 'ServiceItem' search = 'ServiceItem/serviceDLLSignatureExists' content_type = 'bool' content = dll_sig_exists ii_node = ioc_api . make_indicatoritem_node ( condition , document , search , content_type , content , negate = negate ) return ii_node
def build_job ( name = None , parameters = None ) : '''Initiate a build for the provided job . : param name : The name of the job is check if it exists . : param parameters : Parameters to send to the job . : return : True is successful , otherwise raise an exception . CLI Example : . . code - block : : b...
if not name : raise SaltInvocationError ( 'Required parameter \'name\' is missing' ) server = _connect ( ) if not job_exists ( name ) : raise CommandExecutionError ( 'Job \'{0}\' does not exist.' . format ( name ) ) try : server . build_job ( name , parameters ) except jenkins . JenkinsException as err : ...
def wishart_pfaffian ( self ) : """ndarray of wishart pfaffian CDF , before normalization"""
return np . array ( [ Pfaffian ( self , val ) . value for i , val in np . ndenumerate ( self . _chisq ) ] ) . reshape ( self . _chisq . shape )
def comment_delete ( self , comment_id ) : """Remove a specific comment ( Requires login ) . Parameters : comment _ id ( int ) : The id number of the comment to remove ."""
return self . _get ( 'comments/{0}.json' . format ( comment_id ) , method = 'DELETE' , auth = True )
def ExtractEvents ( self , parser_mediator , registry_key , codepage = 'cp1252' , ** kwargs ) : """Extracts events from a Windows Registry key . Args : parser _ mediator ( ParserMediator ) : mediates interactions between parsers and other components , such as storage and dfvfs . registry _ key ( dfwinreg . ...
self . _ParseMRUListExKey ( parser_mediator , registry_key , codepage = codepage )
def to_frame ( self , data , state ) : """Extract a single frame from the data buffer . The consumed data should be removed from the buffer . If no complete frame can be read , must raise a ` ` NoFrames ` ` exception . : param data : A ` ` bytearray ` ` instance containing the data so far read . : param s...
# Find the next newline data_len = data . find ( b'\n' ) if data_len < 0 : # No line to extract raise exc . NoFrames ( ) # Track how much to exclude frame_len = data_len + 1 # Are we to exclude carriage returns ? if ( self . carriage_return and data_len and data [ data_len - 1 ] == ord ( b'\r' ) ) : data_len -=...
async def rev_regs ( self ) -> list : """Return list of revocation registry identifiers for which HolderProver has associated tails files . The operation creates associations for any ( newly copied , via service wrapper API ) tails files without . : return : list of revocation registry identifiers for which Hol...
LOGGER . debug ( 'HolderProver.rev_regs >>>' ) for path_rr_id in Tails . links ( self . _dir_tails ) : await self . _sync_revoc_for_proof ( basename ( path_rr_id ) ) rv = [ basename ( f ) for f in Tails . links ( self . _dir_tails ) ] LOGGER . debug ( 'HolderProver.rev_regs <<< %s' , rv ) return rv
def is_qualimap_compatible ( gtf ) : """Qualimap needs a very specific GTF format or it fails , so skip it if the GTF is not in that format"""
if not gtf : return False db = get_gtf_db ( gtf ) def qualimap_compatible ( feature ) : gene_id = feature . attributes . get ( 'gene_id' , [ None ] ) [ 0 ] transcript_id = feature . attributes . get ( 'transcript_id' , [ None ] ) [ 0 ] gene_biotype = feature . attributes . get ( 'gene_biotype' , [ None ...
def sparseHealpixFiles ( title , infiles , field = 'MAGLIM' , ** kwargs ) : """Inputs : field"""
# map = ugali . utils . skymap . readSparseHealpixMaps ( infiles , field ) map = ugali . utils . skymap . read_partial_map ( infiles , field ) ax = hp . mollview ( map = map , title = title , ** kwargs ) return ax , map
def name ( self ) : """Name of the resource . If conversion to unicode somehow didn ' t go well value is returned in base64 encoding ."""
return ( self . _raw_data . get ( ATTR_NAME_UNICODE ) or self . _raw_data . get ( ATTR_NAME ) or "" )
def make_even_size ( x ) : """Pad x to be even - sized on axis 1 and 2 , but only if necessary ."""
x_shape = x . get_shape ( ) . as_list ( ) assert len ( x_shape ) > 2 , "Only 3+-dimensional tensors supported." shape = [ dim if dim is not None else - 1 for dim in x_shape ] new_shape = x_shape # To make sure constant shapes remain constant . if x_shape [ 1 ] is not None : new_shape [ 1 ] = 2 * int ( math . ceil (...
def post_loader ( * decorator_args , serializer ) : """Decorator to automatically instantiate a model from json request data : param serializer : The ModelSerializer to use to load data from the request"""
def wrapped ( fn ) : @ wraps ( fn ) def decorated ( * args , ** kwargs ) : return fn ( * serializer . load ( request . get_json ( ) ) ) return decorated if decorator_args and callable ( decorator_args [ 0 ] ) : return wrapped ( decorator_args [ 0 ] ) return wrapped
def _check_for_int ( x ) : """This is a compatibility function that takes a C { float } and converts it to an C { int } if the values are equal ."""
try : y = int ( x ) except ( OverflowError , ValueError ) : pass else : # There is no way in AMF0 to distinguish between integers and floats if x == x and y == x : return y return x
def _install_nuke ( use_threaded_wrapper ) : """Helper function to The Foundry Nuke support"""
import nuke not_nuke_launch = ( "--hiero" in nuke . rawArgs or "--studio" in nuke . rawArgs or "--nukeassist" in nuke . rawArgs ) if not_nuke_launch : raise ImportError def threaded_wrapper ( func , * args , ** kwargs ) : return nuke . executeInMainThreadWithResult ( func , args , kwargs ) _common_setup ( "Nuke...
def after ( self ) : """Return a deferred that will fire after the request is finished . Returns : Deferred : a new deferred that will fire appropriately"""
d = Deferred ( ) self . _after_deferreds . append ( d ) return d . chain
def step ( self , stash = 'active' , n = None , selector_func = None , step_func = None , successor_func = None , until = None , filter_func = None , ** run_args ) : """Step a stash of states forward and categorize the successors appropriately . The parameters to this function allow you to control everything abou...
l . info ( "Stepping %s of %s" , stash , self ) # 8 < - - - - - Compatibility layer - - - - - if n is not None or until is not None : if once ( 'simgr_step_n_until' ) : print ( "\x1b[31;1mDeprecation warning: the use of `n` and `until` arguments is deprecated. " "Consider using simgr.run() with the same arg...
def bingham_pdf ( fit ) : """From the * Encyclopedia of Paleomagnetism * From Onstott , 1980: Vector resultant : R is analogous to eigenvectors of T . Eigenvalues are analogous to | R | / N ."""
# Uses eigenvectors of the covariance matrix e = fit . hyperbolic_axes # singular _ values # e = sampling _ covariance ( fit ) # not sure e = e [ 2 ] ** 2 / e kappa = ( e - e [ 2 ] ) [ : - 1 ] kappa /= kappa [ - 1 ] F = N . sqrt ( N . pi ) * confluent_hypergeometric_function ( * kappa ) ax = fit . axes Z = 1 / e M = ax...
def wait ( self , timeout = 15 ) : """block until pod is not ready , raises an exc ProbeTimeout if timeout is reached : param timeout : int or float ( seconds ) , time to wait for pod to run : return : None"""
Probe ( timeout = timeout , fnc = self . is_ready , expected_retval = True ) . run ( )
def _add_seg_to_output ( out , data , enumerate_chroms = False ) : """Export outputs to ' seg ' format compatible with IGV and GenePattern ."""
out_file = "%s.seg" % os . path . splitext ( out [ "cns" ] ) [ 0 ] if not utils . file_exists ( out_file ) : with file_transaction ( data , out_file ) as tx_out_file : cmd = [ os . path . join ( os . path . dirname ( sys . executable ) , "cnvkit.py" ) , "export" , "seg" ] if enumerate_chroms : ...
def save ( self , path , name , save_meta = True ) : '''Saves model as a sequence of files in the format : { path } / { name } _ { ' dec ' , ' disc ' , ' dec _ opt ' , ' disc _ opt ' , ' meta ' } . h5 Parameters path : str The directory of the file you wish to save the model to . name : str The name p...
_save_model ( self . dec , str ( path ) , "%s_dec" % str ( name ) ) _save_model ( self . disc , str ( path ) , "%s_disc" % str ( name ) ) _save_model ( self . dec_opt , str ( path ) , "%s_dec_opt" % str ( name ) ) _save_model ( self . disc_opt , str ( path ) , "%s_disc_opt" % str ( name ) ) if save_meta : self . _s...
from typing import List def separate_parenthesis_groups ( paren_string : str ) -> List [ str ] : """Separate groups of balanced , non - nested parentheses into separate strings . Args : paren _ string ( str ) : String containing multiple groups of nested parentheses . Returns : List [ str ] : List of separa...
# Remove spaces and initiate variables paren_string = paren_string . replace ( ' ' , '' ) balance = 0 groups = [ ] start_index = 0 # Iterate over the characters for i , char in enumerate ( paren_string ) : # Increase balance for ' ( ' and decrease for ' ) ' balance += 1 if char == '(' else - 1 # If balance beco...
def do_access_control ( self ) : """` before _ request ` handler to check if user should be redirected to login page ."""
from abilian . services import get_service if current_app . testing and current_app . config . get ( "NO_LOGIN" ) : # Special case for tests user = User . query . get ( 0 ) login_user ( user , force = True ) return state = self . app_state user = unwrap ( current_user ) # Another special case for tests if c...
def removeZeroLenPadding ( str , blocksize = AES_blocksize ) : 'Remove Padding with zeroes + last byte equal to the number of padding bytes'
try : pad_len = ord ( str [ - 1 ] ) # last byte contains number of padding bytes except TypeError : pad_len = str [ - 1 ] assert pad_len < blocksize , 'padding error' assert pad_len < len ( str ) , 'padding error' return str [ : - pad_len ]
def read ( self , size = - 1 ) : """Read data from the ring buffer into a new buffer . This advances the read index after reading ; calling : meth : ` advance _ read _ index ` is * not * necessary . : param size : The number of elements to be read . If not specified , all available elements are read . : t...
if size < 0 : size = self . read_available data = self . _ffi . new ( 'unsigned char[]' , size * self . elementsize ) size = self . readinto ( data ) return self . _ffi . buffer ( data , size * self . elementsize )
def _apply ( self , ctx : ExtensionContext ) -> Any : """Loads a yaml fragment from an external file . Args : ctx : The processing context . Returns : The external resource as a python dictionary . The fragment is already send through the processor as well ."""
_ , external_path = ctx . node return ctx . mentor . load_yaml ( self . locator ( external_path , cast ( str , ctx . document ) if Validator . is_file ( document = ctx . document ) else None ) )
def length ( value , min = None , max = None ) : """Return whether or not the length of given string is within a specified range . Examples : : > > > length ( ' something ' , min = 2) True > > > length ( ' something ' , min = 9 , max = 9) True > > > length ( ' something ' , max = 5) ValidationFailur...
if ( min is not None and min < 0 ) or ( max is not None and max < 0 ) : raise AssertionError ( '`min` and `max` need to be greater than zero.' ) return between ( len ( value ) , min = min , max = max )
def delete ( self , file_path ) : """DELETE Args : file _ path : Full path for a file you want to delete upload _ path : Ndrive path where you want to delete file ex ) / Picture / Returns : True : Delete success False : Delete failed"""
now = datetime . datetime . now ( ) . isoformat ( ) url = nurls [ 'put' ] + upload_path + file_name headers = { 'userid' : self . user_id , 'useridx' : self . useridx , 'Content-Type' : "application/x-www-form-urlencoded; charset=UTF-8" , 'charset' : 'UTF-8' , 'Origin' : 'http://ndrive2.naver.com' , } r = self . sessio...
def add_torrent_task ( self , torrent_path , save_path = '/' , selected_idx = ( ) , ** kwargs ) : """添加本地BT任务 : param torrent _ path : 本地种子的路径 : param save _ path : 远程保存路径 : param selected _ idx : 要下载的文件序号 — — 集合为空下载所有 , 非空集合指定序号集合 , 空串下载默认 : return : requests . Response . . note : : 返回正确时返回的 Reponse 对象...
# 上传种子文件 torrent_handler = open ( torrent_path , 'rb' ) basename = os . path . basename ( torrent_path ) # 清理同名文件 self . delete ( [ '/' + basename ] ) response = self . upload ( '/' , torrent_handler , basename ) . json ( ) remote_path = response [ 'path' ] logging . debug ( 'REMOTE PATH:' + remote_path ) # 获取种子信息 resp...
def get_dict_to_print ( field_to_obs ) : """Transform the field - to - obs mapping into a printable dictionary . Args : field _ to _ obs : Dict that maps string field to ` Observation ` list . Returns : A dict with the keys and values to print to console ."""
def compressed_steps ( steps ) : return { 'num_steps' : len ( set ( steps ) ) , 'min_step' : min ( steps ) , 'max_step' : max ( steps ) , 'last_step' : steps [ - 1 ] , 'first_step' : steps [ 0 ] , 'outoforder_steps' : get_out_of_order ( steps ) } def full_steps ( steps ) : return { 'steps' : steps , 'outoforder...
def get_fields ( self , strip_labels = False ) : """Hook to dynamically change the fields that will be displayed"""
if strip_labels : return [ f [ 0 ] if type ( f ) in ( tuple , list ) else f for f in self . fields ] return self . fields
def start_dut_thread ( self ) : # pylint : disable = no - self - use """Start Dut thread . : return : Nothing"""
if Dut . _th is None : Dut . _run = True Dut . _sem = Semaphore ( 0 ) Dut . _signalled_duts = deque ( ) Dut . _logger = LogManager . get_bench_logger ( 'Dut' ) Dut . _th = Thread ( target = Dut . run , name = 'DutThread' ) Dut . _th . daemon = True Dut . _th . start ( )
def isOutDated ( self , output_file ) : """Figures out if Cyther should compile the given FileInfo object by checking the both of the modified times"""
if output_file . exists ( ) : source_time = self . getmtime ( ) output_time = output_file . getmtime ( ) return source_time > output_time else : return True
def _get_stack ( self , orchestration_client , stack_name ) : """Get the ID for the current deployed overcloud stack if it exists ."""
try : stack = orchestration_client . stacks . get ( stack_name ) self . log . info ( "Stack found, will be doing a stack update" ) return stack except HTTPNotFound : self . log . info ( "No stack found, will be doing a stack create" )
def get_similarity_measures ( self ) : """Helper function for computing similarity measures ."""
if not self . quiet : print print "Computing" , self . current_similarity_measure , "similarity..." self . compute_similarity_scores ( )
def _load_hangul_syllable_types ( ) : """Helper function for parsing the contents of " HangulSyllableType . txt " from the Unicode Character Database ( UCD ) and generating a lookup table for determining whether or not a given Hangul syllable is of type " L " , " V " , " T " , " LV " or " LVT " . For more info ...
filename = "HangulSyllableType.txt" current_dir = os . path . abspath ( os . path . dirname ( __file__ ) ) with codecs . open ( os . path . join ( current_dir , filename ) , mode = "r" , encoding = "utf-8" ) as fp : for line in fp : if not line . strip ( ) or line . startswith ( "#" ) : continue...
def get_modpath ( modname , prefer_pkg = False , prefer_main = False ) : r"""Returns path to module Args : modname ( str or module ) : module name or actual module Returns : str : module _ dir CommandLine : python - m utool . util _ path - - test - get _ modpath Setup : > > > from utool . util _ pat...
import importlib if isinstance ( modname , six . string_types ) : module = importlib . import_module ( modname ) else : module = modname # Hack modpath = module . __file__ . replace ( '.pyc' , '.py' ) initname = '__init__.py' mainname = '__main__.py' if prefer_pkg : if modpath . endswith ( initname ) or...
def in_download_archive ( track ) : """Returns True if a track _ id exists in the download archive"""
global arguments if not arguments [ '--download-archive' ] : return archive_filename = arguments . get ( '--download-archive' ) try : with open ( archive_filename , 'a+' , encoding = 'utf-8' ) as file : logger . debug ( 'Contents of {0}:' . format ( archive_filename ) ) file . seek ( 0 ) ...
def StreamFilePath ( self , filepath , offset = 0 , amount = None ) : """Streams chunks of a file located at given path starting at given offset . Args : filepath : A path to the file to stream . offset : An integer offset at which the file stream should start on . amount : An upper bound on number of bytes...
with open ( filepath , "rb" ) as filedesc : for chunk in self . StreamFile ( filedesc , offset = offset , amount = amount ) : yield chunk
def find_file ( self , path , tgt_env ) : '''Find the specified file in the specified environment'''
tree = self . get_tree ( tgt_env ) if not tree : # Branch / tag / SHA not found in repo return None , None , None blob = None depth = 0 while True : depth += 1 if depth > SYMLINK_RECURSE_DEPTH : blob = None break try : file_blob = tree / path if stat . S_ISLNK ( file_blob...
def run ( self , reset_current_buffer = False , pre_run = None ) : """Read input from the command line . This runs the eventloop until a return value has been set . : param reset _ current _ buffer : XXX : Not used anymore . : param pre _ run : Callable that is called right after the reset has taken place ....
assert pre_run is None or callable ( pre_run ) try : self . _is_running = True self . on_start . fire ( ) self . reset ( ) # Call pre _ run . self . _pre_run ( pre_run ) # Run eventloop in raw mode . with self . input . raw_mode ( ) : self . renderer . request_absolute_cursor_positio...
def convert_md_to_rst ( source , destination = None , backup_dir = None ) : """Try to convert the source , an . md ( markdown ) file , to an . rst ( reStructuredText ) file at the destination . If the destination isn ' t provided , it defaults to be the same as the source path except for the filename extensio...
# Doing this in the function instead of the module level ensures the # error occurs when the function is called , rather than when the module # is evaluated . try : import pypandoc except ImportError : # Don ' t give up right away ; first try to install the python module . os . system ( "pip install pypandoc" )...
def altitude ( msg ) : """Decode aircraft altitude Args : msg ( string ) : 28 bytes hexadecimal message string Returns : int : altitude in feet"""
tc = common . typecode ( msg ) if tc < 9 or tc == 19 or tc > 22 : raise RuntimeError ( "%s: Not a airborn position message" % msg ) mb = common . hex2bin ( msg ) [ 32 : ] if tc < 19 : # barometric altitude q = mb [ 15 ] if q : n = common . bin2int ( mb [ 8 : 15 ] + mb [ 16 : 20 ] ) alt = n *...
def get_subdomain_history ( self , fqn , start_sequence = None , end_sequence = None , start_zonefile_index = None , end_zonefile_index = None , include_unaccepted = False , offset = None , count = None , cur = None ) : """Get the subdomain ' s history over a block range . By default , only include accepted histo...
sql = 'SELECT * FROM {} WHERE fully_qualified_subdomain = ? {} {} {} {} {} ORDER BY parent_zonefile_index ASC' . format ( self . subdomain_table , 'AND accepted=1' if not include_unaccepted else '' , 'AND parent_zonefile_index >= ?' if start_zonefile_index is not None else '' , 'AND parent_zonefile_index < ?' if end_zo...
def create_model ( model_name : Optional [ str ] , params : ModelParams ) -> 'Sequential' : """Load or create a precise model Args : model _ name : Name of model params : Parameters used to create the model Returns : model : Loaded Keras model"""
if model_name and isfile ( model_name ) : print ( 'Loading from ' + model_name + '...' ) model = load_precise_model ( model_name ) else : from keras . layers . core import Dense from keras . layers . recurrent import GRU from keras . models import Sequential model = Sequential ( ) model . ad...
def _execute_callback ( async , callback ) : """Execute the given callback or insert the Async callback , or if no callback is given return the async . result ."""
from furious . async import Async if not callback : return async . result . payload if isinstance ( callback , Async ) : return callback . start ( ) return callback ( )
def get_transactions ( self ) : """Fetches transaction history . : rtype : ` ` list ` ` of ` ` str ` ` transaction IDs"""
self . transactions [ : ] = NetworkAPI . get_transactions ( self . address ) if self . segwit_address : self . transactions += NetworkAPI . get_transactions ( self . segwit_address ) return self . transactions
def sense ( self ) : """Return a situation , encoded as a bit string , which represents the observable state of the environment . Usage : situation = scenario . sense ( ) assert isinstance ( situation , BitString ) Arguments : None Return : The current situation ."""
self . current_situation = bitstrings . BitString ( [ random . randrange ( 2 ) for _ in range ( self . address_size + ( 1 << self . address_size ) ) ] ) return self . current_situation
def p_iteration_statement_2 ( self , p ) : """iteration _ statement : WHILE LPAREN expr RPAREN statement"""
p [ 0 ] = ast . While ( predicate = p [ 3 ] , statement = p [ 5 ] )
def normalizeFeatureText ( value ) : """Normalizes feature text . * * * value * * must be a : ref : ` type - string ` . * Returned value will be an unencoded ` ` unicode ` ` string ."""
if not isinstance ( value , basestring ) : raise TypeError ( "Feature text must be a string, not %s." % type ( value ) . __name__ ) return unicode ( value )
def get_immediate_children ( self ) : """Return all direct subsidiaries of this company . Excludes subsidiaries of subsidiaries"""
ownership = Ownership . objects . filter ( parent = self ) subsidiaries = Company . objects . filter ( child__in = ownership ) . distinct ( ) return subsidiaries
def importcsv ( self ) : '''import data from csv'''
csv_path = os . path . join ( os . path . dirname ( __file__ ) , self . stock_no_files ) with open ( csv_path ) as csv_file : csv_data = csv . reader ( csv_file ) result = { } for i in csv_data : try : result [ i [ 0 ] ] = str ( i [ 1 ] ) . decode ( 'utf-8' ) except ValueError : ...
def is_owner ( package , abspath ) : """Determine whether ` abspath ` belongs to ` package ` ."""
try : files = package [ 'files' ] location = package [ 'location' ] except KeyError : return False paths = ( os . path . abspath ( os . path . join ( location , f ) ) for f in files ) return abspath in paths
def get_outputs_by_public_key ( self , public_key ) : """Get outputs for a public key"""
txs = list ( query . get_owned_ids ( self . connection , public_key ) ) return [ TransactionLink ( tx [ 'id' ] , index ) for tx in txs for index , output in enumerate ( tx [ 'outputs' ] ) if condition_details_has_owner ( output [ 'condition' ] [ 'details' ] , public_key ) ]
def number_of_extents ( self ) : """int : number of extents ."""
if not self . _is_parsed : self . _Parse ( ) self . _is_parsed = True return len ( self . _extents )
def output ( data , ** kwargs ) : '''Display the profiling data in a table format .'''
rows = _find_durations ( data ) kwargs [ 'opts' ] = __opts__ kwargs [ 'rows_key' ] = 'rows' kwargs [ 'labels_key' ] = 'labels' to_show = { 'labels' : [ 'name' , 'mod.fun' , 'duration (ms)' ] , 'rows' : rows } return table_out . output ( to_show , ** kwargs )
def GET ( self ) : """Show page"""
todos = model . get_todos ( ) form = self . form ( ) return render . index ( todos , form )
def _mount_avfs ( self ) : """Mounts the AVFS filesystem ."""
self . _paths [ 'avfs' ] = tempfile . mkdtemp ( prefix = 'image_mounter_avfs_' ) # start by calling the mountavfs command to initialize avfs _util . check_call_ ( [ 'avfsd' , self . _paths [ 'avfs' ] , '-o' , 'allow_other' ] , stdout = subprocess . PIPE ) # no multifile support for avfs avfspath = self . _paths [ 'avfs...
def compile_ir ( engine , llvm_ir ) : """Compile the LLVM IR string with the given engine . The compiled module object is returned ."""
# Create a LLVM module object from the IR mod = llvm . parse_assembly ( llvm_ir ) mod . verify ( ) # Now add the module and make sure it is ready for execution engine . add_module ( mod ) engine . finalize_object ( ) engine . run_static_constructors ( ) return mod
def types ( self ) : '''Returns an iterator over the types of the neurites in the object . If the object is a tree , then one value is returned .'''
neurites = self . _obj . neurites if hasattr ( self . _obj , 'neurites' ) else ( self . _obj , ) return ( neu . type for neu in neurites )
def move_file_to_file ( old_path , new_path ) : """Moves file from old location to new one : param old _ path : path of file to move : param new _ path : new path"""
try : os . rename ( old_path , new_path ) except : old_file = os . path . basename ( old_path ) target_directory , target_file = os . path . dirname ( os . path . abspath ( new_path ) ) , os . path . basename ( new_path ) Document . move_file_to_directory ( old_path , target_directory ) # move old f...
def create_node ( manager , name , meta_type_label , type_label , handle_id , legacy = True ) : """Creates a node with the mandatory attributes name and handle _ id also sets type label . : param manager : Manager to handle sessions and transactions : param name : Node name : param meta _ type _ label : Node ...
if meta_type_label not in META_TYPES : raise exceptions . MetaLabelNamingError ( meta_type_label ) q = """ CREATE (n:Node:%s:%s { name: { name }, handle_id: { handle_id }}) RETURN n """ % ( meta_type_label , type_label ) with manager . session as s : if legacy : return s . run ( ...
def set_ticks ( self , max_xticks = _NTICKS , max_yticks = _NTICKS , fontsize = _FONTSIZE ) : """Set and control tick behavior Parameters max _ xticks , max _ yticks : int , optional Maximum number of labeled ticks to plot on x , y axes fontsize : string or int Font size as used by matplotlib text Retur...
from matplotlib . ticker import MaxNLocator # Both are necessary x_major_locator = MaxNLocator ( nbins = max_xticks ) y_major_locator = MaxNLocator ( nbins = max_yticks ) for ax in self . axes . flat : ax . xaxis . set_major_locator ( x_major_locator ) ax . yaxis . set_major_locator ( y_major_locator ) for ...
def json_load_object_hook ( dct ) : """Hook for json . parse ( . . . ) to parse Xero date formats ."""
for key , value in dct . items ( ) : if isinstance ( value , six . string_types ) : value = parse_date ( value ) if value : dct [ key ] = value return dct
def resolve_path ( path , expected = None , multi_projects = False , allow_empty_string = True ) : ''': param path : A path to a data object to attempt to resolve : type path : string : param expected : one of the following : " folder " , " entity " , or None to indicate whether the expected path is a folder ...
# TODO : callers that intend to obtain a data object probably won ' t be happy # with an app or execution ID . Callers should probably have to specify # whether they are okay with getting an execution ID or not . # TODO : callers that are looking for a place to write data , rather than # read it , probably won ' t be h...
def update ( self , settings ) : '''updates the internal dictionary Args : settings : parameters to be set # mabe in the future : # Returns : boolean that is true if update successful'''
if 'settings' in settings : self . _settings . update ( settings [ 'settings' ] ) else : self . _settings . update ( settings ) if 'instruments' in settings : for instrument_name , instrument_setting in settings [ 'instruments' ] . items ( ) : self . instruments [ instrument_name ] [ 'settings' ] . ...
def choose_ancestral_states_mppa ( tree , feature , states , force_joint = True ) : """Chooses node ancestral states based on their marginal probabilities using MPPA method . : param force _ joint : make sure that Joint state is chosen even if it has a low probability . : type force _ joint : bool : param tre...
lh_feature = get_personalized_feature_name ( feature , LH ) allowed_state_feature = get_personalized_feature_name ( feature , ALLOWED_STATES ) joint_state_feature = get_personalized_feature_name ( feature , JOINT_STATE ) n = len ( states ) _ , state2array = get_state2allowed_states ( states , False ) num_scenarios = 1 ...
def process_IN_CREATE ( self , raw_event ) : """If the event affects a directory and the auto _ add flag of the targetted watch is set to True , a new watch is added on this new directory , with the same attribute values than those of this watch ."""
if raw_event . mask & IN_ISDIR : watch_ = self . _watch_manager . get_watch ( raw_event . wd ) created_dir = os . path . join ( watch_ . path , raw_event . name ) if watch_ . auto_add and not watch_ . exclude_filter ( created_dir ) : addw = self . _watch_manager . add_watch # The newly monit...
def unmarshal ( self , v ) : """Convert the value from Strava API format to useful python representation . If the value does not appear in the choices attribute we log an error rather than raising an exception as this may be caused by a change to the API upstream so we want to fail gracefully ."""
try : return self . choices [ v ] except KeyError : self . log . warning ( "No such choice {0} for field {1}." . format ( v , self ) ) # Just return the value from the API return v
def list_media_endpoint_keys ( access_token , subscription_id , rgname , msname ) : '''list the media endpoint keys in a media service Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . rgname ( str ) : Azure resource group name . msnam...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , rgname , '/providers/microsoft.media/' , '/mediaservices/' , msname , '/listKeys?api-version=' , MEDIA_API ] ) return do_get ( endpoint , access_token )
def get_interpolated_value ( self , energy ) : """Returns interpolated density for a particular energy . Args : energy : Energy to return the density for ."""
f = { } for spin in self . densities . keys ( ) : f [ spin ] = get_linear_interpolated_value ( self . energies , self . densities [ spin ] , energy ) return f
def DefaultAdapter ( self ) : '''Retrieve the default adapter'''
default_adapter = None for obj in mockobject . objects . keys ( ) : if obj . startswith ( '/org/bluez/' ) and 'dev_' not in obj : default_adapter = obj if default_adapter : return dbus . ObjectPath ( default_adapter , variant_level = 1 ) else : raise dbus . exceptions . DBusException ( 'No such adap...
def _set_qsfp ( self , v , load = False ) : """Setter method for qsfp , mapped from YANG variable / brocade _ interface _ ext _ rpc / get _ media _ detail / output / interface / qsfp ( container ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ qsfp is considered as a p...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = qsfp . qsfp , is_container = 'container' , presence = False , yang_name = "qsfp" , rest_name = "qsfp" , parent = self , choice = ( u'interface-identifier' , u'qsfp' ) , path_helper = self . _path_helper , extmethods = self . ...
def value ( self , value ) : """Used to set the ` ` value ` ` of form elements ."""
self . client . nowait ( 'set_field' , ( Literal ( 'browser' ) , self . element , value ) )
def match_operators ( inp , relate , cut ) : """Compare two items . Match a string operator to an operator function : param str inp : Comparison item : param str relate : Comparison operator : param any cut : Comparison item : return bool truth : Comparison truth"""
logger_misc . info ( "enter match_operators" ) ops = { '>' : operator . gt , '<' : operator . lt , '>=' : operator . ge , '<=' : operator . le , '=' : operator . eq } try : truth = ops [ relate ] ( inp , cut ) except KeyError as e : truth = False logger_misc . warn ( "get_truth: KeyError: Invalid operator i...
def connect_any_signal_changed ( self , function ) : """Connects the " anything changed " signal for all of the tree to the specified function . Parameters function Function to connect to this signal ."""
# loop over all top level parameters for i in range ( self . _widget . topLevelItemCount ( ) ) : # make sure there is only one connection ! try : self . _widget . topLevelItem ( i ) . param . sigTreeStateChanged . connect ( function , type = _g . QtCore . Qt . UniqueConnection ) except : pass re...
def parse_url_rules ( urls_fp ) : """URL rules from given fp"""
url_rules = [ ] for line in urls_fp : re_url = line . strip ( ) if re_url : url_rules . append ( { 'str' : re_url , 're' : re . compile ( re_url ) } ) return url_rules
def extract_references_from_wets ( wet_files , metadata_dir , out_dir , tmp_dir = None ) : """Extract references from WET files into sharded output files ."""
# Setup output files shard_files = make_ref_shard_files ( out_dir ) num_refs = 0 for i , wet_file in enumerate ( wet_files ) : num_refs_in_wet = 0 tf . logging . info ( "Processing file %d" , i ) # Read metadata file metadata_fname = os . path . join ( metadata_dir , os . path . basename ( wet_file ) ) ...
def acquire_for ( pid_dir , num_available = 1 , kill_signal = None ) : """Makes sure the process is only run once at the same time with the same name . Notice that we since we check the process name , different parameters to the same command can spawn multiple processes at the same time , i . e . running " / ...
my_pid , my_cmd , pid_file = get_info ( pid_dir ) # Create a pid file if it does not exist try : os . mkdir ( pid_dir ) os . chmod ( pid_dir , 0o777 ) except OSError as exc : if exc . errno != errno . EEXIST : raise pass # Let variable " pids " be all pids who exist in the . pid - file who are s...
def is_leap ( year ) : """Leap year or not in the Gregorian calendar ."""
x = math . fmod ( year , 4 ) y = math . fmod ( year , 100 ) z = math . fmod ( year , 400 ) # Divisible by 4 and , # either not divisible by 100 or divisible by 400. return not x and ( y or not z )
def _move_to_top ( self , pos ) : """Move element at given position to top of queue ."""
if pos > 0 : self . queue . rotate ( - pos ) item = self . queue . popleft ( ) self . queue . rotate ( pos ) self . queue . appendleft ( item )
def make_summaries ( self ) : """Make and save summary csv files , each containing values from all cells"""
self . summary_df = save_summaries ( self . frames , self . keys , self . selected_summaries , self . batch_dir , self . name ) logger . debug ( "made and saved summaries" )
def save ( self , * args , ** kwargs ) : """The save method should create a new OrganizationUser linking the User matching the provided email address . If not matching User is found it should kick off the registration process . It needs to create a User in order to link it to the Organization ."""
try : user = get_user_model ( ) . objects . get ( email__iexact = self . cleaned_data [ "email" ] ) except get_user_model ( ) . MultipleObjectsReturned : raise forms . ValidationError ( _ ( "This email address has been used multiple times." ) ) except get_user_model ( ) . DoesNotExist : user = invitation_ba...
def command_x ( self , x , to = None ) : """Sends a character to the currently active element with Command pressed . This method takes care of pressing and releasing Command ."""
if to is None : ActionChains ( self . driver ) . send_keys ( [ Keys . COMMAND , x , Keys . COMMAND ] ) . perform ( ) else : self . send_keys ( to , [ Keys . COMMAND , x , Keys . COMMAND ] )
def gps2dt ( gps_week , gps_ms ) : """Convert GPS week and ms to a datetime"""
gps_epoch = datetime ( 1980 , 1 , 6 , 0 , 0 , 0 ) gps_week_s = timedelta ( seconds = gps_week * 7 * 24 * 60 * 60 ) gps_ms_s = timedelta ( milliseconds = gps_ms ) return gps_epoch + gps_week_s + gps_ms_s
def get_vm ( access_token , subscription_id , resource_group , vm_name ) : '''Get virtual machine details . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . resource _ group ( str ) : Azure resource group name . vm _ name ( str ) : Na...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/resourceGroups/' , resource_group , '/providers/Microsoft.Compute/virtualMachines/' , vm_name , '?api-version=' , COMP_API ] ) return do_get ( endpoint , access_token )
def clear_cache ( self ) : """Clear the TTS cache , removing all cache files from disk . . . versionadded : : 1.6.0"""
if self . use_cache : self . log ( u"Requested to clear TTS cache" ) self . cache . clear ( )
def _get_valididty ( self ) : """Determines whether this AD Group is valid . : returns : True and " " if this group is valid or False and a string description with the reason why it isn ' t valid otherwise ."""
try : self . ldap_connection . search ( search_base = self . VALID_GROUP_TEST [ 'base_dn' ] , search_filter = self . VALID_GROUP_TEST [ 'filter_string' ] , search_scope = self . VALID_GROUP_TEST [ 'scope' ] , attributes = self . VALID_GROUP_TEST [ 'attribute_list' ] ) except LDAPOperationsErrorResult as error_messa...
def _insert_tasks ( tasks , queue , transactional = False , retry_transient_errors = True , retry_delay = RETRY_SLEEP_SECS ) : """Insert a batch of tasks into the specified queue . If an error occurs during insertion , split the batch and retry until they are successfully inserted . Return the number of success...
from google . appengine . api import taskqueue if not tasks : return 0 try : taskqueue . Queue ( name = queue ) . add ( tasks , transactional = transactional ) return len ( tasks ) except ( taskqueue . BadTaskStateError , taskqueue . TaskAlreadyExistsError , taskqueue . TombstonedTaskError ) : if len ( ...
def create_hitor_calibration ( output_filename , plot_pixel_calibrations = False ) : '''Generating HitOr calibration file ( _ calibration . h5 ) from raw data file and plotting of calibration data . Parameters output _ filename : string Input raw data file name . plot _ pixel _ calibrations : bool , iterabl...
logging . info ( 'Analyze HitOR calibration data and plot results of %s' , output_filename ) with AnalyzeRawData ( raw_data_file = output_filename , create_pdf = True ) as analyze_raw_data : # Interpret the raw data file analyze_raw_data . create_occupancy_hist = False # too many scan parameters to do in ram hi...
def mod_division_by_lists ( list1 , list2 ) : """A function to perform element - wise modulo division of two lists and returns a list of the results using map and lambda function . > > > mod _ division _ by _ lists ( [ 4 , 5 , 6 ] , [ 1 , 2 , 3 ] ) [0 , 1 , 0] > > > mod _ division _ by _ lists ( [ 3 , 2 ] , [...
resultant_modulus = map ( ( lambda x , y : x % y ) , list1 , list2 ) return list ( resultant_modulus )
def list_qos_policies ( self , retrieve_all = True , ** _params ) : """Fetches a list of all qos policies for a project ."""
# Pass filters in " params " argument to do _ request return self . list ( 'policies' , self . qos_policies_path , retrieve_all , ** _params )
def _load_attributes ( self , mft_config , attrs_view ) : '''Loads all the attributes of an entry . Once executed , all the attributes should have been loaded in the attribute * attrs * instance attribute . Args : mft _ config ( : obj : ` MFTConfig ` ) - An instance of MFTConfig , as this tells how the li...
offset = 0 load_attrs = mft_config . attribute_load_list while ( attrs_view [ offset : offset + 4 ] != b'\xff\xff\xff\xff' ) : attr_type , attr_len , non_resident = _get_attr_info ( attrs_view [ offset : ] ) if attr_type in load_attrs : # pass all the information to the attr , as we don ' t know how # much ...
def ini_dump_hook ( cfg , text : bool = False ) : """Dumps all the data into a INI file . This will automatically kill anything with a ' _ ' in the keyname , replacing it with a dot . You have been warned ."""
data = cfg . config . dump ( ) # Load data back into the goddamned ini file . ndict = { } for key , item in data . items ( ) : key = key . replace ( '_' , '.' ) ndict [ key ] = item cfg . tmpini = configparser . ConfigParser ( ) cfg . tmpini . read_dict ( data ) if not text : cfg . tmpini . write ( cfg . fd...
def contrib_phone ( contrib_tag ) : """Given a contrib tag , look for an phone tag"""
phone = None if raw_parser . phone ( contrib_tag ) : phone = first ( raw_parser . phone ( contrib_tag ) ) . text return phone
def add_prefix ( self , name , stmt ) : """Return ` name ` prepended with correct prefix . If the name is already prefixed , the prefix may be translated to the value obtained from ` self . module _ prefixes ` . Unmodified ` name ` is returned if we are inside a global grouping ."""
if self . gg_level : return name pref , colon , local = name . partition ( ":" ) if colon : return ( self . module_prefixes [ stmt . i_module . i_prefixes [ pref ] [ 0 ] ] + ":" + local ) else : return self . prefix_stack [ - 1 ] + ":" + pref
def value_to_bytes ( self , obj , value , default_endianness = DEFAULT_ENDIANNESS ) : """Converts the given value to an appropriately encoded string of bytes that represents it . : param obj : The parent : class : ` . PebblePacket ` of this field : type obj : . PebblePacket : param value : The python value to...
return struct . pack ( str ( self . endianness or default_endianness ) + self . struct_format , value )
def Deserialize ( self , reader ) : """Read serialized data from byte stream Args : reader ( neocore . IO . BinaryReader ) : reader to read byte data from"""
self . name = reader . ReadVarString ( ) . decode ( 'utf-8' ) self . symbol = reader . ReadVarString ( ) . decode ( 'utf-8' ) self . decimals = reader . ReadUInt8 ( )