当前位置: 首页>>代码示例>>Python>>正文


Python DeferredLock.acquire方法代码示例

本文整理汇总了Python中twisted.internet.defer.DeferredLock.acquire方法的典型用法代码示例。如果您正苦于以下问题:Python DeferredLock.acquire方法的具体用法?Python DeferredLock.acquire怎么用?Python DeferredLock.acquire使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer.DeferredLock的用法示例。


在下文中一共展示了DeferredLock.acquire方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Pulser_729

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class Pulser_729(LabradServer):
    
    name = 'Pulser_729'
       
    def initServer(self):
        self.api  = api()
        self.inCommunication = DeferredLock()
        self.initializeBoard()
    
    def initializeBoard(self):
        connected = self.api.connectOKBoard()
        if not connected:
            raise Exception("Pulser Not Found")
    
    @setting(0, 'Reset DDS', returns = '')
    def resetDDS(self , c):
        """
        Reset the ram position to 0
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.resetAllDDS)
        self.inCommunication.release()
        
    @setting(1, "Program DDS", program = '*(is)', returns = '')
    def programDDS(self, c, program):
        """
        Programs the DDS, the input is a tuple of channel numbers and buf objects for the channels
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self._programDDSSequence, program)
        self.inCommunication.release()
    
    @setting(2, "Reinitialize DDS", returns = '')
    def reinitializeDDS(self, c):
        """
        Reprograms the DDS chip to its initial state
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.initializeDDS)
        self.inCommunication.release()
    
    def _programDDSSequence(self, program):
        '''takes the parsed dds sequence and programs the board with it'''
        for chan, buf in program:
            self.api.setDDSchannel(chan)
            self.api.programDDS(buf)
        self.api.resetAllDDS()
    
    def wait(self, seconds, result=None):
        """Returns a deferred that will be fired later"""
        d = Deferred()
        reactor.callLater(seconds, d.callback, result)
        return d
开发者ID:ahusain,项目名称:Haeffner-Lab-LabRAD-Tools,代码行数:55,代码来源:pulser_729.py

示例2: Client

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class Client(object):
    def __init__(self, specFilename, exchange='signals'):
        self.exchange = exchange
        spec = txamqp.spec.load(specFilename)

        delegate = TwistedDelegate()
        self.clientConnected = ClientCreator(reactor, AMQClient,
                                             delegate=delegate, vhost="/",
                                     spec=spec).connectTCP("localhost", 5672)
        self.conn = None
        self.chan = None
        self.finishLock = DeferredLock()

    @inlineCallbacks
    def finishChannelOpen(self):
        yield self.finishLock.acquire()
        if self.conn is None:
            print "opening connection for", self
            self.conn = yield self.clientConnected

            authentication = {"LOGIN": "guest", "PASSWORD": "guest"}
            yield self.conn.start(authentication)

        if self.chan is None:
            self.chan = yield self.conn.channel(1)
            yield self.chan.channel_open()
            yield self.newChan()
            print "made channel for", self
        self.finishLock.release()
            
    def newChan(self):
        # called once when the new channel is opened
        return succeed(None)
开发者ID:drewp,项目名称:magma,代码行数:35,代码来源:mqclient.py

示例3: acquire

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
    def acquire(self, timeout=None):
        """
        This method operates the same as :meth:`DeferredLock.acquire` does
        except it requires a timeout argument.

        :param int timeout:
            The number of seconds to wait before timing out.

        :raises LockTimeoutError:
            Raised if the timeout was reached before we could acquire
            the lock.
        """
        assert timeout is None \
            or isinstance(timeout, (int, float)) and timeout > 0

        lock = DeferredLock.acquire(self)
        if timeout is None:
            return lock

        # Schedule a call to trigger finished.errback() which will raise
        # an exception.  If lock finishes first however cancel the timeout
        # and unlock the lock by calling finished.
        finished = Deferred()
        lock.addCallback(
            self._cancel_timeout,
            reactor.callLater(timeout, self._timeout, finished))
        lock.addCallback(self._call_callback, finished)

        return finished
开发者ID:xlhtc007,项目名称:pyfarm-agent,代码行数:31,代码来源:utility.py

示例4: add_scan_to_queue

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
 def add_scan_to_queue(self, scan, priority = 'Normal'):
     #increment counter
     scan_id = self.scan_ID_counter
     self.scan_ID_counter += 1
     #add to queue
     if priority == 'Normal':
         order = self.queue.put_last(1, (scan_id, scan,  1))
     elif priority == 'First in Queue':
         order = self.queue.put_first(1, (scan_id, scan, 1))
     elif priority == 'Pause All Others':
         order = self.queue.put_last(0, (scan_id, scan, 0))
     else: 
         raise Exception ("Unrecognized priority type")
     self.signals.on_queued_new_script((scan_id, scan.name, order))
     d = DeferredLock()
     d.acquire()
     self.running_locks[scan_id] = d
     self.launch_scripts()
     return scan_id
开发者ID:HaeffnerLab,项目名称:Haeffner-Lab-LabRAD-Tools,代码行数:21,代码来源:scheduler.py

示例5: __init__

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class InterfaceUpper:
    def __init__(self, iface):
        self.iface = iface
        self._lock = DeferredLock()
        CompositeStatePublisher(lambda x: x, [
            netlink_monitor.get_state_publisher(iface, IFSTATE.PLUGGED),
            netlink_monitor.get_state_publisher(iface, IFSTATE.UP),
        ]).subscribe(self._cb)
        self._is_shutdown = False
        self.state = None
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
   
    @inlineCallbacks
    def restart(self):
        yield self._lock.acquire()
        try:
            yield system.system('ifconfig', self.iface, '0.0.0.0')
            yield system.system('ifconfig', self.iface, 'down')
        finally:
            self._lock.release()

    @inlineCallbacks
    def _cb(self, old_state, new_state):
        plugged, up = new_state
        self.state = new_state
        if plugged and not up and not self._is_shutdown:
            yield self._lock.acquire()
            try:
                yield system.system('ifconfig', self.iface, 'up')
            finally:
                self._lock.release()

    @inlineCallbacks
    def _shutdown(self):
        self._is_shutdown = True
        if self.state:
            yield self.restart()
开发者ID:PR2,项目名称:linux_networking,代码行数:39,代码来源:interface_upper.py

示例6: NotificationConnector

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class NotificationConnector(object):
    """Provide ready-to-use AMQP channels."""

    def __init__(self, service, clock=reactor):
        """
        @param service: An object implementing the same whenConnected() API as
            the twisted.application.internet.ClientService class.
        @param clock: An object implementing IReactorTime.
        """
        self._service = service
        self._clock = clock
        self._channel = None
        self._channel_lock = DeferredLock()

    @inlineCallbacks
    def __call__(self):
        """
        @return: A deferred firing with a ready-to-use txamqp.protocol.Channel.
        """
        # Serialize calls, in order to setup new channels only once.
        yield self._channel_lock.acquire()
        try:
            if self._channel and self._channel.client.closed:
                # If we have a client but it's closed, let's wait for it to be
                # fully disconnected and spin a reactor iteration to give
                # change to the AMQClient.connectionLost callback chain to
                # settle (in particular our ClientService will be notified and
                # will start connecting again).
                yield self._channel.client.disconnected.wait()
                yield deferLater(self._clock, 0, lambda: None)

            client = yield self._service.whenConnected()
            channel = yield client.channel(1)
            # Check if we got a new channel, and initialize it if so.
            if channel is not self._channel:
                self._channel = channel
                yield self._channel.channel_open()
                # This tells the broker to deliver us at most one message at
                # a time to support using multiple processes (e.g. in a
                # load-balanced/HA deployment). If NotificationSource.get()
                # gets called against the same UUID first by process A and then
                # when it completes by process B, we're guaranteed that process
                # B will see the very next message in the queue, because
                # process A hasn't fetched any more messages than the one it
                # received. See #729140.
                yield self._channel.basic_qos(prefetch_count=1)
        finally:
            self._channel_lock.release()
        returnValue(self._channel)
开发者ID:CanonicalLtd,项目名称:txlongpoll,代码行数:51,代码来源:notification.py

示例7: emailer

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class emailer( LabradServer ):
    name = 'Email Server'
    
    @inlineCallbacks
    def initServer( self ):
        self.username, self.fromaddr, self.password = yield self.getInfoReg()
        self.password = base64.b64decode(self.password)
        self.toaddrs = {}
        self.smtp = 'smtp.gmail.com:587'
        self.sending = DeferredLock()
    
    @inlineCallbacks
    def getInfoReg(self):
        reg = self.client.registry
        yield reg.cd(['Servers','Email Server'])
        username = yield reg.get('username')
        fromaddr = yield reg.get('address')
        password = yield reg.get('password')
        returnValue([username,fromaddr,password])
        
    @setting(0, "Set Recipients", recepients = '*s', returns = '')
    def setRecepients(self, c, recepients):
        """Set the recipients of the email as a list of strings of email addresses"""
        self.toaddrs[c.ID] = recepients
    
    @setting(1, "Send", subject = 's', message = 's', returns = '')
    def selectDP(self, c, subject, message):
        """Select Double Pass in the current context"""
        if not self.toaddrs[c.ID]: raise Exception("Recipients not set")
        yield self.sending.acquire()  
        session = smtplib.SMTP(self.smtp)
        session.starttls()
        session.login(self.username,self.password)
        toaddrs = self.toaddrs[c.ID]
        msg = MIMEMultipart()
        msg['From'] = self.fromaddr
        msg['To'] = COMMASPACE.join(toaddrs)
        msg['Subject'] = subject
        msg.attach(MIMEText(message, 'plain'))    
        session.sendmail(self.fromaddr, toaddrs, msg.as_string())
        session.quit()
        self.sending.release()
    
    def initContext(self, c):
        """Initialize a new context object."""
        pass
    
    def expireContext(self, c):
        del(self.toaddrs[c.ID])
开发者ID:HaeffnerLab,项目名称:HaeffnerLabLattice,代码行数:51,代码来源:emailer.py

示例8: __init__

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class _DhcpSetterCommon:
    # Provides support common code for shutting down on shutdown, and
    # handles locking.
    def __init__(self):
        self._lock = DeferredLock()
        self.is_shutdown = False
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
    
    @inlineCallbacks
    def _cb(self, old_state, new_state):
        if self.is_shutdown:
            return
        yield self._lock.acquire()
        try:
            yield self._locked_cb(old_state, new_state)
        finally:
            self._lock.release()
    
    @inlineCallbacks
    def _shutdown(self):
        #print "Shutdown", self
        yield self._cb(None, None)
        self.is_shutdown = True
开发者ID:PR2,项目名称:linux_networking,代码行数:25,代码来源:dhcp_apply_config.py

示例9: ZipStream

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class ZipStream(object):

    def __init__(self, consumer):
        self.consumer = consumer
        assert IConsumer.implementedBy(consumer.__class__)

        self._producers = []

        self._sendingLock = DeferredLock()
        self._localHeaderLength = 0
        self._centralDirectoryLength = 0


    @inlineCallbacks
    def addProducer(self, producer):
        assert IZippyProducer.implementedBy(producer.__class__)

        size = yield producer.size()
        timestamp = yield producer.timestamp()
        crc32 = yield producer.crc32()
        key = yield producer.key()

        yield self._sendingLock.acquire()

        self._producers.append((producer, self._localHeaderLength))

        # local file header
        timestamp = dos_timestamp(timestamp)
        localHeader = struct.pack('<L5H3L2H', # format 
                                  0x04034b50, # magic (4 bytes)
                                  20, # version needed to extract (2 bytes)
                                  0, # general purpose bit flag (2 bytes)
                                  0, # compression method (2 bytes)
                                  timestamp[1], # last mod file time (2 bytes)
                                  timestamp[0], # last mod file date (2 bytes)
                                  crc32 & 0xffffffff, # CRC (4 bytes)
                                  size, # compressed size (4 bytes)
                                  size, # uncompressed size (4 bytes)
                                  len(key), # file name length (2 bytes)
                                  0, # extra field length (2 bytes)
                                 )

        localHeader += producer.key()
        self.consumer.write(localHeader)
        self._localHeaderLength += len(localHeader) + size

        # file data
        yield producer.beginProducing(self.consumer)

        self._sendingLock.release()


    @inlineCallbacks
    def centralDirectory(self):
        yield self._sendingLock.acquire()

        # file header
        for producer, offset in self._producers:
            size = yield producer.size()
            timestamp = yield producer.timestamp()
            timestamp = dos_timestamp(timestamp)
            crc32 = yield producer.crc32()
            key = yield producer.key()

            fileHeader = struct.pack('<L6H3L5H2L', # format
                                     0x02014b50, # magic (4 bytes)
                                     20, # version made by (2 bytes)
                                     20, # version needed to extract (2 bytes)
                                     0, # general purpose bit flag (2 bytes)
                                     0, # compression method (2 bytes)
                                     timestamp[1], # last mod file time (2 bytes)
                                     timestamp[0], # last mod file date (2 bytes)
                                     crc32 & 0xffffffff, # CRC (4 bytes)
                                     size, # compressed size (4 bytes)
                                     size, # uncompressed size(4 bytes)
                                     len(key), # file name length (2 bytes)
                                     0, # extra field length (2 bytes)
                                     0, # file comment length (2 bytes)
                                     0, # disk number start (2 bytes)
                                     0, # internal file attributes (2 bytes)
                                     0, # external file attributes (4 bytes)
                                     offset, # relative offset of local header (4 bytes)
                                    )

            fileHeader += producer.key()
            self._centralDirectoryLength += len(fileHeader)
            self.consumer.write(fileHeader)


        # end of central directory header
        endHeader = struct.pack('<L4H2LH', # format
                                0x06054b50, # magic (4 bytes)
                                0, # disk number (2 bytes)
                                0, # disk number with start of central directory (2 bytes)
                                len(self._producers), # total central directory entries on this disk (2 bytes)
                                len(self._producers), # total central directory entries (2 bytes)
                                self._centralDirectoryLength, # size of central directory (4 bytes)
                                self._localHeaderLength, # offset of start of central directory with respect to the starting disk number (4 bytes)
                                0, # zip file comment length (2 bytes)
                               )
#.........这里部分代码省略.........
开发者ID:unshift,项目名称:zippy2,代码行数:103,代码来源:stream.py

示例10: CFProcessor

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class CFProcessor(service.Service):
    implements(interfaces.IProcessor)

    def __init__(self, name, conf):
        _log.info("CF_INIT %s", name)
        self.name, self.conf = name, conf
        self.channel_dict = defaultdict(list)
        self.iocs = dict()
        self.client = None
        self.currentTime = getCurrentTime
        self.lock = DeferredLock()

    def startService(self):
        service.Service.startService(self)
        self.running = 1
        _log.info("CF_START")
        from channelfinder import ChannelFinderClient
        # Using the default python cf-client.
        # The usr, username, and password are provided by the channelfinder._conf module.
        if self.client is None:  # For setting up mock test client
            self.client = ChannelFinderClient()
        self.clean_service()

    def stopService(self):
        service.Service.stopService(self)
        #Set channels to inactive and close connection to client
        self.running = 0
        self.clean_service()
        _log.info("CF_STOP")

    @defer.inlineCallbacks
    def commit(self, transaction_record):
        yield self.lock.acquire()
        try:
            yield deferToThread(self.__commit__, transaction_record)
        finally:
            self.lock.release()

    def __commit__(self, TR):
        _log.debug("CF_COMMIT %s", TR.infos.items())
        pvNames = [unicode(rname, "utf-8") for rid, (rname, rtype) in TR.addrec.iteritems()]
        delrec = list(TR.delrec)
        iocName = TR.src.port
        hostName = TR.src.host
        iocid = hostName + ":" + str(iocName)
        owner = TR.infos.get('CF_USERNAME') or TR.infos.get('ENGINEER') or self.conf.get('username', 'cfstore')
        time = self.currentTime()
        if TR.initial:
            self.iocs[iocid] = {"iocname": iocName, "hostname": hostName, "owner": owner, "channelcount": 0}  # add IOC to source list
        if not TR.connected:
            delrec.extend(self.channel_dict.keys())
        for pv in pvNames:
            self.channel_dict[pv].append(iocid)  # add iocname to pvName in dict
            self.iocs[iocid]["channelcount"] += 1
        for pv in delrec:
            if iocid in self.channel_dict[pv]:
                self.channel_dict[pv].remove(iocid)
                self.iocs[iocid]["channelcount"] -= 1
                if self.iocs[iocid]['channelcount'] == 0:
                    self.iocs.pop(iocid, None)
                elif self.iocs[iocid]['channelcount'] < 0:
                    _log.error("channel count negative!")
                if len(self.channel_dict[pv]) <= 0:  # case: channel has no more iocs
                    del self.channel_dict[pv]
        poll(__updateCF__, self.client, pvNames, delrec, self.channel_dict, self.iocs, hostName, iocName, time, owner)
        dict_to_file(self.channel_dict, self.iocs, self.conf)

    def clean_service(self):
        sleep = 1
        retry_limit = 5
        owner = self.conf.get('username', 'cfstore')
        while 1:
            try:
                _log.debug("Cleaning service...")
                channels = self.client.findByArgs([('pvStatus', 'Active')])
                if channels is not None:
                    new_channels = []
                    for ch in channels or []:
                        new_channels.append(ch[u'name'])
                    if len(new_channels) > 0:
                        self.client.update(property={u'name': 'pvStatus', u'owner': owner, u'value': "Inactive"},
                                           channelNames=new_channels)
                    _log.debug("Service clean.")
                    return
            except RequestException:
                _log.exception("cleaning failed, retrying: ")

            time.sleep(min(60, sleep))
            sleep *= 1.5
            if self.running == 0 and sleep >= retry_limit:
                _log.debug("Abandoning clean.")
                return
开发者ID:mskinner5278,项目名称:recsync,代码行数:94,代码来源:cfstore.py

示例11: TriggerFPGA

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class TriggerFPGA(LabradServer):
    name = 'Trigger'
    onNewUpdate = Signal(SIGNALID, 'signal: switch toggled', '(sb)')
    
    def initServer(self):
        self.inCommunication = DeferredLock()
        self.connectOKBoard()
        #create dictionary for triggers and switches in the form 'trigger':channel;'switch:(channel , logicnotnegated, state'
        #the state written below represents the initial state of the server
        self.dict = {
                     'Triggers':{'PaulBox':0},
                     'Switches':{'866':[0x01,True, True], 'BluePI':[0x02,True, False], '397LocalHeating':[0x04,True,False]}
                     }
        self.initializeChannels()
        self.listeners = set()
        
    def connectOKBoard(self):
        self.xem = None
        fp = ok.FrontPanel()
        module_count = fp.GetDeviceCount()
        print "Found {} unused modules".format(module_count)
        for i in range(module_count):
            serial = fp.GetDeviceListSerial(i)
            tmp = ok.FrontPanel()
            tmp.OpenBySerial(serial)
            id = tmp.GetDeviceID()
            if id == okDeviceID:
                self.xem = tmp
                print 'Connected to {}'.format(id)
                self.programOKBoard(self.xem)
                return
        print 'Not found {}'.format(okDeviceID)
        print 'Will try again in {} seconds'.format(devicePollingPeriod)
        reactor.callLater(devicePollingPeriod, self.connectOKBoard)
    
    def programOKBoard(self, xem):
        print 'Programming FPGA'
        basepath = os.environ.get('LABRADPATH',None)
        if not basepath:
            raise Exception('Please set your LABRADPATH environment variable')
        path = os.path.join(basepath,'sqip/okfpgaservers/trigger.bit')
        prog = xem.ConfigureFPGA(path)
        if prog: raise("Not able to program FPGA")
        pll = ok.PLL22150()
        xem.GetEepromPLL22150Configuration(pll)
        pll.SetDiv1(pll.DivSrc_VCO,4)
        xem.SetPLL22150Configuration(pll)
    
    def initializeChannels(self):
        for switchName in self.dict['Switches'].keys():
            channel = self.dict['Switches'][switchName][0]
            value = self.dict['Switches'][switchName][1]
            initialize = self.dict['Switches'][switchName][2]
            if initialize:
                print 'initializing {0} to {1}'.format(switchName, value)
                self._switch( channel, value)
        
    def _isSequenceDone(self):
        self.xem.UpdateTriggerOuts()
        return self.xem.IsTriggered(0x6A,0b00000001)
    
    def _trigger(self, channel):
        self.xem.ActivateTriggerIn(0x40, channel)
    
    def _switch(self, channel, value):
        if value:
            self.xem.SetWireInValue(0x00,channel,channel)
        else:
            self.xem.SetWireInValue(0x00,0x00,channel)
        self.xem.UpdateWireIns()
    
    @setting(0, 'Get Trigger Channels', returns = '*s')
    def getTriggerChannels(self, c):
        """
        Returns available channels for triggering
        """
        return self.dict['Triggers'].keys()
    
    @setting(1, 'Get Switching Channels', returns = '*s')
    def getSwitchingChannels(self, c):
        """
        Returns available channels for switching
        """
        return self.dict['Switches'].keys()
    
    @setting(2, 'Trigger', channelName = 's')
    def trigger(self, c, channelName):
        """
        Triggers the select channel
        """
        if channelName not in self.dict['Triggers'].keys(): raise Exception("Incorrect Channel")
        yield self.inCommunication.acquire()
        channel = self.dict['Triggers'][channelName]
        yield deferToThread(self._trigger, channel)
        yield self.inCommunication.release()
    
    @setting(3, 'Switch', channelName = 's', state= 'b')
    def switch(self, c, channelName, state):  
        """
        Switches the given channel
