signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def frames ( self , skip_registration = False ) : """Retrieve a new frame from the Kinect and convert it to a ColorImage , a DepthImage , and an IrImage . Parameters skip _ registration : bool If True , the registration step is skipped . Returns : obj : ` tuple ` of : obj : ` ColorImage ` , : obj : ` De...
color_im , depth_im , ir_im , _ = self . _frames_and_index_map ( skip_registration = skip_registration ) return color_im , depth_im , ir_im
def set_position ( self , x , y , speed = None ) : '''Move chuck to absolute position in um'''
if speed : self . _intf . write ( 'MoveChuckSubsite %1.1f %1.1f R Y %d' % ( x , y , speed ) ) else : self . _intf . write ( 'MoveChuckSubsite %1.1f %1.1f R Y' % ( x , y ) )
def load_pip_addons ( _globals ) : '''Load all known fabsetup addons which are installed as pypi pip - packages . Args : _ globals ( dict ) : the globals ( ) namespace of the fabric script . Return : None'''
for package_name in known_pip_addons : _ , username = package_username ( package_name ) try : load_addon ( username , package_name . replace ( '-' , '_' ) , _globals ) except ImportError : pass
def create_keytype_item_node ( field , state ) : """Create a definition list item node that describes the key type of a dict - type config field . Parameters field : ` ` lsst . pex . config . Field ` ` A ` ` lsst . pex . config . DictField ` ` or ` ` lsst . pex . config . DictConfigField ` ` . state : ` `...
keytype_node = nodes . definition_list_item ( ) keytype_node = nodes . term ( text = 'Key type' ) keytype_def = nodes . definition ( ) keytype_def += make_python_xref_nodes_for_type ( field . keytype , state , hide_namespace = False ) keytype_node += keytype_def return keytype_node
def train_epoch ( self , epoch_info , source : 'vel.api.Source' , interactive = True ) : """Run a single training epoch"""
self . train ( ) if interactive : iterator = tqdm . tqdm ( source . train_loader ( ) , desc = "Training" , unit = "iter" , file = sys . stdout ) else : iterator = source . train_loader ( ) for batch_idx , ( data , target ) in enumerate ( iterator ) : batch_info = BatchInfo ( epoch_info , batch_idx ) bat...
def parse_fields ( attributes ) : """Parse model fields ."""
return tuple ( field . bind_name ( name ) for name , field in six . iteritems ( attributes ) if isinstance ( field , fields . Field ) )
def get_outliers ( self ) : '''Performs iterative sigma clipping to get outliers .'''
log . info ( "Clipping outliers..." ) log . info ( 'Iter %d/%d: %d outliers' % ( 0 , self . oiter , len ( self . outmask ) ) ) def M ( x ) : return np . delete ( x , np . concatenate ( [ self . nanmask , self . badmask , self . transitmask ] ) , axis = 0 ) t = M ( self . time ) outmask = [ np . array ( [ - 1 ] ) , ...
def get_http_json ( self , url = None , retry_count = 3 , rate_limit_timeout = 120 , headers = None ) : """The function for retrieving a json result via HTTP . Args : url ( : obj : ` str ` ) : The URL to retrieve ( required ) . retry _ count ( : obj : ` int ` ) : The number of times to retry in case socket ...
if headers is None : headers = { 'Accept' : 'application/rdap+json' } try : # Create the connection for the whois query . log . debug ( 'HTTP query for {0} at {1}' . format ( self . address_str , url ) ) conn = Request ( url , headers = headers ) data = self . opener . open ( conn , timeout = self . tim...
def get_dim_indexers ( data_obj , indexers ) : """Given a xarray data object and label based indexers , return a mapping of label indexers with only dimension names as keys . It groups multiple level indexers given on a multi - index dimension into a single , dictionary indexer for that dimension ( Raise a Va...
invalid = [ k for k in indexers if k not in data_obj . dims and k not in data_obj . _level_coords ] if invalid : raise ValueError ( "dimensions or multi-index levels %r do not exist" % invalid ) level_indexers = defaultdict ( dict ) dim_indexers = { } for key , label in indexers . items ( ) : dim , = data_obj [...
def get_execution_info ( self , driver_id , function_descriptor ) : """Get the FunctionExecutionInfo of a remote function . Args : driver _ id : ID of the driver that the function belongs to . function _ descriptor : The FunctionDescriptor of the function to get . Returns : A FunctionExecutionInfo object ...
if self . _worker . load_code_from_local : # Load function from local code . # Currently , we don ' t support isolating code by drivers , # thus always set driver ID to NIL here . driver_id = ray . DriverID . nil ( ) if not function_descriptor . is_actor_method ( ) : self . _load_function_from_local ( d...
def asm_app ( parser , cmd , args ) : # pragma : no cover """Assemble code from commandline or stdin . Please not that all semi - colons are replaced with carriage returns unless source is read from stdin ."""
parser . add_argument ( 'source' , help = 'the code to assemble, read from stdin if omitted' , nargs = '?' ) pwnypack . main . add_target_arguments ( parser ) parser . add_argument ( '--syntax' , '-s' , choices = AsmSyntax . __members__ . keys ( ) , default = None , ) parser . add_argument ( '--address' , '-o' , type =...
def openTypeHeadCreatedFallback ( info ) : """Fallback to the environment variable SOURCE _ DATE _ EPOCH if set , otherwise now ."""
if "SOURCE_DATE_EPOCH" in os . environ : t = datetime . utcfromtimestamp ( int ( os . environ [ "SOURCE_DATE_EPOCH" ] ) ) return t . strftime ( _date_format ) else : return dateStringForNow ( )
def mass_3d ( self , R , Rs , rho0 , r_core ) : """: param R : projected distance : param Rs : scale radius : param rho0 : central core density : param r _ core : core radius"""
Rs = float ( Rs ) b = r_core * Rs ** - 1 c = R * Rs ** - 1 M0 = 4 * np . pi * Rs ** 3 * rho0 return M0 * ( 1 + b ** 2 ) ** - 1 * ( 0.5 * np . log ( 1 + c ** 2 ) + b ** 2 * np . log ( c * b ** - 1 + 1 ) - b * np . arctan ( c ) )
def delete_expired_requests ( ) : """Delete expired inclusion requests ."""
InclusionRequest . query . filter_by ( InclusionRequest . expiry_date > datetime . utcnow ( ) ) . delete ( ) db . session . commit ( )
def add_file_handler ( logger , level , tags ) : """Creates and Adds a file handler ( ` logging . FileHandler ` instance ) to the specified logger . Args : logger : The ` logging . Logger ` instance to add the new file handler to . level : ` str ` . The logging level for which the handler accepts messages , i...
f_formatter = logging . Formatter ( '%(asctime)s:%(name)s:\t%(message)s' ) filename = get_logfile_name ( tags ) handler = logging . FileHandler ( filename = filename , mode = "a" ) handler . setLevel ( level ) handler . setFormatter ( f_formatter ) logger . addHandler ( handler )
def turbulent_von_Karman ( Re , Pr , fd ) : r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [ 2 ] _ as in [ 1 ] _ . . . math : : Nu = \ frac { ( f / 8 ) Re Pr } { 1 + 5 ( f / 8 ) ^ { 0.5 } \ left [ Pr - 1 + \ ln \ left ( \ frac { 5Pr + 1} {6 } \ right ) \ right ] }...
return fd / 8. * Re * Pr / ( 1 + 5 * ( fd / 8. ) ** 0.5 * ( Pr - 1 + log ( ( 5 * Pr + 1 ) / 6. ) ) )
def flash ( function , links , thread_count ) : """Process the URLs and uses a threadpool to execute a function ."""
# Convert links ( set ) to list links = list ( links ) threadpool = concurrent . futures . ThreadPoolExecutor ( max_workers = thread_count ) futures = ( threadpool . submit ( function , link ) for link in links ) for i , _ in enumerate ( concurrent . futures . as_completed ( futures ) ) : if i + 1 == len ( links ) ...
def analyze_async ( output_dir , dataset , cloud = False , project_id = None ) : """Analyze data locally or in the cloud with BigQuery . Produce analysis used by training . This can take a while , even for small datasets . For small datasets , it may be faster to use local _ analysis . Args : output _ dir :...
import google . datalab . utils as du with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" ) fn = lambda : _analyze ( output_dir , dataset , cloud , project_id ) # noqa return du . LambdaJob ( fn , job_id = None )
def available_delegations ( self ) : """Instance depends on the API version : * 2018-08-01 : : class : ` AvailableDelegationsOperations < azure . mgmt . network . v2018_08_01 . operations . AvailableDelegationsOperations > `"""
api_version = self . _get_api_version ( 'available_delegations' ) if api_version == '2018-08-01' : from . v2018_08_01 . operations import AvailableDelegationsOperations as OperationClass else : raise NotImplementedError ( "APIVersion {} is not available" . format ( api_version ) ) return OperationClass ( self ....
def setLocked ( self , state ) : """Sets the locked state for this view widget . When locked , a user no longer has control over editing views and layouts . A view panel with a single entry will hide its tab bar , and if it has multiple views , it will simply hide the editing buttons . : param state | < bool >"""
changed = state != self . _locked self . _locked = state for panel in self . panels ( ) : panel . setLocked ( state ) if changed and not self . signalsBlocked ( ) : self . lockToggled . emit ( state )
def SelectFromListId ( LId , Val = None , Crit = 'Name' , PreExp = None , PostExp = None , Log = 'any' , InOut = 'In' , Out = bool ) : """Return the indices or instances of all LOS matching criteria The selection can be done according to 2 different mechanisms Mechanism ( 1 ) : provide the value ( Val ) a crite...
C0 = type ( Crit ) is str C1 = type ( Crit ) is list and all ( [ type ( cc ) is str for cc in Crit ] ) assert C0 or C1 , "Arg Crit must be a str or list of str !" for rr in [ PreExp , PostExp ] : if rr is not None : C0 = type ( rr ) is str C1 = type ( rr ) is list and all ( [ type ( ee ) is str for ...
def iter_following ( username , number = - 1 , etag = None ) : """List the people ` ` username ` ` follows . : param str username : ( required ) , login of the user : param int number : ( optional ) , number of users being followed by username to return . Default : - 1 , return all of them : param str etag ...
return gh . iter_following ( username , number , etag ) if username else [ ]
def onAIOCompletion ( self ) : """Call when eventfd notified events are available ."""
event_count = self . eventfd . read ( ) trace ( 'eventfd reports %i events' % event_count ) # Even though eventfd signaled activity , even though it may give us # some number of pending events , some events seem to have been already # processed ( maybe during io _ cancel call ? ) . # So do not trust eventfd value , and...
def extract_detections ( detections , templates , archive , arc_type , extract_len = 90.0 , outdir = None , extract_Z = True , additional_stations = [ ] ) : """Extract waveforms associated with detections Takes a list of detections for the template , template . Waveforms will be returned as a list of : class : ...
# Sort the template according to start - times , needed so that stachan [ i ] # corresponds to delays [ i ] all_delays = [ ] # List of tuples of template name , delays all_stachans = [ ] for template in templates : templatestream = template [ 1 ] . sort ( [ 'starttime' ] ) stachans = [ ( tr . stats . station , ...
def get_next_logs ( self , n ) : """gets next n objects from list"""
# Implemented from kitosid template for - # osid . resource . ResourceList . get _ next _ resources if n > self . available ( ) : # ! ! ! This is not quite as specified ( see method docs ) ! ! ! raise IllegalState ( 'not enough elements available in this list' ) else : next_list = [ ] i = 0 while i < n ...
def get_queryset ( self , ** kwargs ) : """Gets our queryset . This takes care of filtering if there are any fields to filter by ."""
queryset = self . derive_queryset ( ** kwargs ) return self . order_queryset ( queryset )
def extract_value ( self , string , key , inline_code = True ) : """Extract strings from the docstrings . . code - block : : text * synopsis : ` ` % shorten { text , max _ size } ` ` * example : ` ` % shorten { $ title , 32 } ` ` * description : Shorten “ text ” on word boundarys ."""
regex = r'\* ' + key + ': ' if inline_code : regex = regex + '``(.*)``' else : regex = regex + '(.*)' value = re . findall ( regex , string ) if value : return value [ 0 ] . replace ( '``' , '' ) else : return False
def get_context ( self , language ) : """Get the context ( description ) of this task"""
context = self . gettext ( language , self . _context ) if self . _context else "" vals = self . _hook_manager . call_hook ( 'task_context' , course = self . get_course ( ) , task = self , default = context ) return ParsableText ( vals [ 0 ] , "rst" , self . _translations . get ( language , gettext . NullTranslations (...
def _check_file_io ( self ) : """Create and define logging directory"""
folder = 'Model' + str ( self . flags [ 'RUN_NUM' ] ) + '/' folder_restore = 'Model' + str ( self . flags [ 'MODEL_RESTORE' ] ) + '/' self . flags [ 'RESTORE_DIRECTORY' ] = self . flags [ 'SAVE_DIRECTORY' ] + self . flags [ 'MODEL_DIRECTORY' ] + folder_restore self . flags [ 'LOGGING_DIRECTORY' ] = self . flags [ 'SAVE...
def GetLocations ( ) : """Return all cloud locations available to the calling alias ."""
r = clc . v1 . API . Call ( 'post' , 'Account/GetLocations' , { } ) if r [ 'Success' ] != True : if clc . args : clc . v1 . output . Status ( 'ERROR' , 3 , 'Error calling %s. Status code %s. %s' % ( 'Account/GetLocations' , r [ 'StatusCode' ] , r [ 'Message' ] ) ) raise Exception ( 'Error calling %s....
def main ( ) : '''Calculate the distance of an object in inches using a HCSR04 sensor and a Raspberry Pi'''
trig_pin = 17 echo_pin = 27 # Default values # unit = ' metric ' # temperature = 20 # round _ to = 1 # Create a distance reading with the hcsr04 sensor module # and overide the default values for temp , unit and rounding ) value = sensor . Measurement ( trig_pin , echo_pin , temperature = 68 , unit = 'imperial' , round...
def _packet_manager ( self ) : """Watch packet list for timeouts ."""
while True : if self . _packets : with self . _packet_lock : now = time . time ( ) self . _packets [ : ] = [ packet for packet in self . _packets if self . _packet_timeout ( packet , now ) ] # c . f . nyquist time . sleep ( ACK_RESEND / 2 )
def get_compute_usage ( access_token , subscription_id , location ) : '''List compute usage and limits for a location . Args : access _ token ( str ) : A valid Azure authentication token . subscription _ id ( str ) : Azure subscription id . location ( str ) : Azure data center location . E . g . westus . ...
endpoint = '' . join ( [ get_rm_endpoint ( ) , '/subscriptions/' , subscription_id , '/providers/Microsoft.compute/locations/' , location , '/usages?api-version=' , COMP_API ] ) return do_get ( endpoint , access_token )
def start ( self , name : str , increment_count : bool = True ) -> None : """Start a named timer . Args : name : name of the timer increment _ count : increment the start count for this timer"""
if not self . _timing : return now = get_now_utc_pendulum ( ) # If we were already timing something else , pause that . if self . _stack : last = self . _stack [ - 1 ] self . _totaldurations [ last ] += now - self . _starttimes [ last ] # Start timing our new thing if name not in self . _starttimes : se...
def acquire_lock ( self ) : """Acquire lock before scheduling jobs to prevent another scheduler from scheduling jobs at the same time . This function returns True if a lock is acquired . False otherwise ."""
key = '%s_lock' % self . scheduler_key now = time . time ( ) expires = int ( self . _interval ) + 10 self . _lock_acquired = self . connection . set ( key , now , ex = expires , nx = True ) return self . _lock_acquired
def _from_dict ( cls , _dict ) : """Initialize a Expansions object from a json dictionary ."""
args = { } if 'expansions' in _dict : args [ 'expansions' ] = [ Expansion . _from_dict ( x ) for x in ( _dict . get ( 'expansions' ) ) ] else : raise ValueError ( 'Required property \'expansions\' not present in Expansions JSON' ) return cls ( ** args )
def instance ( self , * args , ** kwargs ) : """Create an instance of the specified class in the initializer . : param args : the arguments given to the initializer of the new class : param kwargs : the keyword arguments given to the initializer of the new class"""
mod , cls = self . get_module_class ( ) inst = cls ( * args , ** kwargs ) logger . debug ( f'inst: {inst}' ) return inst
def pressision_try ( orbitals , U , beta , step ) : """perform a better initial guess of lambda no improvement"""
mu , lam = main ( orbitals , U , beta , step ) mu2 , lam2 = linspace ( 0 , U * orbitals , step ) , zeros ( step ) for i in range ( 99 ) : lam2 [ i + 1 ] = fsolve ( restriction , lam2 [ i ] , ( mu2 [ i + 1 ] , orbitals , U , beta ) ) plot ( mu2 , 2 * orbitals * fermi_dist ( - ( mu2 + lam2 ) , beta ) , label = 'Test ...
def matchingFilePaths ( targetfilename , directory , targetFileExtension = None , selector = None ) : """Search for files in all subfolders of specified directory , return filepaths of all matching instances . : param targetfilename : filename to search for , only the string before the last " . " is used for ...
targetFilePaths = list ( ) targetfilename = os . path . splitext ( targetfilename ) [ 0 ] targetFileExtension = targetFileExtension . replace ( '.' , '' ) matchExtensions = False if targetFileExtension is None else True if selector is None : selector = functools . partial ( operator . eq , targetfilename ) for dirp...
def _rsassa_pss_sign ( self , M , h = None , mgf = None , sLen = None ) : """Implements RSASSA - PSS - SIGN ( ) function described in Sect . 8.1.1 of RFC 3447. Input : M : message to be signed , an octet string Output : signature , an octet string of length k , where k is the length in octets of the RSA...
# Set default parameters if not provided if h is None : # By default , sha1 h = "sha1" if not h in _hashFuncParams : warning ( "Key._rsassa_pss_sign(): unknown hash function " "provided (%s)" % h ) return None if mgf is None : # use mgf1 with underlying hash function mgf = lambda x , y : pkcs_mgf1 ( x ,...
def get_log_entry_log_assignment_session ( self , proxy ) : """Gets the session for assigning log entry to log mappings . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . logging . LogEntryLogAssignmentSession ) - a ` ` LogEntryLogAssignmentSession ` ` raise : NullArgument - ` ` proxy ` ` is...
if not self . supports_log_entry_log_assignment ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . LogEntryLogAssignmentSession ( proxy = proxy , runtime = self . _runtime )
def indexableText ( self , include_properties = True ) : """Words found in the various texts of the document . : param include _ properties : Adds words from properties : return : Space separated words of the document ."""
text = set ( ) for extractor in self . _text_extractors : if extractor . content_type in self . content_types . overrides : for tree in self . content_types . getTreesFor ( self , extractor . content_type ) : words = extractor . indexableText ( tree ) text |= words if include_propert...
def branchings_segments ( self ) : """Detect branchings and partition the data into corresponding segments . Detect all branchings up to ` n _ branchings ` . Writes segs : np . ndarray Array of dimension ( number of segments ) × ( number of data points ) . Each row stores a mask array that defines a segme...
self . detect_branchings ( ) self . postprocess_segments ( ) self . set_segs_names ( ) self . order_pseudotime ( )
def detach ( self , * items ) : """Unlinks all of the specified items from the tree . The items and all of their descendants are still present , and may be reinserted at another point in the tree , but will not be displayed . The root item may not be detached . : param items : list of item identifiers : t...
self . _visual_drag . detach ( * items ) ttk . Treeview . detach ( self , * items )
def create ( name , packages = None , user = None ) : """Create a conda env"""
packages = packages or '' packages = packages . split ( ',' ) packages . append ( 'pip' ) args = packages + [ '--yes' , '-q' ] cmd = _create_conda_cmd ( 'create' , args = args , env = name , user = user ) ret = _execcmd ( cmd , user = user , return0 = True ) if ret [ 'retcode' ] == 0 : ret [ 'result' ] = True r...
def parse_component_config ( self , component_config : Dict [ str , Union [ Dict , List ] ] ) -> List [ str ] : """Parses a hierarchical component specification into a list of standardized component definitions . This default parser expects component configurations as a list of dicts . Each dict at the top level ...
return _parse_component_config ( component_config )
def scalloping_loss ( wnd ) : """Positive number with the scalloping loss in dB ."""
return - dB20 ( abs ( sum ( wnd * cexp ( line ( len ( wnd ) , 0 , - 1j * pi ) ) ) ) / sum ( wnd ) )
def inception_v3_base ( inputs , final_endpoint = 'Mixed_7c' , min_depth = 16 , depth_multiplier = 1.0 , scope = None ) : """Inception model from http : / / arxiv . org / abs / 1512.00567. Constructs an Inception v3 network from inputs to the given final endpoint . This method can construct the network up to th...
# end _ points will collect relevant activations for external use , for example # summaries or losses . end_points = { } if depth_multiplier <= 0 : raise ValueError ( 'depth_multiplier is not greater than zero.' ) def depth ( d ) : return max ( int ( d * depth_multiplier ) , min_depth ) with tf . variable_scope...
def get ( self , ** kwargs ) : """: returns : Full specification of the remote app object : rtype : dict Returns the contents of the app . The result includes the key - value pairs as specified in the API documentation for the ` / app - xxxx / get < https : / / wiki . dnanexus . com / API - Specification ...
if self . _dxid is not None : return dxpy . api . app_get ( self . _dxid , ** kwargs ) else : return dxpy . api . app_get ( 'app-' + self . _name , alias = self . _alias , ** kwargs )
def set ( self , name , value ) : """Set an option value . Args : name ( str ) : The name of the option . value : The value to set the option to . Raises : TypeError : If the value is not a string or appropriate native type . ValueError : If the value is a string but cannot be coerced . If the name is...
if name not in self . _options : self . register ( name , self . _generator ( ) ) return self . _options [ name ] . __set__ ( self , value )
def parse_arguments ( argv : Optional [ Sequence [ str ] ] = None ) -> argparse . Namespace : """Parse the command line arguments . Args : argv : If not ` ` None ` ` , use the provided command line arguments for parsing . Otherwise , extract them automatically . Returns : The argparse object representin...
parser = argparse . ArgumentParser ( description = 'Git credential helper using pass as the data source.' , formatter_class = argparse . ArgumentDefaultsHelpFormatter ) parser . add_argument ( '-m' , '--mapping' , type = argparse . FileType ( 'r' ) , metavar = 'MAPPING_FILE' , default = None , help = 'A mapping file to...
def execute ( options ) : """execute the tool with given options ."""
# Load the key in PKCS 12 format that you downloaded from the Google APIs # Console when you created your Service account . package_name = options [ '<package>' ] source_directory = options [ '<output_dir>' ] if options [ 'upload' ] is True : upstream = True else : upstream = False sub_tasks = { 'images' : opti...
def file_uptodate ( fname , cmp_fname ) : """Check if a file exists , is non - empty and is more recent than cmp _ fname ."""
try : return ( file_exists ( fname ) and file_exists ( cmp_fname ) and os . path . getmtime ( fname ) >= os . path . getmtime ( cmp_fname ) ) except OSError : return False
def import_from_chain ( cls , name , certificate_file , private_key = None ) : """Import the server certificate , intermediate and optionally private key from a certificate chain file . The expected format of the chain file follows RFC 4346. In short , the server certificate should come first , followed by ...
contents = load_cert_chain ( certificate_file ) for pem in list ( contents ) : if b'PRIVATE KEY' in pem [ 0 ] : private_key = pem [ 1 ] contents . remove ( pem ) if not private_key : raise ValueError ( 'Private key was not found in chain file and ' 'was not provided. The private key is required ...
def send_stdout ( cls , sock , payload ) : """Send the Stdout chunk over the specified socket ."""
cls . write_chunk ( sock , ChunkType . STDOUT , payload )
def _parse_flags ( element ) : """Parse OSM XML element for generic data . Args : element ( etree . Element ) : Element to parse Returns : tuple : Generic OSM data for object instantiation"""
visible = True if element . get ( 'visible' ) else False user = element . get ( 'user' ) timestamp = element . get ( 'timestamp' ) if timestamp : timestamp = utils . Timestamp . parse_isoformat ( timestamp ) tags = { } try : for tag in element [ 'tag' ] : key = tag . get ( 'k' ) value = tag . ge...
def stageContent ( self , configFiles , dateTimeFormat = None ) : """Parses a JSON configuration file to stage content . Args : configFiles ( list ) : A list of JSON files on disk containing configuration data for staging content . dateTimeFormat ( str ) : A valid date formatting directive , as understood ...
results = None groups = None items = None group = None content = None contentInfo = None startTime = None orgTools = None if dateTimeFormat is None : dateTimeFormat = '%Y-%m-%d %H:%M' scriptStartTime = datetime . datetime . now ( ) try : print ( "********************Stage Content Started********************" ) ...
def register_workflow ( self , name , workflow ) : """Register an workflow to be showed in the workflows list ."""
assert name not in self . workflows self . workflows [ name ] = workflow
def _ReadStructureFromByteStream ( self , byte_stream , file_offset , data_type_map , description , context = None ) : """Reads a structure from a byte stream . Args : byte _ stream ( bytes ) : byte stream . file _ offset ( int ) : offset of the data relative from the start of the file - like object . dat...
if not byte_stream : raise ValueError ( 'Invalid byte stream.' ) if not data_type_map : raise ValueError ( 'Invalid data type map.' ) try : return data_type_map . MapByteStream ( byte_stream , context = context ) except dtfabric_errors . MappingError as exception : raise errors . FileFormatError ( ( 'Un...
def _to_cwlfile_with_indexes ( val , get_retriever ) : """Convert reads with ready to go indexes into the right CWL object . Identifies the top level directory and creates a tarball , avoiding trying to handle complex secondary setups which are not cross platform . Skips doing this for reference files and sta...
val [ "indexes" ] = _index_blacklist ( val [ "indexes" ] ) tval = { "base" : _remove_remote_prefix ( val [ "base" ] ) , "indexes" : [ _remove_remote_prefix ( f ) for f in val [ "indexes" ] ] } # Standard named set of indices , like bwa # Do not include snpEff , which we need to isolate inside a nested directory # hisat...
def israw ( self ) : """Returns True if the PTY should operate in raw mode . If the container was not started with tty = True , this will return False ."""
if self . raw is None : info = self . container_info ( ) self . raw = self . stdout . isatty ( ) and info [ 'Config' ] [ 'Tty' ] return self . raw
async def helo ( self , from_host = None ) : """Sends a SMTP ' HELO ' command . - Identifies the client and starts the session . If given ` ` from _ host ` ` is None , defaults to the client FQDN . For further details , please check out ` RFC 5321 § 4.1.1.1 ` _ . Args : from _ host ( str or None ) : Name ...
if from_host is None : from_host = self . fqdn code , message = await self . do_cmd ( "HELO" , from_host ) self . last_helo_response = ( code , message ) return code , message
def host_is_trusted ( hostname , trusted_list ) : """Checks if a host is trusted against a list . This also takes care of port normalization . . . versionadded : : 0.9 : param hostname : the hostname to check : param trusted _ list : a list of hostnames to check against . If a hostname starts with a dot i...
if not hostname : return False if isinstance ( trusted_list , string_types ) : trusted_list = [ trusted_list ] def _normalize ( hostname ) : if ':' in hostname : hostname = hostname . rsplit ( ':' , 1 ) [ 0 ] return _encode_idna ( hostname ) hostname = _normalize ( hostname ) for ref in trusted_...
def get_choices_file_urls_map ( self ) : """stub"""
file_urls_map = [ ] for choice in self . get_choices ( ) : choice = dict ( choice ) small_asset_content = self . _get_asset_content ( Id ( choice [ 'assetId' ] ) , OV_SET_SMALL_ASSET_CONTENT_TYPE ) choice [ 'smallOrthoViewSet' ] = small_asset_content . get_url ( ) small_asset_content = self . _get_asset...
def _load32 ( ins ) : """Load a 32 bit value from a memory address If 2nd arg . start with ' * ' , it is always treated as an indirect value ."""
output = _32bit_oper ( ins . quad [ 2 ] ) output . append ( 'push de' ) output . append ( 'push hl' ) return output
def register_layouts ( layouts , app , url = "/api/props/" , brand = "Pyxley" ) : """register UILayout with the flask app create a function that will send props for each UILayout Args : layouts ( dict ) : dict of UILayout objects by name app ( object ) : flask app url ( string ) : address of props ; defau...
def props ( name ) : if name not in layouts : # cast as list for python3 name = list ( layouts . keys ( ) ) [ 0 ] return jsonify ( { "layouts" : layouts [ name ] [ "layout" ] } ) def apps ( ) : paths = [ ] for i , k in enumerate ( layouts . keys ( ) ) : if i == 0 : paths . ap...
def error_state ( self ) : """Set the error condition"""
self . buildstate . state . lasttime = time ( ) self . buildstate . commit ( ) return self . buildstate . state . error
def loads ( s , encoding = None , cls = JSONTreeDecoder , object_hook = None , parse_float = None , parse_int = None , parse_constant = None , object_pairs_hook = None , ** kargs ) : """JSON load from string function that defaults the loading class to be JSONTreeDecoder"""
return json . loads ( s , encoding , cls , object_hook , parse_float , parse_int , parse_constant , object_pairs_hook , ** kargs )
def get_grid_point_from_address ( grid_address , mesh ) : """Return grid point index by tranlating grid address"""
_set_no_error ( ) return spg . grid_point_from_address ( np . array ( grid_address , dtype = 'intc' ) , np . array ( mesh , dtype = 'intc' ) )
def set_font_size ( self , pt = None , px = None ) : """Set the font size to the desired size , in pt or px ."""
self . font . set_size ( pt , px ) self . _render ( )
def generate_permissions ( urlpatterns , permissions = { } ) : """Generate names for permissions ."""
for pattern in urlpatterns : if isinstance ( pattern , urlresolvers . RegexURLPattern ) : perm = generate_perm_name ( pattern . callback ) if is_allowed_view ( perm ) and perm not in permissions : permissions [ ACL_CODE_PREFIX + perm ] = ACL_NAME_PREFIX + perm elif isinstance ( patte...
def check ( self ) : """Checks if the list of tracked terms has changed . Returns True if changed , otherwise False ."""
new_tracking_terms = self . update_tracking_terms ( ) terms_changed = False # any deleted terms ? if self . _tracking_terms_set > new_tracking_terms : logging . debug ( "Some tracking terms removed" ) terms_changed = True # any added terms ? elif self . _tracking_terms_set < new_tracking_terms : logging . d...
def _getPayload ( self , record ) : """The data that will be sent to loggly ."""
payload = super ( LogglyHandler , self ) . _getPayload ( record ) payload [ 'tags' ] = self . _implodeTags ( ) return payload
def import_from_json ( self , data , * , override = False ) : """Import a JSON dictionary which must have the same format as exported by : meth : ` export ` . If * override * is true , the existing data in the pin store will be overriden with the data from ` data ` . Otherwise , the ` data ` will be merged ...
if override : self . _storage = { hostname : set ( self . _decode_key ( key ) for key in pins ) for hostname , pins in data . items ( ) } return for hostname , pins in data . items ( ) : existing_pins = self . _storage . setdefault ( hostname , set ( ) ) existing_pins . update ( self . _decode_key ( key...
def get ( self , now ) : """Get a bucket key to compact . If none are available , returns None . This uses a Lua script to ensure that the bucket key is popped off the sorted set in an atomic fashion . : param now : The current time , as a float . Used to ensure the bucket key has been aged sufficiently to ...
items = self . script ( keys = [ self . key ] , args = [ now - self . min_age ] ) return items [ 0 ] if items else None
def _compute_ticks ( self , element , edges , widths , lims ) : """Compute the ticks either as cyclic values in degrees or as roughly evenly spaced bin centers ."""
if self . xticks is None or not isinstance ( self . xticks , int ) : return None if self . cyclic : x0 , x1 , _ , _ = lims xvals = np . linspace ( x0 , x1 , self . xticks ) labels = [ "%.0f" % np . rad2deg ( x ) + '\N{DEGREE SIGN}' for x in xvals ] elif self . xticks : dim = element . get_dimension ...
def _scrub_participant_table ( path_to_data ) : """Scrub PII from the given participant table ."""
path = os . path . join ( path_to_data , "participant.csv" ) with open_for_csv ( path , "r" ) as input , open ( "{}.0" . format ( path ) , "w" ) as output : reader = csv . reader ( input ) writer = csv . writer ( output ) headers = next ( reader ) writer . writerow ( headers ) for i , row in enumera...
def bind_context ( context_filename ) : """loads context from file and binds to it : param : context _ filename absolute path of the context file called by featuredjango . startup . select _ product prior to selecting the individual features"""
global PRODUCT_CONTEXT if PRODUCT_CONTEXT is None : with open ( context_filename ) as contextfile : try : context = json . loads ( contextfile . read ( ) ) except ValueError as e : raise ContextParseError ( 'Error parsing %s: %s' % ( context_filename , str ( e ) ) ) c...
def _preprocess_and_rename_grid_attrs ( func , grid_attrs = None , ** kwargs ) : """Call a custom preprocessing method first then rename grid attrs . This wrapper is needed to generate a single function to pass to the ` ` preprocesss ` ` of xr . open _ mfdataset . It makes sure that the user - specified prepr...
def func_wrapper ( ds ) : return grid_attrs_to_aospy_names ( func ( ds , ** kwargs ) , grid_attrs ) return func_wrapper
def SLT ( self , o ) : """Signed less than : param o : The other operand : return : TrueResult ( ) , FalseResult ( ) , or MaybeResult ( )"""
signed_bounds_1 = self . _signed_bounds ( ) signed_bounds_2 = o . _signed_bounds ( ) ret = [ ] for lb_1 , ub_1 in signed_bounds_1 : for lb_2 , ub_2 in signed_bounds_2 : if ub_1 < lb_2 : ret . append ( TrueResult ( ) ) elif lb_1 >= ub_2 : ret . append ( FalseResult ( ) ) ...
def AddNIC ( self , network_id , ip = '' ) : """Add a NIC from the provided network to server and , if provided , assign a provided IP address https : / / www . ctl . io / api - docs / v2 / # servers - add - secondary - network Requires package ID , currently only available by browsing control and browsing ...
return ( clc . v2 . Requests ( clc . v2 . API . Call ( 'POST' , 'servers/%s/%s/networks' % ( self . alias , self . id ) , json . dumps ( { 'networkId' : network_id , 'ipAddress' : ip } ) , session = self . session ) , alias = self . alias , session = self . session ) )
def set_tcp_port ( self , tcp_port ) : """Defines the TCP port number . : type tcp _ port : int : param tcp _ port : The TCP port number ."""
if tcp_port is None : self . tcp_port = None return self . tcp_port = int ( tcp_port )
def ensure_int_vector ( I , require_order = False ) : """Checks if the argument can be converted to an array of ints and does that . Parameters I : int or iterable of int require _ order : bool If False ( default ) , an unordered set is accepted . If True , a set is not accepted . Returns arr : ndarray ...
if is_int_vector ( I ) : return I elif is_int ( I ) : return np . array ( [ I ] ) elif is_list_of_int ( I ) : return np . array ( I ) elif is_tuple_of_int ( I ) : return np . array ( I ) elif isinstance ( I , set ) : if require_order : raise TypeError ( 'Argument is an unordered set, but I r...
def set_compression_pool_size ( pool_size ) : """Set the size of the compression workers thread pool . If the pool is already created , it waits until all jobs are finished , and then proceeds with setting the new size . Parameters pool _ size : ` int ` The size of the pool ( must be a positive integer ) ...
pool_size = int ( pool_size ) if pool_size < 1 : raise ValueError ( "The compression thread pool size cannot be of size {}" . format ( pool_size ) ) global _compress_thread_pool if _compress_thread_pool is not None : _compress_thread_pool . close ( ) _compress_thread_pool . join ( ) _compress_thread_pool = ...
def list_storage_accounts ( call = None ) : '''List storage accounts within the subscription .'''
if call == 'action' : raise SaltCloudSystemExit ( 'The list_storage_accounts function must be called with ' '-f or --function' ) storconn = get_conn ( client_type = 'storage' ) ret = { } try : accounts_query = storconn . storage_accounts . list ( ) accounts = __utils__ [ 'azurearm.paged_object_to_list' ] ( ...
def generate_repr ( * members ) : """Decorator that binds an auto - generated ` ` _ _ repr _ _ ( ) ` ` function to a class . The generated ` ` _ _ repr _ _ ( ) ` ` function prints in following format : < ClassName object ( field1 = 1 , field2 = ' A string ' , field3 = [ 1 , 2 , 3 ] ) at 0xAAAA > Note that thi...
def decorator ( cls ) : cls . __repr__ = __repr__ return cls if members : # Prepare members list . members_to_print = list ( members ) for i , member in enumerate ( members_to_print ) : if isinstance ( member , tuple ) : # Check tuple dimensions . length = len ( member ) ...
def _set_chain_sid ( chain_model , sid ) : """Set or update SID for chain . If the chain already has a SID , ` ` sid ` ` must either be None or match the existing SID ."""
if not sid : return if chain_model . sid and chain_model . sid . did != sid : raise d1_common . types . exceptions . ServiceFailure ( 0 , 'Attempted to modify existing SID. ' 'existing_sid="{}", new_sid="{}"' . format ( chain_model . sid . did , sid ) , ) chain_model . sid = d1_gmn . app . did . get_or_create_d...
def invert ( self , points ) : """Invert the distortion Parameters points : ndarray Input image points Returns ndarray Undistorted points"""
X = points if not points . ndim == 1 else points . reshape ( ( points . size , 1 ) ) wx , wy = self . wc # Switch to polar coordinates rn = np . sqrt ( ( X [ 0 , : ] - wx ) ** 2 + ( X [ 1 , : ] - wy ) ** 2 ) phi = np . arctan2 ( X [ 1 , : ] - wy , X [ 0 , : ] - wx ) # ' atan ' method r = np . tan ( rn * self . lgamma )...
def verify_signature ( message , signature , address ) : """This function verifies a bitcoin signed message . : param message : the plain text of the message to verify : param signature : the signature in base64 format : param address : the signing address"""
if ( len ( signature ) != SIGNATURE_LENGTH ) : return False try : binsig = base64 . b64decode ( signature ) except : return False r = intbytes . from_bytes ( binsig [ 1 : 33 ] ) s = intbytes . from_bytes ( binsig [ 33 : 65 ] ) val = intbytes . from_bytes ( bitcoin_sig_hash ( message . encode ( ) ) ) pubpair...
def find ( self , id ) : """breadth - first sprite search by ID"""
for sprite in self . sprites : if sprite . id == id : return sprite for sprite in self . sprites : found = sprite . find ( id ) if found : return found
def get_param_info ( self , obj , include_super = True ) : """Get the parameter dictionary , the list of modifed parameters and the dictionary or parameter values . If include _ super is True , parameters are also collected from the super classes ."""
params = dict ( obj . param . objects ( 'existing' ) ) if isinstance ( obj , type ) : changed = [ ] val_dict = dict ( ( k , p . default ) for ( k , p ) in params . items ( ) ) self_class = obj else : changed = [ name for ( name , _ ) in obj . param . get_param_values ( onlychanged = True ) ] val_dic...
def training_base_config ( estimator , inputs = None , job_name = None , mini_batch_size = None ) : """Export Airflow base training config from an estimator Args : estimator ( sagemaker . estimator . EstimatorBase ) : The estimator to export training config from . Can be a BYO estimator , Framework estimato...
default_bucket = estimator . sagemaker_session . default_bucket ( ) s3_operations = { } if job_name is not None : estimator . _current_job_name = job_name else : base_name = estimator . base_job_name or utils . base_name_from_image ( estimator . train_image ( ) ) estimator . _current_job_name = utils . name...
def from_binary ( self , d ) : """Given a binary payload d , update the appropriate payload fields of the message ."""
p = MsgEphemerisGPSDepF . _parser . parse ( d ) for n in self . __class__ . __slots__ : setattr ( self , n , getattr ( p , n ) )
def remove_service_checks ( self , service_id ) : """Remove all checks from a service ."""
from hypermap . aggregator . models import Service service = Service . objects . get ( id = service_id ) service . check_set . all ( ) . delete ( ) layer_to_process = service . layer_set . all ( ) for layer in layer_to_process : layer . check_set . all ( ) . delete ( )
def dew_point ( self , db ) : """Get the dew point ( C ) , which is constant throughout the day ( except at saturation ) . args : db : The maximum dry bulb temperature over the day ."""
if self . _hum_type == 'Dewpoint' : return self . _hum_value elif self . _hum_type == 'Wetbulb' : return dew_point_from_db_wb ( db , self . _hum_value , self . _barometric_pressure ) elif self . _hum_type == 'HumidityRatio' : return dew_point_from_db_hr ( db , self . _hum_value , self . _barometric_pressure...
def generate_lambda_functions ( ) : """Create the Blockade lambda functions ."""
logger . debug ( "[#] Setting up the Lambda functions" ) aws_lambda = boto3 . client ( 'lambda' , region_name = PRIMARY_REGION ) functions = aws_lambda . list_functions ( ) . get ( 'Functions' ) existing_funcs = [ x [ 'FunctionName' ] for x in functions ] iam = boto3 . resource ( 'iam' ) account_id = iam . CurrentUser ...
def is_paired ( text , open = '(' , close = ')' ) : """Check if the text only contains : 1 . blackslash escaped parentheses , or 2 . parentheses paired ."""
count = 0 escape = False for c in text : if escape : escape = False elif c == '\\' : escape = True elif c == open : count += 1 elif c == close : if count == 0 : return False count -= 1 return count == 0
def timetuple ( self ) : "Return local time tuple compatible with time . localtime ( ) ."
dst = self . dst ( ) if dst is None : dst = - 1 elif dst : dst = 1 else : dst = 0 return _build_struct_time ( self . year , self . month , self . day , self . hour , self . minute , self . second , dst )
def push ( self , item ) : """Push and item onto the sorting stack . @ param item : An item to push . @ type item : I { item } @ return : The number of items pushed . @ rtype : int"""
if item in self . pushed : return frame = ( item , iter ( item [ 1 ] ) ) self . stack . append ( frame ) self . pushed . add ( item )
def getEntityType ( self , found = None ) : '''Method to recover the value of the entity in case it may vary . : param found : The expression to be analysed . : return : The entity type returned will be an s ' i3visio . email ' for foo @ bar . com and an ' i3visio . text ' for foo [ at ] bar [ dot ] com .'''
# character may be ' @ ' or ' . ' for character in self . substitutionValues . keys ( ) : for value in self . substitutionValues [ character ] : if value in found : return "i3visio.text" # If none of the values were found . . . Returning as usual the ' i3visio . email ' string . return self . na...