signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def remove_node ( node_id = str , force = bool ) : '''Remove a node from a swarm and the target needs to be a swarm manager node _ id The node id from the return of swarm . node _ ls force Forcefully remove the node / minion from the service CLI Example : . . code - block : : bash salt ' * ' swarm . r...
client = docker . APIClient ( base_url = 'unix://var/run/docker.sock' ) try : if force == 'True' : service = client . remove_node ( node_id , force = True ) return service else : service = client . remove_node ( node_id , force = False ) return service except TypeError : salt...
def logoff ( self ) : """Send a logoff request . : rtype : bool"""
self . send ( C1218LogoffRequest ( ) ) data = self . recv ( ) if data == b'\x00' : self . _initialized = False return True return False
def change_site ( self , new_name , new_location = None , new_er_data = None , new_pmag_data = None , replace_data = False ) : """Update a site ' s name , location , er _ data , and pmag _ data . By default , new data will be added in to pre - existing data , overwriting existing values . If replace _ data is T...
self . name = new_name if new_location : self . location = new_location self . update_data ( new_er_data , new_pmag_data , replace_data )
def gpu_iuwt_recomposition ( in1 , scale_adjust , store_on_gpu , smoothed_array ) : """This function calls the a trous algorithm code to recompose the input into a single array . This is the implementation of the isotropic undecimated wavelet transform recomposition for a GPU . INPUTS : in1 ( no default ) : A...
wavelet_filter = ( 1. / 16 ) * np . array ( [ 1 , 4 , 6 , 4 , 1 ] , dtype = np . float32 ) # Filter - bank for use in the a trous algorithm . wavelet_filter = gpuarray . to_gpu_async ( wavelet_filter ) # Determines scale with adjustment and creates a zero array on the GPU to store the output , unless smoothed _ array #...
def get_agent_sock_path ( env = None , sp = subprocess ) : """Parse gpgconf output to find out GPG agent UNIX socket path ."""
args = [ util . which ( 'gpgconf' ) , '--list-dirs' ] output = check_output ( args = args , env = env , sp = sp ) lines = output . strip ( ) . split ( b'\n' ) dirs = dict ( line . split ( b':' , 1 ) for line in lines ) log . debug ( '%s: %s' , args , dirs ) return dirs [ b'agent-socket' ]
def purge_archives ( self ) : """Delete older archived items . Use the class attribute NUM _ KEEP _ ARCHIVED to control how many items are kept ."""
klass = self . get_version_class ( ) qs = klass . normal . filter ( object_id = self . object_id , state = self . ARCHIVED ) . order_by ( '-last_save' ) [ self . NUM_KEEP_ARCHIVED : ] for obj in qs : obj . _delete_reverses ( ) klass . normal . filter ( vid = obj . vid ) . delete ( )
def save ( self ) : """Called by the parent settings dialog when the user clicks on the Save button . Stores the current settings in the ConfigManager ."""
logger . debug ( "User requested to save settings. New settings: " + self . _settings_str ( ) ) cm . ConfigManager . SETTINGS [ cm . PROMPT_TO_SAVE ] = not self . autosave_checkbox . isChecked ( ) cm . ConfigManager . SETTINGS [ cm . SHOW_TRAY_ICON ] = self . show_tray_checkbox . isChecked ( ) # cm . ConfigManager . SE...
def buffer ( self , geometries , inSR , distances , units , outSR = None , bufferSR = None , unionResults = True , geodesic = True ) : """The buffer operation is performed on a geometry service resource The result of this operation is buffered polygons at the specified distances for the input geometry array . O...
url = self . _url + "/buffer" params = { "f" : "json" , "inSR" : inSR , "geodesic" : geodesic , "unionResults" : unionResults } if isinstance ( geometries , list ) and len ( geometries ) > 0 : g = geometries [ 0 ] if isinstance ( g , Polygon ) : params [ 'geometries' ] = { "geometryType" : "esriGeometry...
def format_item ( format_spec , item , defaults = None ) : """Format an item according to the given output format . The format can be gioven as either an interpolation string , or a Tempita template ( which has to start with " E { lb } E { lb } " ) , @ param format _ spec : The output format . @ param item ...
template_engine = getattr ( format_spec , "__engine__" , None ) # TODO : Make differences between engines transparent if template_engine == "tempita" or ( not template_engine and format_spec . startswith ( "{{" ) ) : # Set item , or field names for column titles namespace = dict ( headers = not bool ( item ) ) ...
def traverseItems ( self , mode = TraverseMode . DepthFirst , parent = None ) : """Generates a tree iterator that will traverse the items of this tree in either a depth - first or breadth - first fashion . : param mode | < XTreeWidget . TraverseMode > recurse | < bool > : return < generator >"""
try : if parent : count = parent . childCount ( ) func = parent . child else : count = self . topLevelItemCount ( ) func = self . topLevelItem except RuntimeError : # can be raised when iterating on a deleted tree widget . return next = [ ] for i in range ( count ) : try ...
def musixmatch ( song ) : """Returns the lyrics found in musixmatch for the specified mp3 file or an empty string if not found ."""
escape = re . sub ( "'-¡¿" , '' , URLESCAPE ) translate = { escape : '' , ' ' : '-' } artist = song . artist . title ( ) artist = re . sub ( r"( '|' )" , '' , artist ) artist = re . sub ( r"'" , '-' , artist ) title = song . title title = re . sub ( r"( '|' )" , '' , title ) title = re . sub ( r"'" , '-' , title ) arti...
def _compress ( self , data , operation ) : """This private method compresses some data in a given mode . This is used because almost all of the code uses the exact same setup . It wouldn ' t have to , but it doesn ' t hurt at all ."""
# The ' algorithm ' for working out how big to make this buffer is from # the Brotli source code , brotlimodule . cc . original_output_size = int ( math . ceil ( len ( data ) + ( len ( data ) >> 2 ) + 10240 ) ) available_out = ffi . new ( "size_t *" ) available_out [ 0 ] = original_output_size output_buffer = ffi . new...
def split_sources ( srcs ) : """: param srcs : sources : returns : a pair ( split sources , split time ) or just the split _ sources"""
from openquake . hazardlib . source import splittable sources = [ ] split_time = { } # src . id - > time for src in srcs : t0 = time . time ( ) mag_a , mag_b = src . get_min_max_mag ( ) min_mag = src . min_mag if mag_b < min_mag : # discard the source completely continue has_serial = hasattr...
def has_equal_value ( state , ordered = False , ndigits = None , incorrect_msg = None ) : """Verify if a student and solution query result match up . This function must always be used after ' zooming ' in on certain columns or records ( check _ column , check _ row or check _ result ) . ` ` has _ equal _ value ...
if not hasattr ( state , "parent" ) : raise ValueError ( "You can only use has_equal_value() on the state resulting from check_column, check_row or check_result." ) if incorrect_msg is None : incorrect_msg = "Column `{{col}}` seems to be incorrect.{{' Make sure you arranged the rows correctly.' if ordered else ...
def get_fieldsets ( self , request , obj = None ) : """Add fieldsets of placeholders to the list of already existing fieldsets ."""
# some ugly business to remove freeze _ date # from the field list general_module = { 'fields' : list ( self . general_fields ) , 'classes' : ( 'module-general' , ) , } default_fieldsets = list ( self . fieldsets ) if not request . user . has_perm ( 'pages.can_freeze' ) : general_module [ 'fields' ] . remove ( 'fre...
def create_zip_dir ( zipfile_path , * file_list ) : """This function creates a zipfile located in zipFilePath with the files in the file list # fileList can be both a comma separated list or an array"""
try : if isinstance ( file_list , ( list , tuple ) ) : # unfolding list of list or tuple if len ( file_list ) == 1 : if isinstance ( file_list [ 0 ] , ( list , tuple ) ) : file_list = file_list [ 0 ] # converting string to iterable list if isinstance ( file_list , str ) :...
def _handle_skip_feature ( self , test_dict ) : """handle skip feature for test - skip : skip current test unconditionally - skipIf : skip current test if condition is true - skipUnless : skip current test unless condition is true Args : test _ dict ( dict ) : test info Raises : SkipTest : skip test""...
# TODO : move skip to initialize skip_reason = None if "skip" in test_dict : skip_reason = test_dict [ "skip" ] elif "skipIf" in test_dict : skip_if_condition = test_dict [ "skipIf" ] if self . session_context . eval_content ( skip_if_condition ) : skip_reason = "{} evaluate to True" . format ( skip...
def append ( self , func , * args , ** kwargs ) : """add a task to the chain takes the same parameters as async _ task ( )"""
self . chain . append ( ( func , args , kwargs ) ) # remove existing results if self . started : delete_group ( self . group ) self . started = False return self . length ( )
def del_doc ( self , doc ) : """Delete a document"""
if not self . index_writer : self . index_writer = self . index . writer ( ) if not self . label_guesser_updater : self . label_guesser_updater = self . label_guesser . get_updater ( ) logger . info ( "Removing doc from the index: %s" % doc ) if doc . docid in self . _docs_by_id : self . _docs_by_id . pop (...
def decode_run_length ( run_length_list ) : """Function to decode a given list encoded with run - length encoding . Here run - length encoding means : [ N , E ] represents N occurrences of element E . If an element is not in such run - length format , it means this element appears once . Examples : decode _...
decoded_list = [ ] for element in run_length_list : if type ( element ) is list : decoded_list . extend ( [ element [ 1 ] ] * element [ 0 ] ) else : decoded_list . append ( element ) return decoded_list
def __directory_list_descriptor ( self , configs ) : """Builds a directory list for an API . Args : configs : List of dicts containing the service configurations to list . Returns : A dictionary that can be deserialized into JSON in discovery list format . Raises : ApiConfigurationError : If there ' s s...
descriptor = { 'kind' : 'discovery#directoryList' , 'discoveryVersion' : 'v1' , } items = [ ] for config in configs : item_descriptor = self . __item_descriptor ( config ) if item_descriptor : items . append ( item_descriptor ) if items : descriptor [ 'items' ] = items return descriptor
def get ( self , section , option , * args ) : """Get option value from section . If an option is secure , populates the plain text ."""
if self . is_secure_option ( section , option ) and self . keyring_available : s_option = "%s%s" % ( section , option ) if self . _unsaved . get ( s_option , [ '' ] ) [ 0 ] == 'set' : res = self . _unsaved [ s_option ] [ 1 ] else : res = keyring . get_password ( self . keyring_name , s_optio...
def raw_order_book ( self , pair , prec = None , ** kwargs ) : """Subscribe to the passed pair ' s raw order book channel . : param pair : str , Pair to request data for . : param kwargs : : return :"""
prec = 'R0' if prec is None else prec self . _subscribe ( 'book' , pair = pair , prec = prec , ** kwargs )
def windchill ( temperature , speed , face_level_winds = False , mask_undefined = True ) : r"""Calculate the Wind Chill Temperature Index ( WCTI ) . Calculates WCTI from the current temperature and wind speed using the formula outlined by the FCM [ FCMR192003 ] _ . Specifically , these formulas assume that wi...
# Correct for lower height measurement of winds if necessary if face_level_winds : # No in - place so that we copy # noinspection PyAugmentAssignment speed = speed * 1.5 temp_limit , speed_limit = 10. * units . degC , 3 * units . mph speed_factor = speed . to ( 'km/hr' ) . magnitude ** 0.16 wcti = units . Quantity ...
def ext_pillar ( minion_id , pillar , # pylint : disable = W0613 use_grain = False , minion_ids = None , tag_match_key = None , tag_match_value = 'asis' , tag_list_key = None , tag_list_sep = ';' ) : '''Execute a command and read the output as YAML'''
valid_tag_match_value = [ 'uqdn' , 'asis' ] # meta - data : instance - id grain_instance_id = __grains__ . get ( 'meta-data' , { } ) . get ( 'instance-id' , None ) if not grain_instance_id : # dynamic : instance - identity : document : instanceId grain_instance_id = __grains__ . get ( 'dynamic' , { } ) . get ( 'ins...
def follow_link ( self , link = None , * args , ** kwargs ) : """Follow a link . If ` ` link ` ` is a bs4 . element . Tag ( i . e . from a previous call to : func : ` links ` or : func : ` find _ link ` ) , then follow the link . If ` ` link ` ` doesn ' t have a * href * - attribute or is None , treat ` ` l...
link = self . _find_link_internal ( link , args , kwargs ) referer = self . get_url ( ) headers = { 'Referer' : referer } if referer else None return self . open_relative ( link [ 'href' ] , headers = headers )
def SetSerializersProfiler ( self , serializers_profiler ) : """Sets the serializers profiler . Args : serializers _ profiler ( SerializersProfiler ) : serializers profiler ."""
self . _serializers_profiler = serializers_profiler if self . _storage_file : self . _storage_file . SetSerializersProfiler ( serializers_profiler )
def _nextNonSpaceColumn ( block , column ) : """Returns the column with a non - whitespace characters starting at the given cursor position and searching forwards ."""
textAfter = block . text ( ) [ column : ] if textAfter . strip ( ) : spaceLen = len ( textAfter ) - len ( textAfter . lstrip ( ) ) return column + spaceLen else : return - 1
def get_network ( families = [ socket . AF_INET ] ) : """# > > > from psutil . _ common import snic > > > import mock > > > from collections import namedtuple > > > snic = namedtuple ( ' snic ' , [ ' family ' , ' address ' , ' netmask ' , ' broadcast ' , ' ptp ' ] ) > > > MOCK = { . . . " awdl0 " : [ snic...
nic = psutil . net_if_addrs ( ) ips = defaultdict ( list ) # return nic for card , addresses in nic . items ( ) : for address in addresses : if address . family in families : ips [ card ] . append ( "{0.address}/{0.netmask}" . format ( address ) ) return dict ( ips )
def sample ( self , n ) : """Samples data into a Pandas DataFrame . Note that it calls BigQuery so it will incur cost . Args : n : number of sampled counts . Note that the number of counts returned is approximated . Returns : A dataframe containing sampled data . Raises : Exception if n is larger than...
total = bq . Query ( 'select count(*) from %s' % self . _get_source ( ) ) . execute ( ) . result ( ) [ 0 ] . values ( ) [ 0 ] if n > total : raise ValueError ( 'sample larger than population' ) sampling = bq . Sampling . random ( percent = n * 100.0 / float ( total ) ) if self . _query is not None : source = se...
def select_tag ( self , uid ) : """Selects tag for further usage . uid - - list or tuple with four bytes tag ID Returns error state ."""
back_data = [ ] buf = [ ] buf . append ( self . act_select ) buf . append ( 0x70 ) for i in range ( 5 ) : buf . append ( uid [ i ] ) crc = self . calculate_crc ( buf ) buf . append ( crc [ 0 ] ) buf . append ( crc [ 1 ] ) ( error , back_data , back_length ) = self . card_write ( self . mode_transrec , buf ) if ( no...
def _inserts ( self ) : """thwe"""
return { concat ( a , c , b ) for a , b in self . slices for c in ALPHABET }
def send ( self , message , callback , timeout = 0 ) : """Add a single message to the internal pending queue to be processed by the Connection without waiting for it to be sent . : param message : The message to send . : type message : ~ uamqp . message . Message : param callback : The callback to be run on...
# pylint : disable = protected - access try : raise self . _error except TypeError : pass except Exception as e : _logger . warning ( "%r" , e ) raise c_message = message . get_message ( ) message . _on_message_sent = callback try : self . _session . _connection . lock ( timeout = - 1 ) return s...
def dump2sqlite ( records , output_file ) : """Dumps tests results to database ."""
results_keys = list ( records . results [ 0 ] . keys ( ) ) pad_data = [ ] for key in REQUIRED_KEYS : if key not in results_keys : results_keys . append ( key ) pad_data . append ( "" ) conn = sqlite3 . connect ( os . path . expanduser ( output_file ) , detect_types = sqlite3 . PARSE_DECLTYPES ) # in...
def set_dhw_on ( self , until = None ) : """Sets the DHW on until a given time , or permanently ."""
if until is None : data = { "Mode" : "PermanentOverride" , "State" : "On" , "UntilTime" : None } else : data = { "Mode" : "TemporaryOverride" , "State" : "On" , "UntilTime" : until . strftime ( '%Y-%m-%dT%H:%M:%SZ' ) } self . _set_dhw ( data )
def isDocumentCollection ( cls , name ) : """return true or false wether ' name ' is the name of a document collection ."""
try : col = cls . getCollectionClass ( name ) return issubclass ( col , Collection ) except KeyError : return False
def conv3x3 ( in_planes , out_planes , stride = 1 ) : "3x3 convolution with padding"
return nn . Conv2d ( in_planes , out_planes , kernel_size = 3 , stride = stride , padding = 1 , bias = True )
def sparse_decom2 ( inmatrix , inmask = ( None , None ) , sparseness = ( 0.01 , 0.01 ) , nvecs = 3 , its = 20 , cthresh = ( 0 , 0 ) , statdir = None , perms = 0 , uselong = 0 , z = 0 , smooth = 0 , robust = 0 , mycoption = 0 , initialization_list = [ ] , initialization_list2 = [ ] , ell1 = 10 , prior_weight = 0 , verbo...
if inmatrix [ 0 ] . shape [ 0 ] != inmatrix [ 1 ] . shape [ 0 ] : raise ValueError ( 'Matrices must have same number of rows (samples)' ) idim = 3 if isinstance ( inmask [ 0 ] , iio . ANTsImage ) : maskx = inmask [ 0 ] . clone ( 'float' ) idim = inmask [ 0 ] . dimension hasmaskx = 1 elif isinstance ( in...
def allow_exception ( self , exc_class ) : """Allow raising this class of exceptions from commands . When a command fails on the server side due to an exception , by default it is turned into a string and raised on the client side as an ExternalError . The original class name is sent but ignored . If you wo...
name = exc_class . __name__ self . _allowed_exceptions [ name ] = exc_class
def rotation_substring_check ( main_string , check_string ) : """Checks if check _ string or any of its rotations is a substring of main _ string . Returns True if it is , False otherwise . Args : main _ string ( str ) : The main string in which to check for substrings . check _ string ( str ) : The string ...
check_length = len ( check_string ) double_check_string = check_string + check_string for index in range ( len ( main_string ) - check_length + 1 ) : for subset_index in range ( check_length + 1 ) : if main_string [ index : index + check_length ] == double_check_string [ subset_index : subset_index + check_...
def _next_sample_index ( self ) : """StochasticMux chooses its next sample stream randomly"""
return self . rng . choice ( self . n_active , p = ( self . stream_weights_ / self . weight_norm_ ) )
async def datacenters ( self ) : """Queries for WAN coordinates of Consul servers Returns : Mapping : WAN network coordinates for all Consul servers , organized by DCs . It returns a body like this : : " dc1 " : { " Datacenter " : " dc1 " , " Coordinates " : [ " Node " : " agent - one " , " Coord ...
response = await self . _api . get ( "/v1/coordinate/datacenters" ) return { data [ "Datacenter" ] : data for data in response . body }
def rex ( expr ) : """Regular expression matcher to use together with transform functions"""
r = re . compile ( expr ) return lambda key : isinstance ( key , six . string_types ) and r . match ( key )
def rename ( self , node ) : """Translate a rename node into latex qtree node . : param node : a treebrd node : return : a qtree subtree rooted at the node"""
child = self . translate ( node . child ) attributes = '' if node . attributes : attributes = '({})' . format ( ', ' . join ( node . attributes . names ) ) return '[.${op}_{{{name}{attributes}}}$ {child} ]' . format ( op = latex_operator [ node . operator ] , name = node . name , attributes = attributes , child = c...
def create_notification ( self ) : """Instead of the typical create _ widget we use ` create _ notification ` because after it ' s closed it needs created again ."""
d = self . declaration builder = self . builder = Notification . Builder ( self . get_context ( ) , d . channel_id ) d = self . declaration # Apply any custom settings if d . settings : builder . update ( ** d . settings ) for k , v in self . get_declared_items ( ) : handler = getattr ( self , 'set_{}' . format...
def is_citeable ( publication_info ) : """Check some fields in order to define if the article is citeable . : param publication _ info : publication _ info field already populated : type publication _ info : list"""
def _item_has_pub_info ( item ) : return all ( key in item for key in ( 'journal_title' , 'journal_volume' ) ) def _item_has_page_or_artid ( item ) : return any ( key in item for key in ( 'page_start' , 'artid' ) ) has_pub_info = any ( _item_has_pub_info ( item ) for item in publication_info ) has_page_or_artid...
def parse_meta ( meta_str ) : """Parse the metadata for a single ds9 region string . Parameters meta _ str : ` str ` Meta string , the metadata is everything after the close - paren of the region coordinate specification . All metadata is specified as key = value pairs separated by whitespace , but someti...
keys_vals = [ ( x , y ) for x , _ , y in regex_meta . findall ( meta_str . strip ( ) ) ] extra_text = regex_meta . split ( meta_str . strip ( ) ) [ - 1 ] result = OrderedDict ( ) for key , val in keys_vals : # regex can include trailing whitespace or inverted commas # remove it val = val . strip ( ) . strip ( "'" )...
def has_more_pages ( self ) : """: return : ` ` True ` ` if there are more pages available on the server ."""
# if has _ next property exists , it represents whether more pages exist if self . has_next is not None : return self . has_next # otherwise , try to compute whether or not more pages exist total_pages = self . get_total_pages ( ) if self . page_number is None or total_pages is None : return None else : ret...
def render_stop_display ( step : 'projects.ProjectStep' , message : str ) : """Renders a stop action to the Cauldron display ."""
stack = render_stack . get_formatted_stack_frame ( project = step . project , error_stack = False ) try : names = [ frame [ 'filename' ] for frame in stack ] index = names . index ( os . path . realpath ( __file__ ) ) frame = stack [ index - 1 ] except Exception : frame = { } stop_message = ( '{}' . for...
def delete_namespaced_daemon_set ( self , name , namespace , ** kwargs ) : # noqa : E501 """delete _ namespaced _ daemon _ set # noqa : E501 delete a DaemonSet # noqa : E501 This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > ...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_namespaced_daemon_set_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 else : ( data ) = self . delete_namespaced_daemon_set_with_http_info ( name , namespace , ** kwargs ) # noqa : E501 re...
def start ( self ) : """Start all the registered services . A new container is created for each service using the container class provided in the _ _ init _ _ method . All containers are started concurrently and the method will block until all have completed their startup routine ."""
service_names = ', ' . join ( self . service_names ) _log . info ( 'starting services: %s' , service_names ) SpawningProxy ( self . containers ) . start ( ) _log . debug ( 'services started: %s' , service_names )
def makedirs ( self ) : """Create all parent folders if they do not exist ."""
normpath = os . path . normpath ( self . path ) parentfolder = os . path . dirname ( normpath ) if parentfolder : try : os . makedirs ( parentfolder ) except OSError : pass
def Chisholm ( m , x , rhol , rhog , mul , mug , D , roughness = 0 , L = 1 , rough_correction = False ) : r'''Calculates two - phase pressure drop with the Chisholm ( 1973 ) correlation from [ 1 ] _ , also in [ 2 ] _ and [ 3 ] _ . . . math : : \ frac { \ Delta P _ { tp } } { \ Delta P _ { lo } } = \ phi _ { c...
G_tp = m / ( pi / 4 * D ** 2 ) n = 0.25 # Blasius friction factor exponent # Liquid - only properties , for calculation of dP _ lo v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5...
def unique_hash ( filepath : str , blocksize : int = 80 ) -> str : """Small function to generate a hash to uniquely generate a file . Default blocksize is ` 500 `"""
s = sha1 ( ) with open ( filepath , "rb" ) as f : buf = f . read ( blocksize ) s . update ( buf ) return s . hexdigest ( )
def vasp_version_from_outcar ( filename = 'OUTCAR' ) : """Returns the first line from a VASP OUTCAR file , to get the VASP source version string . Args : filename ( Str , optional ) : OUTCAR filename . Defaults to ' OUTCAR ' . Returns : ( Str ) : The first line read from the OUTCAR file ."""
with open ( filename ) as f : line = f . readline ( ) . strip ( ) return line
def get_hla ( sample , cromwell_dir , hla_glob ) : """Retrieve HLA calls and input fastqs for a sample ."""
hla_dir = glob . glob ( os . path . join ( cromwell_dir , hla_glob , "align" , sample , "hla" ) ) [ 0 ] fastq = os . path . join ( hla_dir , "OptiType-HLA-A_B_C-input.fq" ) calls = os . path . join ( hla_dir , "%s-optitype.csv" % sample ) return fastq , calls
def _optimal_size ( self , capacity , error ) : """Calculates minimum number of bits in filter array and number of hash functions given a number of enteries ( maximum ) and the desired error rate ( falese positives ) . Example : m , k = self . _ optimal _ size ( 3000 , 0.01 ) # m = 28756 , k = 7"""
m = math . ceil ( ( capacity * math . log ( error ) ) / math . log ( 1.0 / ( math . pow ( 2.0 , math . log ( 2.0 ) ) ) ) ) k = math . ceil ( math . log ( 2.0 ) * m / capacity ) return int ( m ) , int ( k )
def get ( self , key , default = NoDefault ) : """Retrieve a value from its key . Retrieval steps are : 1 ) Normalize the key 2 ) For each option group : a ) Retrieve the value at that key b ) If no value exists , continue c ) If the value is an instance of ' Default ' , continue d ) Otherwise , retur...
key = normalize_key ( key ) if default is NoDefault : defaults = [ ] else : defaults = [ default ] for options in self . options : try : value = options [ key ] except KeyError : continue if isinstance ( value , Default ) : defaults . append ( value . value ) continue...
def execute ( ) : """Ensure provisioning"""
boto_server_error_retries = 3 # Ensure provisioning for table_name , table_key in sorted ( dynamodb . get_tables_and_gsis ( ) ) : try : table_num_consec_read_checks = CHECK_STATUS [ 'tables' ] [ table_name ] [ 'reads' ] except KeyError : table_num_consec_read_checks = 0 try : table_n...
def run ( args ) : """Args : args ( argparse . Namespace )"""
regex_extractor = RegexExtractor ( pattern = args . pattern ) with warnings . catch_warnings ( ) : warnings . simplefilter ( 'ignore' ) for line in args . input_file : extractions = regex_extractor . extract ( line ) for e in extractions : print ( e . value )
def read_block_data ( self , i2c_addr , register , force = None ) : """Read a block of up to 32 - bytes from a given register . : param i2c _ addr : i2c address : type i2c _ addr : int : param register : Start register : type register : int : param force : : type force : Boolean : return : List of byt...
self . _set_address ( i2c_addr , force = force ) msg = i2c_smbus_ioctl_data . create ( read_write = I2C_SMBUS_READ , command = register , size = I2C_SMBUS_BLOCK_DATA ) ioctl ( self . fd , I2C_SMBUS , msg ) length = msg . data . contents . block [ 0 ] return msg . data . contents . block [ 1 : length + 1 ]
def remove_from_organization ( self , delete_account = False ) : """Remove a user from the organization ' s list of visible users . Optionally also delete the account . Deleting the account can only be done if the organization owns the account ' s domain . : param delete _ account : Whether to delete the accoun...
self . append ( removeFromOrg = { "deleteAccount" : True if delete_account else False } ) return None
def widont_html ( value ) : """Add an HTML non - breaking space between the final two words at the end of ( and in sentences just outside of ) block level tags to avoid " widowed " words . Examples : > > > print ( widont _ html ( ' < h2 > Here is a simple example < / h2 > < p > Single < / p > ' ) ) < h2 >...
def replace ( matchobj ) : return force_text ( '%s&nbsp;%s%s' % matchobj . groups ( ) ) return re_widont_html . sub ( replace , force_text ( value ) )
def normalize_total ( adata , target_sum = None , fraction = 1 , key_added = None , layers = None , layer_norm = None , inplace = True ) : """{ norm _ descr } { params _ bulk } { norm _ return } { examples }"""
if fraction < 0 or fraction > 1 : raise ValueError ( 'Choose fraction between 0 and 1.' ) X = adata . X gene_subset = None if not inplace : # not recarray because need to support sparse dat = { } if fraction < 1 : logg . msg ( 'normalizing by count per cell for \ genes that make up less th...
def get_cell_dimensions ( self ) : """Calculate centroid , width , length and area of each mesh cell . : returns : Tuple of four elements , each being 2d numpy array . Each array has both dimensions less by one the dimensions of the mesh , since they represent cells , not vertices . Arrays contain the fol...
points , along_azimuth , updip , diag = self . triangulate ( ) top = along_azimuth [ : - 1 ] left = updip [ : , : - 1 ] tl_area = geo_utils . triangle_area ( top , left , diag ) top_length = numpy . sqrt ( numpy . sum ( top * top , axis = - 1 ) ) left_length = numpy . sqrt ( numpy . sum ( left * left , axis = - 1 ) ) b...
def _sub_ms_char ( self , match ) : """Changes a MS smart quote character to an XML or HTML entity , or an ASCII character ."""
orig = match . group ( 1 ) if self . smart_quotes_to == 'ascii' : sub = self . MS_CHARS_TO_ASCII . get ( orig ) . encode ( ) else : sub = self . MS_CHARS . get ( orig ) if type ( sub ) == tuple : if self . smart_quotes_to == 'xml' : sub = '&#x' . encode ( ) + sub [ 1 ] . encode ( ) + ';'...
def error_codes ( self ) : """ThreatConnect error codes ."""
if self . _error_codes is None : from . tcex_error_codes import TcExErrorCodes self . _error_codes = TcExErrorCodes ( ) return self . _error_codes
def IntegerField ( default = NOTHING , required = True , repr = True , cmp = True , key = None ) : """Create new int field on a model . : param default : any integer value : param bool required : whether or not the object is invalid if not provided . : param bool repr : include this field should appear in obj...
default = _init_fields . init_default ( required , default , None ) validator = _init_fields . init_validator ( required , int ) return attrib ( default = default , converter = converters . int_if_not_none , validator = validator , repr = repr , cmp = cmp , metadata = dict ( key = key ) )
def init_original_response ( self ) : """Get the original response for comparing , confirm ` ` is _ cookie _ necessary ` `"""
if 'json' in self . request : self . request [ 'data' ] = json . dumps ( self . request . pop ( 'json' ) ) . encode ( self . encoding ) r1 = self . req . request ( retry = self . retry , timeout = self . timeout , ** self . request ) resp = r1 . x assert resp , ValueError ( 'original_response should not be failed. ...
def db990 ( self , value = None ) : """Corresponds to IDD Field ` db990 ` Dry - bulb temperature corresponding to 90.0 % annual cumulative frequency of occurrence ( cold conditions ) Args : value ( float ) : value for IDD Field ` db990 ` Unit : C if ` value ` is None it will not be checked against the ...
if value is not None : try : value = float ( value ) except ValueError : raise ValueError ( 'value {} need to be of type float ' 'for field `db990`' . format ( value ) ) self . _db990 = value
def touch_tip ( self , location = None , radius = 1.0 , v_offset = - 1.0 , speed = 60.0 ) : """Touch the : any : ` Pipette ` tip to the sides of a well , with the intent of removing left - over droplets Notes If no ` location ` is passed , the pipette will touch _ tip from it ' s current position . Parame...
if not self . tip_attached : log . warning ( "Cannot touch tip without a tip attached." ) if speed > 80.0 : log . warning ( "Touch tip speeds greater than 80mm/s not allowed" ) speed = 80.0 if speed < 20.0 : log . warning ( "Touch tip speeds greater than 80mm/s not allowed" ) speed = 20.0 if helpers...
def mogrify ( self , query , args = None ) : """Returns the exact string that is sent to the database by calling the execute ( ) method . This method follows the extension to the DB API 2.0 followed by Psycopg . : param query : ` ` str ` ` sql statement : param args : ` ` tuple ` ` or ` ` list ` ` of argume...
conn = self . _get_db ( ) if args is not None : query = query % self . _escape_args ( args , conn ) return query
def palettize ( arr , colors , values ) : """From start * values * apply * colors * to * data * ."""
new_arr = np . digitize ( arr . ravel ( ) , np . concatenate ( ( values , [ max ( np . nanmax ( arr ) , values . max ( ) ) + 1 ] ) ) ) new_arr -= 1 new_arr = new_arr . clip ( min = 0 , max = len ( values ) - 1 ) try : new_arr = np . ma . array ( new_arr . reshape ( arr . shape ) , mask = arr . mask ) except Attribu...
def _grid_in_property ( field_name , docstring , read_only = False , closed_only = False ) : """Create a GridIn property ."""
def getter ( self ) : if closed_only and not self . _closed : raise AttributeError ( "can only get %r on a closed file" % field_name ) # Protect against PHP - 237 if field_name == 'length' : return self . _file . get ( field_name , 0 ) return self . _file . get ( field_name , None ) def ...
def depth_first_search ( graph , root_node = None ) : """Searches through the tree in a breadth - first fashion . If root _ node is None , an arbitrary node will be used as the root . If root _ node is not None , it will be used as the root for the search tree . Returns a list of nodes , in the order that the...
ordering , parent_lookup , children_lookup = depth_first_search_with_parent_data ( graph , root_node ) return ordering
def dot_product_self_attention_relative_v2 ( q , k , v , bias , max_relative_position = None , dropout_rate = 0.0 , image_shapes = None , name = None , make_image_summary = True , dropout_broadcast_dims = None , heads_share_relative_embedding = False , add_relative_to_values = False ) : """Calculate relative positi...
if not max_relative_position : raise ValueError ( "Max relative position (%s) should be > 0 when using " "relative self attention." % ( max_relative_position ) ) with tf . variable_scope ( name , default_name = "dot_product_self_attention_relative_v2" , values = [ q , k , v ] ) : # This calculation only works for s...
def append ( self , item ) : """Appends a ` Monomer to the ` Polymer ` . Notes Does not update labelling ."""
if isinstance ( item , Monomer ) : self . _monomers . append ( item ) else : raise TypeError ( 'Only Monomer objects can be appended to an Polymer.' ) return
def serialize_unicode ( self , data ) : """Special handling for serializing unicode strings in Py2. Encode to UTF - 8 if unicode , otherwise handle as a str . : param data : Object to be serialized . : rtype : str"""
try : return data . value except AttributeError : pass try : if isinstance ( data , unicode ) : return data . encode ( encoding = 'utf-8' ) except NameError : return str ( data ) else : return str ( data )
def client_for ( self , config_path , quiet = False , bootstrap_server = False , create_client = False ) : """Get a cached client for a project , otherwise create one ."""
client = None abs_path = os . path . abspath ( config_path ) if abs_path in self . clients : client = self . clients [ abs_path ] elif create_client : client = self . create_client ( config_path ) if client . setup ( quiet = quiet , bootstrap_server = bootstrap_server ) : self . clients [ abs_path ]...
def get ( self , * args , ** kwargs ) -> "QuerySet" : """Fetch exactly one object matching the parameters ."""
queryset = self . filter ( * args , ** kwargs ) queryset . _limit = 2 queryset . _get = True return queryset
def set_display_name ( self , display_name ) : '''Set display name of a system independently of upload .'''
if self . config . legacy_upload : return self . _legacy_set_display_name ( display_name ) system = self . _fetch_system_by_machine_id ( ) if not system : return system inventory_id = system [ 0 ] [ 'id' ] req_url = self . base_url + '/inventory/v1/hosts/' + inventory_id try : net_logger . info ( "PATCH %s"...
def global_state ( self ) : """Returns global variables for generating function from ` ` func _ code ` ` . Includes compiled regular expressions and imports , so it does not have to do it every time when validation function is called ."""
self . _generate_func_code ( ) return dict ( REGEX_PATTERNS = self . _compile_regexps , re = re , JsonSchemaException = JsonSchemaException , )
def start_search ( self ) : """Start the Gateway Search Request and return the address information : rtype : ( string , int ) : return : a tuple ( string ( IP ) , int ( Port ) when found or None when timeout occurs"""
self . _asyncio_loop = asyncio . get_event_loop ( ) # Creating Broadcast Receiver coroutine_listen = self . _asyncio_loop . create_datagram_endpoint ( lambda : self . KNXSearchBroadcastReceiverProtocol ( self . _process_response , self . _timeout_handling , self . _timeout , self . _asyncio_loop ) , local_addr = ( self...
def _clean_result ( self , text ) : """Remove double spaces , punctuation and escapes apostrophes ."""
text = re . sub ( '\s\s+' , ' ' , text ) text = re . sub ( '\.\.+' , '.' , text ) text = text . replace ( "'" , "\\'" ) return text
def OnExport ( self , event ) : """File export event handler Currently , only CSV export is supported"""
code_array = self . main_window . grid . code_array tab = self . main_window . grid . current_table selection = self . main_window . grid . selection # Check if no selection is present selection_bbox = selection . get_bbox ( ) f2w = get_filetypes2wildcards ( [ "csv" , "pdf" , "svg" ] ) filters = f2w . keys ( ) wildcard...
def addAdminResource ( self , pluginSubPath : bytes , resource : BasicResource ) -> None : """Add Site Resource Add a cusotom implementation of a served http resource . : param pluginSubPath : The resource path where you want to serve this resource . : param resource : The resource to serve . : return : Non...
pluginSubPath = pluginSubPath . strip ( b'/' ) self . __rootAdminResource . putChild ( pluginSubPath , resource )
def convert_machine_list_time_val ( text : str ) -> datetime . datetime : '''Convert RFC 3659 time - val to datetime objects .'''
# TODO : implement fractional seconds text = text [ : 14 ] if len ( text ) != 14 : raise ValueError ( 'Time value not 14 chars' ) year = int ( text [ 0 : 4 ] ) month = int ( text [ 4 : 6 ] ) day = int ( text [ 6 : 8 ] ) hour = int ( text [ 8 : 10 ] ) minute = int ( text [ 10 : 12 ] ) second = int ( text [ 12 : 14 ]...
def checkpoint_filepath ( checkpoint , pm ) : """Create filepath for indicated checkpoint . : param str | pypiper . Stage checkpoint : Pipeline phase / stage or one ' s name : param pypiper . PipelineManager | pypiper . Pipeline pm : manager of a pipeline instance , relevant for output folder path . : retur...
# Handle case in which checkpoint is given not just as a string , but # as a checkpoint - like filename . Don ' t worry about absolute path status # of a potential filename input , or whether it ' s in the pipeline ' s # output folder . That ' s handled upstream . While this isn ' t a protected # function , there ' s n...
def actions_for_project ( self , project ) : """Compile & Run the experiment with - O3 enabled ."""
project . cflags = [ "-O3" , "-fno-omit-frame-pointer" ] project . runtime_extension = time . RunWithTime ( run . RuntimeExtension ( project , self ) ) return self . default_runtime_actions ( project )
def tree_analysisOutput ( self , * args , ** kwargs ) : """An optional method for looping over the < outputTree > and calling an outputcallback on the analysis results at each path . Only call this if self . b _ persisAnalysisResults is True ."""
fn_outputcallback = None for k , v in kwargs . items ( ) : if k == 'outputcallback' : fn_outputcallback = v index = 1 total = len ( self . d_inputTree . keys ( ) ) for path , d_analysis in self . d_outputTree . items ( ) : self . simpleProgress_show ( index , total ) self . dp . qprint ( "Processing...
def insert ( self , data ) : """Insert 1 into each bit by local _ hash"""
if not data : return data = self . _compress_by_md5 ( data ) # cut the first two place , route to different block by block _ num name = self . key + str ( int ( data [ 0 : 2 ] , 16 ) % self . block_num ) for h in self . hash_function : local_hash = h . hash ( data ) self . server . setbit ( name , local_has...
def set_object ( cache , template , indexes , data ) : """Set an object in Redis using a pipeline . Only sets the fields that are present in both the template and the data . Arguments : template : a dictionary containg the keys for the object and template strings for the corresponding redis keys . The templ...
# TODO ( mattmillr ) : Handle expiration times with cache as redis_connection : pipe = redis_connection . pipeline ( ) for key in set ( template . keys ( ) ) & set ( data . keys ( ) ) : pipe . set ( template [ key ] % indexes , str ( data [ key ] ) ) pipe . execute ( )
def upload_image ( self , image_file , referer_url = None , title = None , desc = None , created_at = None , collection_id = None ) : """Upload an image : param image _ file : File - like object of an image file : param referer _ url : Referer site URL : param title : Site title : param desc : Comment : p...
url = self . upload_url + '/api/upload' data = { } if referer_url is not None : data [ 'referer_url' ] = referer_url if title is not None : data [ 'title' ] = title if desc is not None : data [ 'desc' ] = desc if created_at is not None : data [ 'created_at' ] = str ( created_at ) if collection_id is not...
def trim_tree_before ( element , include_element = True , keep_head = True ) : """Removes the document tree preceding the given element . If include _ element is True , the given element is kept in the tree , otherwise it is removed ."""
el = element for parent_el in element . iterancestors ( ) : parent_el . text = None if el != element or include_element : el = el . getprevious ( ) else : parent_el . text = el . tail while el is not None : remove_el = el el = el . getprevious ( ) tag = remove_el ...
def load_data ( train_path = './data/regression.train' , test_path = './data/regression.test' ) : '''Load or create dataset'''
print ( 'Load data...' ) df_train = pd . read_csv ( train_path , header = None , sep = '\t' ) df_test = pd . read_csv ( test_path , header = None , sep = '\t' ) num = len ( df_train ) split_num = int ( 0.9 * num ) y_train = df_train [ 0 ] . values y_test = df_test [ 0 ] . values y_eval = y_train [ split_num : ] y_train...
def mkmanpage ( name ) : """Return man page content for the given ` cmdln . Cmdln ` subclass name ."""
mod_name , class_name = name . rsplit ( '.' , 1 ) mod = __import__ ( mod_name ) inst = getattr ( mod , class_name ) ( ) sections = cmdln . man_sections_from_cmdln ( inst ) sys . stdout . write ( '' . join ( sections ) )
def _is_subsequence_of ( self , sub , sup ) : """Parameters sub : str sup : str Returns bool"""
return bool ( re . search ( ".*" . join ( sub ) , sup ) )
def encode_index_req ( self , bucket , index , startkey , endkey = None , return_terms = None , max_results = None , continuation = None , timeout = None , term_regex = None , streaming = False ) : """Encodes a secondary index request into the protobuf message . : param bucket : the bucket whose index to query ...
req = riak . pb . riak_kv_pb2 . RpbIndexReq ( bucket = str_to_bytes ( bucket . name ) , index = str_to_bytes ( index ) ) self . _add_bucket_type ( req , bucket . bucket_type ) if endkey is not None : req . qtype = riak . pb . riak_kv_pb2 . RpbIndexReq . range req . range_min = str_to_bytes ( str ( startkey ) ) ...
def crval ( self ) : """Get the world coordinate of the reference pixel . @ rtype : float , float"""
try : return self . wcs . crval1 , self . wcs . crval2 except Exception as ex : logging . debug ( "Couldn't get CRVAL from WCS: {}" . format ( ex ) ) logging . debug ( "Trying RA/DEC values" ) try : return ( float ( self [ 'RA-DEG' ] ) , float ( self [ 'DEC-DEG' ] ) ) except KeyError as ke : KeyErro...
def name ( self ) : """MessageHandler name ."""
return ffi . string ( lib . EnvGetDefmessageHandlerName ( self . _env , self . _cls , self . _idx ) ) . decode ( )