#.........这里部分代码省略.........
开发者ID:noli,项目名称:HaeffnerLabSQIP,代码行数:103,代码来源:trigger_ok.py

示例12: Dataset

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class Dataset(QtCore.QObject):
    
    def __init__(self, data_vault, context, dataset_location,reactor):
        super(Dataset, self).__init__()
        self.data = None
        self.accessingData = DeferredLock()
        self.reactor = reactor
        self.dataset_location = dataset_location
        self.data_vault = data_vault
        self.updateCounter = 0
        self.context = context
        self.connectDataVault()
        self.setupListeners()

    @inlineCallbacks
    def connectDataVault(self):
        yield self.data_vault.cd(self.dataset_location[0], context = self.context)
        path, dataset_name = yield self.data_vault.open(self.dataset_location[1], context = self.context)
        self.dataset_name = dataset_name

    @inlineCallbacks
    def setupListeners(self):
        yield self.data_vault.signal__data_available(11111, context = self.context)
        yield self.data_vault.addListener(listener = self.updateData, source = None, ID = 11111, context = self.context)


    @inlineCallbacks
    def openDataset(self):
        yield self.data_vault.cd(self.dataset_location[0], context = self.context)
        yield self.data_vault.open(self.dataset_location[1], context = self.context)

    @inlineCallbacks
    def getParameters(self):
        parameters = yield self.data_vault.parameters(context = self.context)
        parameterValues = []
        for parameter in parameters:
            parameterValue = yield self.data_vault.get_parameter(parameter, context = self.context)
            parameterValues.append( (parameter, parameterValue) )
        returnValue(parameterValues)

    def updateData(self, x, y):
        self.updateCounter += 1
        self.getData()

    @inlineCallbacks
    def getData(self):
        Data = yield self.data_vault.get(100, context = self.context)
        if (self.data == None):
            yield self.accessingData.acquire()
            try:
                self.data = Data.asarray
            except:
                self.data = Data
            self.accessingData.release()
        else:
            yield self.accessingData.acquire()
            try:
                self.data = np.append(self.data, Data.asarray, 0)
            except:
                self.data = np.append(self.data, Data, 0)
            self.accessingData.release()

    @inlineCallbacks
    def getLabels(self):
        labels = []
        yield self.openDataset()
        variables = yield self.data_vault.variables(context = self.context)
        for i in range(len(variables[1])):
            labels.append(variables[1][i][1] + ' - ' + self.dataset_name)
        returnValue(labels)

    @inlineCallbacks
    def disconnectDataSignal(self):
        yield self.data_vault.removeListener(listener = self.updateData, source = None, ID = 11111, context = self.context)
