Best Python code snippet using yandex-tank
imagewriters.py
Source:imagewriters.py  
1#!/usr/bin/python2#3## @file4#5# Image file writers for various formats.6#7# Hazen 02/148#9import copy10import struct11import tiffwriter12# Figure out the version of the software, if possible.13have_git = True14try:15    import git16except:17    print "GitPython is not installed, software version information will not be recorded."18    have_git = False19software_version = "NA"20if have_git:21    try:22        repo = git.Repo(".")23        software_version = str(repo.commit('HEAD'))24    except:25        print "Cannot determine software version."26## attrToString27#28# Convert an attribute to a string, or "NA" if the attribute does not exist.29#30# @param obj A Python object.31# @param attr A attribute of the object as a string.32#33# @return The string form of the attribute if it exists, otherwise "NA".34#35def attrToString(obj, attr):36    if hasattr(obj, attr):37        return str(getattr(obj, attr))38    else:39        return "NA"40## availableFileFormats41#42# Return a list of the available movie formats.43#44# @return A python list of file extensions (".dax", ".spe", etc..).45#46def availableFileFormats(ui_mode):47    if (ui_mode == "dual"):48        return [".dax", ".dcf", ".spe", ".tif"]49    else:50        return [".dax", ".spe", ".tif"]51## createFileWriter52#53# This is convenience function which creates the appropriate file writer54# based on the filetype.55#56# @param filetype A string specifying one of the available file formats, e.g. ".dax", ".spe", etc.57# @param filename The name of the file.58# @param parameters A parameters object.59# @param cameras A array of camera names, such as ["camera1"].60#61# @return A file writer object.62#63def createFileWriter(filetype, filename, parameters, cameras):64    if (filetype == ".dax"):65        return DaxFile(filename, parameters, cameras)66    elif (filetype == ".dcf"):67        return DualCameraFormatFile(filename, parameters, cameras)68    elif (filetype == ".spe"):69        return SPEFile(filename, parameters, cameras)70    elif (filetype == ".tif"):71        return TIFFile(filename, parameters, cameras)72    else:73        print "Unknown output file format, defaulting to .dax"74        return DaxFile(filename, parameters, cameras)75## getCameraSize76#77# Returns the AOI of the camera specified by camera_name78#79# @param parameters A parameters object.80# @param camera_name The name of the camera, e.g. "camera1".81#82# @return [x size (pixels), y size (pixels)]83#84def getCameraSize(parameters, camera_name):85    if (hasattr(parameters, camera_name)):86        camera_obj = getattr(parameters, camera_name)87        x_pixels = camera_obj.x_pixels88        y_pixels = camera_obj.y_pixels89    else:90        x_pixels = parameters.x_pixels91        y_pixels = parameters.y_pixels92    return [x_pixels, y_pixels]93## writeInfFile94#95# Inf writing function. We save one of these regardless of the96# output format of the data as it is a easy way to preserve97# the file meta-data.98#99# @param filename The name of the movie file.100# @param filetype The type of the movie file, e.g. ".dax", ".spe", etc.101# @param number_frames The number of frames in the movie.102# @param parameters A parameters object.103# @param camera The camera sub-object of a parameters object.104# @param stage_position The stage position, [stage x, stage y, stage z].105# @param lock_target The focus lock target.106#107def writeInfFile(filename, filetype, number_frames, parameters, camera, stage_position, lock_target):108    c = camera109    fp = open(filename[0:-len(filetype)] + ".inf", "w")110    nl =  "\n"111    p = parameters112    # General info113    fp.write("information file for" + nl)114    fp.write(filename + nl)115    fp.write("software version = " + software_version + nl)116    fp.write("machine name = " + p.setup_name + nl)117    fp.write("parameters file = " + p.parameters_file + nl)118    fp.write("shutters file = " + p.shutters + nl)119    if p.want_big_endian:120        fp.write("data type = 16 bit integers (binary, big endian)" + nl)121    else:122        fp.write("data type = 16 bit integers (binary, little endian)" + nl)123    fp.write("number of frames = " + str(number_frames) + nl)124    # Camera related125    fp.write("frame size = " + str(c.x_pixels * c.y_pixels) + nl)126    fp.write("frame dimensions = " + str(c.x_pixels) + " x " + str(c.y_pixels) + nl)127    fp.write("binning = " + str(c.x_bin) + " x " + str(c.y_bin) + nl)128    if hasattr(c, "frame_transfer_mode") and c.frame_transfer_mode:129        fp.write("CCD mode = frame-transfer" + nl)130    fp.write("horizontal shift speed = " + attrToString(c, "hsspeed") + nl)131    fp.write("vertical shift speed = " + attrToString(c, "vsspeed") + nl)132    fp.write("EMCCD Gain = " + attrToString(c, "emccd_gain") + nl)133    fp.write("Preamp Gain = " + attrToString(c, "preampgain") + nl)134    fp.write("Exposure Time = " + str(c.exposure_value) + nl)135    fp.write("Frames Per Second = " + str(1.0/c.kinetic_value) + nl)136    fp.write("camera temperature (deg. C) = " + attrToString(c, "actual_temperature") + nl)137    fp.write("camera head = " + attrToString(c, "head_model") + nl)138    fp.write("ADChannel = " + attrToString(c, "adchannel") + nl)139    fp.write("scalemax = " + str(c.scalemax) + nl)140    fp.write("scalemin = " + str(c.scalemin) + nl)141    fp.write("x_start = " + str(c.x_start) + nl)142    fp.write("x_end = " + str(c.x_end) + nl)143    fp.write("y_start = " + str(c.y_start) + nl)144    fp.write("y_end = " + str(c.y_end) + nl)145    # Additional info146    fp.write("Stage X = {0:.2f}".format(stage_position[0]) + nl)147    fp.write("Stage Y = {0:.2f}".format(stage_position[1]) + nl)148    fp.write("Stage Z = {0:.2f}".format(stage_position[2]) + nl)149    fp.write("Lock Target = " + str(lock_target) + nl)150    fp.write("notes = " + str(p.notes) + nl)151    fp.close()152#def writeInfFile(file_class, stage_position, lock_target):153#        fp = open(file_class.filename + ".inf", "w")154#        p = file_class.parameters155#        nl =  "\n"156## GenericFile157#158# Generic file writing class159#160class GenericFile:161    ## __init__162    #163    # @param filename The name of the movie file (without an extension).164    # @param parameters A parameters object.165    # @param cameras A python array of camera names, e.g. ["camera1"].166    # @param extension The movie file extension (".spe", ".dax", etc.).167    # @param want_fp (Optional) Create file pointer(s) for saving the movie.168    #169    def __init__(self, filename, parameters, cameras, extension, want_fp = True):170        self.cameras = cameras171        self.parameters = parameters172        self.open = True173        self.lock_target = 0.0174        self.spot_counts = "NA"175        self.stage_position = [0.0, 0.0, 0.0]176        self.filenames = []177        self.file_ptrs = []178        self.number_frames = []179        if (len(cameras) > 1):180            for i in range(len(cameras)):181                fname = filename + "_cam" + str(i+1) + "." + extension182                self.filenames.append(fname)183                if want_fp:184                    self.file_ptrs.append(open(fname, "wb"))185                self.number_frames.append(0)186        else:187            fname = filename + "." + extension188            self.filenames.append(fname)189            if want_fp:190                self.file_ptrs.append(open(fname, "wb"))191            self.number_frames.append(0)192    ## closeFile193    #194    # Close the file pointers (if any) and write the .inf file.195    #196    def closeFile(self):197        198        # Close the files.199        if (len(self.file_ptrs)>0):200            for fp in self.file_ptrs:201                fp.close()202        # Write the inf files.203        for i in range(len(self.filenames)):204            if (hasattr(self.parameters, self.cameras[i])):205                camera = getattr(self.parameters, self.cameras[i])206            else:207                camera = self.parameters208            writeInfFile(self.filenames[i],209                         self.parameters.filetype,210                         self.number_frames[i],211                         self.parameters,212                         camera,213                         self.stage_position,214                         self.lock_target)215        self.open = False216    ## getLockTarget()217    #218    # @return The film's lock target.219    #220    def getLockTarget(self):221        return self.lock_target222    ## getSpotCounts()223    #224    # @return The film's spot counts.225    #226    def getSpotCounts(self):227        return self.spot_counts228    ## setLockTarget()229    #230    # @param lock_target The film's lock target.231    #232    def setLockTarget(self, lock_target):233        self.lock_target = lock_target234    ## setSpotCounts()235    #236    # @param spot_counts The film's spot counts (this is saved as a string).237    #238    def setSpotCounts(self, spot_counts):239        self.spot_counts = spot_counts240    ## setStagePosition()241    #242    # @param stage_position The new stage position.243    #244    def setStagePosition(self, stage_position):245        self.stage_position = stage_position246    ## totalFilmSize247    #248    # @return The total size of the film taken so far in mega-bytes.    249    #250    def totalFilmSize(self):251        total_size = 0.0252        for i in range(len(self.filenames)):253            if (hasattr(self.parameters, self.cameras[i])):254                temp = getattr(self.parameters, self.cameras[i])255            else:256                temp = self.parameters257            total_size += self.number_frames[i] * temp.bytesPerFrame * 0.000000953674258        return total_size259    ## __del__260    #261    # Clean things up if this object is deleted.262    #263    def __del__(self):264        if self.open:265            self.closeFile()266## DaxFile267#268# Dax file writing class.269#270class DaxFile(GenericFile):271    ## __init__272    #273    # @param filename The name of the movie file (without an extension).274    # @param parameters A parameters object.275    # @param cameras A python array of camera names, e.g. ["camera1"].276    #277    def __init__(self, filename, parameters, cameras):278        GenericFile.__init__(self, filename, parameters, cameras, "dax")279    ## saveFrame280    #281    # Saves a frame. If we have two cameras then this first figures282    # out which of the two output files to save it to.283    #284    # @param frame A frame object.285    #286    def saveFrame(self, frame):287        for i in range(len(self.cameras)):288            if (frame.which_camera == self.cameras[i]):289                np_data = frame.getData()290                if self.parameters.want_big_endian:291                    np_data = np_data.byteswap()292                    np_data.tofile(self.file_ptrs[i])293                else:294                    np_data.tofile(self.file_ptrs[i])295                self.number_frames[i] += 1296## DualCameraFormatFile297#298# Dual camera format writing class.299#300# This is just the dax format with the camera number encoded into the301# first pixel of the image. It is useful because writing two files302# at once at a high data rate can overwhelm a hard-drive.303# 304class DualCameraFormatFile(GenericFile):305    ## __init__306    #307    # @param filename The name of the movie file (without an extension).308    # @param parameters A parameters object.309    # @param cameras A python array of camera names, e.g. ["camera1"].310    #311    def __init__(self, filename, parameters, cameras):312        GenericFile.__init__(self, filename, parameters, cameras, "dax")313    ## saveFrame314    #315    # Saves a frame. In this format the camera information (i.e. which316    # camera the frame is from) is encoded into the first pixel of the picture.317    #318    # @param frame A frame object.319    #320    def saveFrame(self, frame):321        #camera_int = int(frame.which_camera[6:])-1322        np_data = frame.getData().copy()323        np_data[0] = int(frame.which_camera[6:])-1324        #temp = chr(camera_int) + chr(camera_int) + copy.copy(frame.data[2:])325        if self.parameters.want_big_endian:326            np_data.tofile(self.file_ptrs[0]).byteswap()327            #self.file_ptrs[0].write(fconv.LEtoBE(temp))328        else:329            np_data.tofile(self.file_ptrs[0])330            #self.file_ptrs[0].write(temp)331        self.number_frames[0] += 1332## SPEFile333#334# SPE file writing class.335#336class SPEFile(GenericFile):337    ## __init__338    #339    # @param filename The name of the movie file (without an extension).340    # @param parameters A parameters object.341    # @param cameras A python array of camera names, e.g. ["camera1"].342    #343    def __init__(self, filename, parameters, cameras):344        GenericFile.__init__(self, filename, parameters, cameras, "spe")345        346        # write headers347        for i in range(len(self.file_ptrs)):348            [x_pixels, y_pixels] = getCameraSize(parameters, self.cameras[i])349            fp = self.file_ptrs[i]350            header = chr(0) * 4100351            fp.write(header)352            fp.seek(42)353            fp.write(struct.pack("h", x_pixels))354            fp.seek(656)355            fp.write(struct.pack("h", y_pixels))356            fp.seek(108)357            fp.write(struct.pack("h", 3))358            fp.seek(4100)359    ## saveFrame360    #361    # @param frame A frame object.362    #363    def saveFrame(self, frame):364        for i in range(len(self.cameras)):365            if (frame.which_camera == self.cameras[i]):366                np_data = frame.getData()367                np_data.tofile(self.file_ptrs[i])368                #self.file_ptrs[i].write(frame.data)369                370                self.number_frames[i] += 1371    ## closeFile372    #373    # Writes the file size into the header part of the spe file and374    # then closes the file.375    #376    def closeFile(self):377        # write film length & close the file378        for i in range(len(self.file_ptrs)):379            self.file_ptrs[i].seek(1446)380            self.file_ptrs[i].write(struct.pack("i", self.number_frames[i]))381        GenericFile.closeFile(self)382## TIFFile383#384# TIF file writing class. Note that this is a normal tif file format385# and not a big tif format so the maximum size is limited to 4GB386# more or less.387#388class TIFFile(GenericFile):389    ## __init__390    #391    # Creates the tif writer(s) for saving in tif format.392    #393    # @param filename The name of the movie file (without an extension).394    # @param parameters A parameters object.395    # @param cameras A python array of camera names, e.g. ["camera1"].396    #397    def __init__(self, filename, parameters, cameras):398        GenericFile.__init__(self, filename, parameters, cameras, "tif", want_fp = False)399        self.tif_writers = []400        for i in range(len(cameras)):401            tif_writer = tiffwriter.TiffWriter(self.filenames[i],402                                               software = "hal4000")403            self.tif_writers.append(tif_writer)404    ## saveFrame405    #406    # @param frame A frame object.407    #408    def saveFrame(self, frame):409        for i in range(len(self.cameras)):410            if (frame.which_camera == self.cameras[i]):411                [x_pixels, y_pixels] = getCameraSize(self.parameters, self.cameras[i])412                self.tif_writers[i].addFrame(frame.getData(), x_pixels, y_pixels)413                self.number_frames[i] += 1414    ## closeFile415    #416    # Closes the tif file writers.417    #418    def closeFile(self):419        for writer in self.tif_writers:420            writer.close()421        GenericFile.closeFile(self)422#423# Testing424# 425if __name__ == "__main__":426    from ctypes import *427    class Parameters:428        def __init__(self, x_pixels, y_pixels, x_bin, y_bin):429            self.x_pixels = x_pixels430            self.y_pixels = y_pixels431            self.x_bin = x_bin432            self.y_bin = y_bin433    parameters = Parameters(100, 100, 1, 1)434    daxfile = DaxFile("test", parameters)435    frame = create_string_buffer(parameters.x_pixels * parameters.y_pixels)436    daxfile.saveFrame(frame)437    daxfile.closeFile()438#439# The MIT License440#441# Copyright (c) 2014 Zhuang Lab, Harvard University442#443# Permission is hereby granted, free of charge, to any person obtaining a copy444# of this software and associated documentation files (the "Software"), to deal445# in the Software without restriction, including without limitation the rights446# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell447# copies of the Software, and to permit persons to whom the Software is448# furnished to do so, subject to the following conditions:449#450# The above copyright notice and this permission notice shall be included in451# all copies or substantial portions of the Software.452#453# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR454# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,455# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE456# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER457# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,458# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN459# THE SOFTWARE.460#...file_lock.py
Source:file_lock.py  
1# Copyright 2015 VMware, Inc. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License"); you may not4# use this file except in compliance with the License.  You may obtain a copy5# of the License at http://www.apache.org/licenses/LICENSE-2.06#7# Unless required by applicable law or agreed to in writing, software8# distributed under the License is distributed on an "AS IS" BASIS, without9# warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED.  See the10# License for then specific language governing permissions and limitations11# under the License.12import abc13from enum import Enum14import errno15import fcntl16import logging17import os18import shutil19import time20import uuid21from gen.resource.ttypes import DatastoreType22LOCK_EXTENSION = "ec_lock"23# From lib/public/fileIO.h24O_EXCLUSIVE_LOCK = 0x1000000025class UnsupportedFileSystem(Exception):26    """27    Exception thrown if we are trying to create a file on a28    filesystem that we don't support.29    """30class InvalidFile(Exception):31    """32    Exception thrown if the file is invalid or can't be read.33    """34    pass35class AcquireLockFailure(Exception):36    """37    Exception thrown if the lock file can't be acquired38    """39    pass40class _FileSystemType(Enum):41    # Vmware VMFS filesystem, implies we are running on ESX.42    vmfs = 043    # NFS, also implies we are running in ESX.44    vmw_nfs = 145    # VSAN46    vsan = 247    # Any posix compliant implementation like ext3, assumes a non esx48    # runtime (e.g. dev setup/fake agent)49    posix = 350    @staticmethod51    def from_thrift(thrift_fs_type):52        """53        Returns the ref count type to use for the datastore type54        """55        if thrift_fs_type is DatastoreType.LOCAL_VMFS or thrift_fs_type is DatastoreType.SHARED_VMFS:56            return _FileSystemType.vmfs57        if thrift_fs_type is DatastoreType.NFS_3 or thrift_fs_type is DatastoreType.NFS_41:58            return _FileSystemType.vmw_nfs59        if thrift_fs_type is DatastoreType.VSAN:60            return _FileSystemType.vsan61        if thrift_fs_type is DatastoreType.EXT3:62            return _FileSystemType.posix63        raise UnsupportedFileSystem("FS type %d" % thrift_fs_type)64class _FileIOBaseImpl(object):65    """ Interface for file i/o.66        Specific filesystem implementations will extend this class.67    """68    __metaclass__ = abc.ABCMeta69    @abc.abstractmethod70    def build_lock_path(self, lock_target):71        pass72    @abc.abstractmethod73    def lock_and_open(self, file_name):74        """75        Lock the file with an exclusive lock and return the open file76        descriptor77        :param: The fully qualified file path for the filename.78        :type: string79        :returns: open file descriptor80        :rtype: int81        raises AcquireLockFailure if file is already locked.82        raises InvalidFile for all other failures, e.g. permissions issues.83        """84        pass85class _EsxFileIOImpl(_FileIOBaseImpl):86    """87    File i/o implementation for NFS and VMFS.88    Issues relating to vmfs:89        1 - Atomic Move: Atomic move only works if the destination file_name is90        not locked. Hence, the scheme of writing to a temp file while holding a91        lock on the ref file and attempting an atomic move to replace the92        original ref file doesn't work on vmfs.93        2 - os.ftruncate doesn't work.94    While writing we just lseek to the start of the file and clobber the write95    with the data we have. This prevents the allocation of new blocks during a96    file write.97    NFS:98        We just reuse the implementation for VMFS here for NFS.99        NFS_FILE_SYNC is always set for all writes so writes update both data100        and metadata on media when it is processed by NFS server.101        NFSv3 on ESX uses advisory locking and NFSv4 uses mandatory locking,102        it is transparent to user space here.103    """104    def build_lock_path(self, lock_target):105        return "%s.%s" % (lock_target, LOCK_EXTENSION)106    def lock_and_open(self, file_name):107        """108        See comments in _FileIOBaseImpl109        """110        # Opening with O_EXCLUSIVE_LOCK will cause the exclusive FS lock to be111        # held.112        # If the file doesn't exist we need to create a file so we prevent113        # concurrent edits of the file.114        try:115            fd = os.open(file_name, os.O_CREAT | os.O_RDWR | os.O_DIRECT | O_EXCLUSIVE_LOCK)116        except OSError as e:117            if e.errno == errno.EBUSY:118                logging.info("File %s already locked" % file_name)119                raise AcquireLockFailure("File %s locked" % file_name)120            else:121                logging.info("Failed to open file:", exc_info=True)122                raise InvalidFile("Can't access file %s" % file_name)123        except Exception:124            logging.info("Failed to open file:", exc_info=True)125            raise InvalidFile("Can't read file %s " % file_name)126        return fd127class _VsanFileIOImpl(_FileIOBaseImpl):128    """129    Implementation of file i/o operations for VSAN130    """131    def build_lock_path(self, lock_target):132        return os.path.join(lock_target, "lock.%s" % LOCK_EXTENSION)133    def lock_and_open(self, file_name):134        # Opening with O_EXCLUSIVE_LOCK will cause the exclusive FS lock to be135        # held.136        # If the file doesn't exist we need to create a file so we prevent137        # concurrent edits of the file.138        try:139            fd = os.open(file_name, os.O_CREAT | os.O_RDWR | os.O_DIRECT | O_EXCLUSIVE_LOCK)140        except OSError as e:141            if e.errno == errno.EBUSY:142                logging.info("File %s already locked" % file_name)143                raise AcquireLockFailure("File %s locked" % file_name)144            else:145                logging.info("Failed to open file:", exc_info=True)146                raise InvalidFile("Can't access file %s" % file_name)147        except Exception:148            logging.info("Failed to open file:", exc_info=True)149            raise InvalidFile("Can't read file %s " % file_name)150        return fd151class _PosixFileIOImpl(_FileIOBaseImpl):152    """153    Implementation of file i/o operations for posix FS154    """155    def build_lock_path(self, lock_target):156        return "%s.%s" % (lock_target, LOCK_EXTENSION)157    def lock_and_open(self, file_name):158        """159        See comments in _FileIOBaseImpl160        Lock the file and open it on ext3 (posix filesystems)161        Doesn't use O_DIRECT as python os.read() call doesn't work for162        O_DIRECT, which should be ok for the fake agent.163        """164        # Now open the file.165        try:166            fd = os.open(file_name, os.O_CREAT | os.O_RDWR)167            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)168        except IOError as e:169            if (e.errno == errno.EAGAIN):170                logging.info("File %s already locked" % file_name)171                raise AcquireLockFailure("File %s locked" % file_name)172        except Exception:173            # The open fd for the lock file will be closed by the subsequent174            # call to self._close()175            logging.info("Failed to open file:", exc_info=True)176            raise InvalidFile("Can't read file %s " % file_name)177        return fd178class FileIOImplFactory(object):179    """ Simple factory class to create filesystem specific i/o objects """180    file_io_objects = {_FileSystemType.vmfs: _EsxFileIOImpl,181                       _FileSystemType.vmw_nfs: _EsxFileIOImpl,182                       _FileSystemType.vsan: _VsanFileIOImpl,183                       _FileSystemType.posix: _PosixFileIOImpl}184    @staticmethod185    def createFileIOImplObj(thrift_type):186        """ Create a i/o class based on the thrift type """187        return FileIOImplFactory.file_io_objects[188            _FileSystemType.from_thrift(thrift_type)]()189class _FileLock(object):190    """ Class implementing filesystem specific lock operations """191    def __init__(self, fs_type):192        """193        Constructor194        fs_type: The thrift fs_type195        """196        self._f_obj = FileIOImplFactory.createFileIOImplObj(fs_type)197        self._fds = []198        self._closed = False199    def build_lock_path(self, lock_target):200        return self._f_obj.build_lock_path(lock_target)201    def lock_and_open(self, file_name, retry=0, wait=0.1):202        """203        Lock and open a file with the specified filename.204        retry: number of times to retry fetching lock205        wait: number of seconds between retries206        return: file descriptor of the opened file.207        rtype: int208        """209        while retry >= 0:210            try:211                return self._lock_and_open(file_name)212            except (AcquireLockFailure, InvalidFile):213                time.sleep(wait)214                retry -= 1215        raise216    def _lock_and_open(self, file_name):217        fd = self._f_obj.lock_and_open(file_name)218        # remember the open file handles.219        self._fds.append(fd)220        self._closed = False221        return fd222    @property223    def closed(self):224        return self._closed225    def close(self):226        """ Close the open file descriptors """227        for fd in self._fds:228            if fd:229                try:230                    os.close(fd)231                except:232                    logging.info("Failed to close file", exc_info=True)233        self._fds = []234        self._closed = True235    def __enter__(self):236        return self237    def __exit__(self, type, value, traceback):238        if not self._closed:239            self.close()240class FileBackedLock(object):241    """Class implementing FileIO-based lock on a single filesystem path242    The class can be used as a context manager. Alternatively instances of243    this class can be explicitly locked or unlocked.244    For now there is no support for lock expiration/renewal. The one main case245    of needing to clear locks on abnormal termination of process holding the246    locks is already handled by the underlying (nfs/vmfs) file system.247    TODO(vui): for posix NFS, to handle case where the process dies without248    getting a chance to close the lock file (e.g. host lost connectivity to NFS249    share), the lock acquisition logic can determine lock staleness by checking250    the last modification time of the lock file.251    """252    def __init__(self, lock_target, ds_type, retry=0, wait_secs=1.0):253        """254        :param path: file system path based on which the lock is created255        :param ds_type: DatastoreType256        :param retry: number of times to retry fetching lock257        :param wait_secs: number of seconds between retries258        """259        self._file_io = _FileLock(ds_type)260        self._lock_path = self._file_io.build_lock_path(lock_target)261        self._acquired = False262        self.retry = retry263        self.wait_secs = wait_secs264    def lock(self):265        try:266            self._file_io.lock_and_open(self._lock_path, self.retry, self.wait_secs)267            self._acquired = True268        except (AcquireLockFailure, InvalidFile):269            logging.info("Unable to lock %s", self._lock_path)270            raise271        return self272    def __enter__(self):273        return self.lock()274    def unlock(self):275        if not self._acquired:276            return277        # Move lock file away to another location while locked before278        # deleting said location. This is to guard against someone else279        # relocking the file prior to us deleting it.280        lock_path_to_delete = "%s.%s" % (self._lock_path, str(uuid.uuid4()))281        try:282            shutil.move(self._lock_path, lock_path_to_delete)283            self._file_io.close()284            os.remove(lock_path_to_delete)285        except:286            logging.info("Unable to clean up lock file %s", self._lock_path, exc_info=True)287            if not self._file_io.closed:288                self._file_io.close()289        self._acquired = False290    def __exit__(self, type, value, traceback):291        self.unlock()292    def acquired(self):...genconstskeyboard_keys.py
Source:genconstskeyboard_keys.py  
1# Embedded file name: scripts/client/gui/Scaleform/genConsts/KEYBOARD_KEYS.py2class KEYBOARD_KEYS(object):3    """4    DO NOT MODIFY!5    Generated with yaml.6    __author__ = 'yaml_processor'7    """8    FORWARD = 'forward'9    BACKWARD = 'backward'10    LEFT = 'left'11    RIGHT = 'right'12    AUTO_ROTATION = 'auto_rotation'13    FORWARD_CRUISE = 'forward_cruise'14    BACKWARD_CRUISE = 'backward_cruise'15    FIRE = 'fire'16    LOCK_TARGET = 'lock_target'17    LOCK_TARGET_OFF = 'lock_target_off'18    ALTERNATE_MODE = 'alternate_mode'19    RELOAD_PARTIAL_CLIP = 'reloadPartialClip'20    SHOW_RADIAL_MENU = 'showRadialMenu'21    ATTACK = 'attack'22    PUSH_TO_TALK = 'pushToTalk'23    VISIBLE = 'visible'24    SHOW_HUD = 'showHUD'25    SHOW_EX_PLAYER_INFO = 'showExPlayerInfo'26    TOGGLE_PLAYER_PANEL_MODES = 'togglePlayerPanelModes'...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
