Received a datablock. Reset the watchdog timer and hand the block to the Site.
343365
protected void restoreBlock(RestoreWork rejoinWork, SiteProcedureConnection siteConnection)
    {
        kickWatchdog(true);
        rejoinWork.restore(siteConnection);
    }
1266489
def start(self):
        """"""
        if (self.cf.link is not None):
            if (self._added is False):
                self.create()
                logger.debug('First time block is started, add block')
            else:
                logger.debug('Block already registered, starting logging'
                             ' for id=%d', self.id)
                pk = CRTPPacket()
                pk.set_header(5, CHAN_SETTINGS)
                pk.data = (CMD_START_LOGGING, self.id, self.period)
                self.cf.send_packet(pk, expected_reply=(
                    CMD_START_LOGGING, self.id))
379389
def handle_data(self, data):
        '''  '''
        self.days += 1
        signals = {}
        self.orderbook = {}

        # Everytime but the first tick
        if self.initialized and self.manager:
            # Keep the portfolio aware of the situation
            self.manager.update(
                self.portfolio,
                self.datetime,
                self.perf_tracker.cumulative_risk_metrics.to_dict())
        else:
            # Perf_tracker needs at least a turn to have an index
            self.sids = data.keys()
            self.warm(data)
            self.initialized = True
            return

        try:
            signals = self.event(data)
        except Exception, error:
            # NOTE Temporary debug. Will probably notify the error and go on
            # with signals={}
            raise AlgorithmEventFailed(
                reason=error, date=self.datetime, data=data)

        # One can process orders within the alogrithm and don't return anything
        if signals and self.manager:
            if (signals.get('buy') or signals.get('sell')):
                self.orderbook = self.manager.trade_signals_handler(signals)
                if self.auto and self._is_interactive():
                    self.process_orders(self.orderbook)

        # Some middlewares send stuff over the wires. This little security
        # prevent us from performing a DDOS
        if self._is_interactive():
            self._call_middlewares()
1043183
def refresh(self):
        
        self.setUpdatesEnabled(False)
        self.blockSignals(True)
        self.clear()
        tableType = self.tableType()
        if not tableType:
            self.setUpdatesEnabled(True)
            self.blockSignals(False)
            return
        
        schema = tableType.schema()
        columns = list(sorted(schema.columns(),
                              key=lambda x: x.name().strip('_')))
        for column in columns:
            XOrbColumnItem(self, column)
        
        self.setUpdatesEnabled(True)
        self.blockSignals(False)
379851
def acquire(self, block=True):
        """"""
        while True:
            # Try to set the lock
            if self.redis.set(self.name, self.value, px=self.timeout, nx=True):
                # It's ours until the timeout now
                return True
            # Lock is taken
            if not block:
                return False
            # If blocking, try again in a bit
            time.sleep(self.sleep)
369492
def goto_block(self, block):
        
        old_block = self.basic_block
        term = block.terminator
        if term is not None:
            self.position_before(term)
        else:
            self.position_at_end(block)
        try:
            yield
        finally:
            self.position_at_end(old_block)
591451
function(chain) {
    const retryAttempts = 100
      , timerInterval = 5000
      , chainTimer = {timer: undefined, blockNumber: 0, retryCounter: 0}
      , provider = (chain == 'utility' ? web3UtilityProvider : web3ValueProvider)
    ;
    return new Promise(function (onResolve, onReject) {
      chainTimer['timer'] = setInterval(function () {
        if (chainTimer['retryCounter'] <= retryAttempts) {
          provider.eth.getBlockNumber(function (err, blocknumber) {
            if (err) {
            } else {
              if (chainTimer['blockNumber']!=0 && chainTimer['blockNumber']!=blocknumber) {
                logger.info("* Geth Checker - " + chain + " chain has new blocks.");
                clearInterval(chainTimer['timer']);
                onResolve();
              }
              chainTimer['blockNumber'] = blocknumber;
            }
          });
        } else {
          logger.error("Geth Checker - " + chain + " chain has no new blocks.");
          onReject();
          process.exit(1);
        }
        chainTimer['retryCounter']++;
      }, timerInterval);
    });
  }
241898
def setRefreshBlocked(self, blocked):
        
        wasBlocked = self._refreshBlocked
        logger.debug("Setting refreshBlocked from {} to {}".format(wasBlocked, blocked))
        self._refreshBlocked = blocked
        return wasBlocked
1086339
def receive_request(self, transaction):
        

        with transaction:

            transaction.separate_timer = self._start_separate_timer(transaction)

            self._blockLayer.receive_request(transaction)

            if transaction.block_transfer:
                self._stop_separate_timer(transaction.separate_timer)
                self._messageLayer.send_response(transaction)
                self.send_datagram(transaction.response)
                return

            self._observeLayer.receive_request(transaction)

            self._requestLayer.receive_request(transaction)

            if transaction.resource is not None and transaction.resource.changed:
                self.notify(transaction.resource)
                transaction.resource.changed = False
            elif transaction.resource is not None and transaction.resource.deleted:
                self.notify(transaction.resource)
                transaction.resource.deleted = False

            self._observeLayer.send_response(transaction)

            self._blockLayer.send_response(transaction)

            self._stop_separate_timer(transaction.separate_timer)

            self._messageLayer.send_response(transaction)

            if transaction.response is not None:
                if transaction.response.type == defines.Types["CON"]:
                    self._start_retransmission(transaction, transaction.response)
                self.send_datagram(transaction.response)