开发者ID:HaeffnerLab,项目名称:Haeffner-Lab-LabRAD-Tools,代码行数:76,代码来源:Dataset.py

示例13: Dataset

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]

#.........这里部分代码省略.........

#    @inlineCallbacks
#    def setupParameterListener(self, context):
#        yield self.cxn.data_vault.signal__new_parameter(66666, context = context)
#        yield self.cxn.data_vault.addListener(listener = self.updateParameter, source = None, ID = 66666, context = context)

#    # Over 60 seconds, check if the dataset has the appropriate 'plotLive' parameter
#    @inlineCallbacks
#    def listenForPlotParameter(self):
#        for i in range(20):
#            if (self.hasPlotParameter == True):
#                returnValue(self.hasPlotParameter)
##            yield deferToThread(time.sleep, .5)
#            yield self.wait(.5)
#        returnValue(self.hasPlotParameter)
#
#    def updateParameter(self, x, y):
#        self.checkForPlotParameter()

        #append whatever to self.parameters

#    # sets up the listener for new data
#    @inlineCallbacks
#    def setupFitListener(self, context):
#        yield self.cxn.data_vault.signal__new_parameter(22222, context = context)
#        yield self.cxn.data_vault.addListener(listener = self.updateFit, source = None, ID = 22222, context = context)