959195
def setBlockRequested(blockInfo, bool)
      if bool
        @requestedBlocks.set blockInfo.blockIndex
      else
        @requestedBlocks.clear blockInfo.blockIndex
      end
    end
574926
@Override
  public LocatedBlock syncBlock(
      Block block,
      List<BlockRecord> syncList,
    boolean closeFile, List<InterDatanodeProtocol> datanodeProxies,
    long deadline
  ) 
    throws IOException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("block=" + block + ", (length=" + block.getNumBytes()
          + "), syncList=" + syncList + ", closeFile=" + closeFile);
    }

    //syncList.isEmpty() that all datanodes do not have the block
    //so the block can be deleted.
    if (syncList.isEmpty()) {
      bsp.commitBlockSynchronization(block, 0, 0, closeFile, true,
          DatanodeID.EMPTY_ARRAY);
      return null;
    }

    List<DatanodeID> successList = new ArrayList<DatanodeID>();

    throwIfAfterTime(deadline);
    long generationstamp = -1;
    try {
      generationstamp = bsp.nextGenerationStamp(block, closeFile);
    } catch (RemoteException e) {
      if (e.unwrapRemoteException() instanceof BlockAlreadyCommittedException) {
        throw new BlockAlreadyCommittedException(e);
      } else {
        throw e;
      }
    }
    Block newblock = new Block(block.getBlockId(), block.getNumBytes(), generationstamp);

    for(BlockRecord r : syncList) {
      try {
        throwIfAfterTime(deadline);
        LOG.info("Updating block " + r + " to " + newblock);
        r.datanode.updateBlock(namespaceId, r.info.getBlock(), newblock, closeFile);
        successList.add(r.id);
      } catch (BlockRecoveryTimeoutException e) {
        throw e;
      } catch (IOException e) {
        InterDatanodeProtocol.LOG.warn("Failed to updateBlock (newblock="
            + newblock + ", datanode=" + r.id + ")", e);
      }
    }

    LOG.info("Updated blocks on syncList for block " + block + " to " + newblock);

    DataNode.stopAllProxies(datanodeProxies);

    if (!successList.isEmpty()) {
      DatanodeID[] nlist = successList.toArray(new DatanodeID[successList.size()]);

      throwIfAfterTime(deadline);
      bsp.commitBlockSynchronization(block,
          newblock.getGenerationStamp(), newblock.getNumBytes(), closeFile, false,
          nlist);
      DatanodeInfo[] info = new DatanodeInfo[nlist.length];
      for (int i = 0; i < nlist.length; i++) {
        info[i] = new DatanodeInfo(nlist[i]);
      }
      return new LocatedBlock(newblock, info); // success
    }

    //failed
    StringBuilder b = new StringBuilder();
    for(BlockRecord r : syncList) {
      b.append("\n  " + r.id);
    }
    throw new IOException("Cannot recover " + block + ", none of these "
        + syncList.size() + " datanodes success {" + b + "\n}");
  }
769541
void loadBlock(BlockId blockId, ByteBuffer block) throws IOException {
        synchronized (m_accessLock) {
            if (! m_blockPathMap.containsKey(blockId)) {
                throw new IllegalArgumentException("Request to load block that is not stored: " + blockId);
            }

            int origPosition = block.position();
            block.position(0);
            Path blockPath = m_blockPathMap.get(blockId);
            try (SeekableByteChannel channel = Files.newByteChannel(blockPath)) {
                channel.read(block);
            }
            finally {
                block.position(origPosition);
            }
        }
    }
439511
private void invalidateBlock(Block blk, DatanodeInfo dn, boolean ackRequired)
    throws IOException {
    NameNode.stateChangeLog.info("DIR* NameSystem.invalidateBlock: "
      + blk + " on "
      + dn.getName());
    DatanodeDescriptor node = getDatanode(dn);
    if (node == null) {
      throw new IOException("Cannot invalidate block " + blk +
        " because datanode " + dn.getName() +
        " does not exist.");
    }

    // Check how many copies we have of the block.  If we have at least one
    // copy on a live node, then we can delete it.
    int count = countNodes(blk).liveReplicas();
    if (count > 1) {
      // delete with ACK
      addToInvalidates(blk, dn, ackRequired);
      removeStoredBlock(blk, node);
      if (NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("BLOCK* NameSystem.invalidateBlocks: "
          + blk + " on "
          + dn.getName() + " listed for deletion.");
      }
    } else {
      NameNode.stateChangeLog.info("BLOCK* NameSystem.invalidateBlocks: "
        + blk + " on "
        + dn.getName() + " is the only copy and was not deleted.");
    }
  }
984311
private void processFailedBlocks(Block []failed, 
      int failedPendingRequests) {
    synchronized (receivedAndDeletedBlockList) {
      // We are adding to the front of a linked list and hence to preserve
      // order we should add the blocks in the reverse order.
      for (int i = failed.length - 1; i >= 0; i--) {
        receivedAndDeletedBlockList.add(0, failed[i]);
      }
      pendingReceivedRequests += failedPendingRequests;
    }
  }
773183
def load(self, callback=None, errback=None, reload=False):
        
        if not reload and self.data:
            raise MonitorException('monitor already loaded')

        def success(result, *args):
            self.data = result
            if callback:
                return callback(self)
            else:
                return self

        return self._rest.retrieve(self.data['id'], callback=success,
                                   errback=errback)
588260
public LocatedBlock recoverBlock(int namespaceId, Block block,
      boolean keepLength, DatanodeID[] datanodeids, boolean closeFile,
      long deadline) throws IOException {
    int errorCount = 0;

    // Number of "replicasBeingWritten" in 0.21 parlance - these are replicas
    // on DNs that are still alive from when the write was happening
    int rbwCount = 0;
    // Number of "replicasWaitingRecovery" in 0.21 parlance - these replicas
    // have survived a DN restart, and thus might be truncated (eg if the
    // DN died because of a machine power failure, and when the ext3 journal
    // replayed, it truncated the file
    int rwrCount = 0;

    List<BlockRecord> blockRecords = new ArrayList<BlockRecord>();
    List<InterDatanodeProtocol> datanodeProxies = new ArrayList<InterDatanodeProtocol>();
    // check generation stamps
    for (DatanodeID id : datanodeids) {
      try {
        InterDatanodeProtocol datanode;
        if (dnr!= null && dnr.equals(id)) {
          LOG.info("Skipping IDNPP creation for local id " + id
              + " when recovering " + block);
          datanode = dn;
        } else {
          LOG.info("Creating IDNPP for non-local id " + id + " (dnReg="
              + dnr + ") when recovering "
              + block);
          datanode = DataNode.createInterDataNodeProtocolProxy(id, conf,
              socketTimeout);
          datanodeProxies.add(datanode);
        }
        BlockSyncer.throwIfAfterTime(deadline);
        BlockRecoveryInfo info = datanode
            .startBlockRecovery(namespaceId, block);
        if (info == null) {
          LOG.info("No block metadata found for block " + block
              + " on datanode " + id);
          continue;
        }
        if (info.getBlock().getGenerationStamp() < block.getGenerationStamp()) {
          LOG.info("Only old generation stamp "
              + info.getBlock().getGenerationStamp() + " found on datanode "
              + id + " (needed block=" + block + ")");
          continue;
        }
        blockRecords.add(new BlockRecord(id, datanode, info));

        if (info.wasRecoveredOnStartup()) {
          rwrCount++;
        } else {
          rbwCount++;
        }
      } catch (BlockRecoveryTimeoutException e) {
        throw e;
      } catch (IOException e) {
        ++errorCount;
        InterDatanodeProtocol.LOG.warn(
            "Failed to getBlockMetaDataInfo for block (=" + block
                + ") from datanode (=" + id + ")", e);
      }
    }

    // If we *only* have replicas from post-DN-restart, then we should
    // include them in determining length. Otherwise they might cause us
    // to truncate too short.
    boolean shouldRecoverRwrs = (rbwCount == 0);

    List<BlockRecord> syncList = new ArrayList<BlockRecord>();
    long minlength = Long.MAX_VALUE;

    for (BlockRecord record : blockRecords) {
      BlockRecoveryInfo info = record.info;
      assert (info != null && info.getBlock().getGenerationStamp() >= block
          .getGenerationStamp());
      if (!shouldRecoverRwrs && info.wasRecoveredOnStartup()) {
        LOG.info("Not recovering replica " + record
            + " since it was recovered on "
            + "startup and we have better replicas");
        continue;
      }
      if (keepLength) {
        if (info.getBlock().getNumBytes() == block.getNumBytes()) {
          syncList.add(record);
        }
      } else {
        syncList.add(record);
        if (info.getBlock().getNumBytes() < minlength) {
          minlength = info.getBlock().getNumBytes();
        }
      }
    }

    if (syncList.isEmpty() && errorCount > 0) {
      DataNode.stopAllProxies(datanodeProxies);
      throw new IOException("All datanodes failed: block=" + block
          + ", datanodeids=" + Arrays.asList(datanodeids));
    }
    if (!keepLength) {
      block.setNumBytes(minlength);
    }
    return blockSyncer.syncBlock(block, syncList, closeFile, datanodeProxies,
        deadline);
  }
1189424
void notifyNamenodeDeletedBlock(Block block) {
    if (block==null) {
      throw new IllegalArgumentException("Block is null");
    }
    // mark it as a deleted block
    DFSUtil.markAsDeleted(block);
    synchronized (receivedAndDeletedBlockList) {
      receivedAndDeletedBlockList.add(block);
    }
  }