#    # new data signal
    @inlineCallbacks
#    def updateFit(self):
    def fit(self):
        value = yield self.cxn.data_vault.get_parameter('Fit', context = self.context)
        variables = yield self.cxn.data_vault.variables(context = self.context)
        numberDependentVariables = len(variables[1])
#       if (self.parameters != None):
        try:
            for window in self.parent.dwDict[self]:
                window.fitFromScript(self.dataset, self.directory, numberDependentVariables, value)
        except KeyError:
            print 'dwDict not created yet. Either the Fit parameter was added before data was created or the data is added too quickly. Try adding a pause after adding all the data intended for fitting.'
    # sets up the listener for new data
    @inlineCallbacks
    def setupDataListener(self, context):
        yield self.cxn.data_vault.signal__data_available(11111, context = context)
        yield self.cxn.data_vault.addListener(listener = self.updateData, source = None, ID = 11111, context = context)
        #self.setupDeferred.callback(True)
        self.updatecounter = 0
        self.timer = self.startTimer(100)

    # new data signal
    def updateData(self,x,y):
        self.updatecounter = self.updatecounter + 1
        self.getData(self.context)
#        print 'still happening dataset'

    def timerEvent(self,evt):
        #print self.updatecounter
#        print 'in dataset'
#        if self.updatecounter < 1:
#            print 'slowing down!, less than 1 dataupdate per 100milliseconds '
        self.updatecounter = 0

    def endTimer(self):
        self.killTimer(self.timer)

    @inlineCallbacks
    def disconnectDataSignal(self):
        yield self.cxn.data_vault.removeListener(listener = self.updateData, source = None, ID = 11111, context = self.context)
#        yield self.cxn.data_vault.removeListener(listener = self.updateParameter, source = None, ID = 66666, context = self.context)

    # returns the current data
    @inlineCallbacks
    def getData(self,context):
        Data = yield self.cxn.data_vault.get(100, context = context)
        if (self.data == None):
            self.data = Data
        else:
            yield self.accessingData.acquire()
            self.data = np.append(self.data, Data, 0)
            self.accessingData.release()

    @inlineCallbacks
    def emptyDataBuffer(self):
        yield self.accessingData.acquire()
        del(self.data)
        self.data = None
        self.accessingData.release()

    @inlineCallbacks
    def getYLabels(self):
        labels = []
        variables = yield self.cxn.data_vault.variables(context = self.context)
        for i in range(len(variables[1])):
            labels.append(variables[1][i][1] + ' - ' + self.datasetName)
        returnValue(labels)

    def wait(self, seconds, result=None):
        d = Deferred()
        self.reactor.callLater(seconds, d.callback, result)
        return d
开发者ID:CampbellGroup,项目名称:common,代码行数:104,代码来源:dataset.py

示例14: UnitLifecycle

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class UnitLifecycle(object):
    """Manager for a unit lifecycle.

    Primarily used by the workflow interaction, to modify unit behavior
    according to the current unit workflow state and transitions.
    """

    def __init__(self, client, unit, service, unit_path, executor):
        self._client = client
        self._unit = unit
        self._service = service
        self._executor = executor
        self._unit_path = unit_path
        self._relations = {}
        self._running = False
        self._watching_relation_memberships = False
        self._watching_relation_resolved = False
        self._run_lock = DeferredLock()
        self._log = logging.getLogger("unit.lifecycle")

    def get_relation_workflow(self, relation_id):
        """Accessor to a unit relation workflow, by relation id.

        Primarily intended for and used by unit tests. Raises
        a KeyError if the relation workflow does not exist.
        """
        return self._relations[relation_id]

    @inlineCallbacks
    def install(self, fire_hooks=True):
        """Invoke the unit's install hook.
        """
        if fire_hooks:
            yield self._execute_hook("install")

    @inlineCallbacks
    def upgrade_charm(self, fire_hooks=True):
        """Invoke the unit's upgrade-charm hook.
        """
        if fire_hooks:
            yield self._execute_hook("upgrade-charm", now=True)
        # Restart hook queued hook execution.
        self._executor.start()

    @inlineCallbacks
    def start(self, fire_hooks=True):
        """Invoke the start hook, and setup relation watching.
        """
        self._log.debug("pre-start acquire, running:%s", self._running)
        yield self._run_lock.acquire()
        self._log.debug("start running, unit lifecycle")
        watches = []

        try:
            # Verify current state
            assert not self._running, "Already started"

            # Execute the start hook
            if fire_hooks:
                yield self._execute_hook("config-changed")
                yield self._execute_hook("start")

            # If we have any existing relations in memory, start them.
            if self._relations:
                self._log.debug("starting relation lifecycles")

            for workflow in self._relations.values():
                yield workflow.transition_state("up")

            # Establish a watch on the existing relations.
            if not self._watching_relation_memberships:
                self._log.debug("starting service relation watch")
                watches.append(self._service.watch_relation_states(
                    self._on_service_relation_changes))
                self._watching_relation_memberships = True

            # Establish a watch for resolved relations
            if not self._watching_relation_resolved:
                self._log.debug("starting unit relation resolved watch")
                watches.append(self._unit.watch_relation_resolved(
                    self._on_relation_resolved_changes))
                self._watching_relation_resolved = True

            # Set current status
            self._running = True
        finally:
            self._run_lock.release()

        # Give up the run lock before waiting on initial watch invocations.
        results = yield DeferredList(watches, consumeErrors=True)

        # If there's an error reraise the first one found.
        errors = [e[1] for e in results if not e[0]]
        if errors:
            returnValue(errors[0])

        self._log.debug("started unit lifecycle")

    @inlineCallbacks
    def stop(self, fire_hooks=True):
#.........这里部分代码省略.........
开发者ID:mcclurmc,项目名称:juju,代码行数:103,代码来源:lifecycle.py

示例15: Dataset

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import acquire [as 别名]
class Dataset(QtCore.QObject):
    
    """Class to handle incoming data and prepare them for plotting """
    def __init__(self, cxn, context, dataset):
        super(Dataset, self).__init__()
        self.accessingData = DeferredLock()
        self.cxn = cxn
        self.context = context # context of the first dataset in the window
        self.dataset = dataset
        self.data = None
        self.setupDataListener(self.context)
        
    # open dataset in order to listen for new data signals in current context        
    @inlineCallbacks
    def openDataset(self):
        yield self.cxn.data_vault.cd(DIRECTORY, context = self.context)
        yield self.cxn.data_vault.open(self.dataset, context = self.context)
        
    # sets up the listener for new data
    @inlineCallbacks
    def setupDataListener(self, context):
        yield self.cxn.data_vault.signal__data_available(11111, context = context)
        yield self.cxn.data_vault.addListener(listener = self.updateData, source = None, ID = 11111, context = context)
        #self.setupDeferred.callback(True)
         
    # new data signal
    def updateData(self,x,y):
        self.getData(self.context)
    
    def waitfor(self):
        #set up a timer
        #start looping call
            #check if timer expired - then return False
            try:
                data_vault.get('plot')
            except:
                pass
            #if this paramter exists return True
      
#    # returns the number of things to plot
#    @inlineCallbacks
#    def getPlotnum(self,context):
#        variables = yield self.cxn.data_vault.variables(context = context)
#        plotNum = len(variables[1])
#        returnValue(plotNum) 

    # returns the current data
    @inlineCallbacks
    def getData(self,context):
        Data = yield self.cxn.data_vault.get(100, context = context)
        if (self.data == None):
            self.data = Data.asarray
        else:
            yield self.accessingData.acquire()         
            self.data = np.append(self.data, Data.asarray, 0)
            self.accessingData.release()
        
    @inlineCallbacks
    def emptyDataBuffer(self):
        print 'in empty, waiting to acquire'
        yield self.accessingData.acquire()
        del(self.data)
        self.data = None
        print 'self data should be none now'
        self.accessingData.release()
开发者ID:HaeffnerLab,项目名称:sqip,代码行数:67,代码来源:pygrapherliveasync_matplotlib.py


注:本文中的twisted.internet.defer.DeferredLock.acquire方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。