Checks the state of each measurement and verifies their state, if an active measurement is now complete then
        passes them to the completed measurement set, if failed then to the failed set, if failed and old then evicts.
        :return:
331722
def _sweep(self):
        
        while self.running:
            for am in list(self.activeMeasurements):
                now = datetime.datetime.utcnow()
                # devices were allocated and have completed == complete
                recordingDeviceCount = len(am.recordingDevices)
                if recordingDeviceCount > 0:
                    if all(entry['state'] == RecordStatus.COMPLETE.name for entry in am.recordingDevices.values()):
                        logger.info("Detected completedmeasurement " + am.id)
                        self._moveToComplete(am)

                # we have reached the end time and we have either all failed devices or no devices == kill
                if now > (am.endTime + datetime.timedelta(days=0, seconds=1)):
                    allFailed = all(entry['state'] == RecordStatus.FAILED.name
                                    for entry in am.recordingDevices.values())
                    if (recordingDeviceCount > 0 and allFailed) or recordingDeviceCount == 0:
                        logger.warning("Detected failed measurement " + am.id + " with " + str(recordingDeviceCount)
                                       + " devices, allFailed: " + str(allFailed))
                        self._moveToFailed(am)

                # we are well past the end time and we have failed devices or an ongoing recording == kill or deathbed
                if now > (am.endTime + datetime.timedelta(days=0, seconds=self.maxTimeTilDeathbedSeconds)):
                    if any(entry['state'] == RecordStatus.FAILED.name for entry in am.recordingDevices.values()):
                        logger.warning("Detected failed and incomplete measurement " + am.id + ", assumed dead")
                        self._moveToFailed(am)
                    elif all(entry['state'] == RecordStatus.RECORDING.name for entry in am.recordingDevices.values()):
                        self._handleDeathbed(am)
            time.sleep(0.1)
        logger.warning("MeasurementCaretaker is now shutdown")
1220775
def clear_measurements(self):
        
        mid_list = self.assignments.get('measurements', None)
        if mid_list is not None:
            for mid in mid_list:
                self.configs.delete_measurements(mid=mid)
            self.assignments['measurements'] = None
123507
def measurements(self, value):
        
        if value == self._defaults['measurements'] and 'measurements' in self._values:
            del self._values['measurements']
        else:
            self._values['measurements'] = value
1129811
def _Verify(self):
    

    # If the list of expected calls is not empty, raise an exception
    if self._expected_calls_queue:
      # The last MultipleTimesGroup is not popped from the queue.
      if (len(self._expected_calls_queue) == 1 and
          isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and
          self._expected_calls_queue[0].IsSatisfied()):
        pass
      else:
        raise ExpectedMethodCallsError(self._expected_calls_queue)
366377
def _check_stage_complete(self):
        

        try:

            for task in self._tasks:
                if task.state not in [states.DONE, states.FAILED]:
                    return False

            return True

        except Exception, ex:
            raise EnTKError(ex)
285255
def _copy_unidimensional_measurement(
      self, phase, name, measurement, mfg_event):
    """"""
    mfg_measurement = mfg_event.measurement.add()

    # Copy basic measurement fields.
    mfg_measurement.name = name
    if measurement.docstring:
      mfg_measurement.description = measurement.docstring
    mfg_measurement.parameter_tag.append(phase.name)
    if (measurement.units and
        measurement.units.code in test_runs_converter.UOM_CODE_MAP):
      mfg_measurement.unit_code = (
          test_runs_converter.UOM_CODE_MAP[measurement.units.code])

    # Copy failed measurements as failure_codes. This happens early to include
    # unset measurements.
    if (measurement.outcome != measurements.Outcome.PASS and
        phase.outcome != htf_test_record.PhaseOutcome.SKIP):
      failure_code = mfg_event.failure_codes.add()
      failure_code.code = name
      failure_code.details = '\n'.join(str(v) for v in measurement.validators)

    # Copy measurement value.
    measured_value = measurement.measured_value
    status_str = MEASUREMENT_OUTCOME_TO_TEST_RUN_STATUS_NAME[
        measurement.outcome]
    mfg_measurement.status = test_runs_pb2.Status.Value(status_str)
    if not measured_value.is_value_set:
      return
    value = measured_value.value

    if isinstance(value, numbers.Number):
      mfg_measurement.numeric_value = float(value)
    elif isinstance(value, bytes):
      # text_value expects unicode or ascii-compatible strings, so we must
      # 'decode' it, even if it's actually just garbage bytestring data.
      mfg_measurement.text_value = unicode(value, errors='replace')
    elif isinstance(value, unicode):
      # Don't waste time and potential errors decoding unicode.
      mfg_measurement.text_value = value
    else:
      # Coercing to string.
      mfg_measurement.text_value = str(value)

    # Copy measurement validators.
    for validator in measurement.validators:
      if isinstance(validator, validators.RangeValidatorBase):
        if validator.minimum is not None:
          mfg_measurement.numeric_minimum = float(validator.minimum)
        if validator.maximum is not None:
          mfg_measurement.numeric_maximum = float(validator.maximum)
      elif isinstance(validator, validators.RegexMatcher):
        mfg_measurement.expected_text = validator.regex
      else:
        mfg_measurement.description += '\nValidator: ' + str(validator)
1053203
def record(self, tags=None):
        
        if tags is None:
            tags = TagContext.get()
        if self._invalid:
            logger.warning("Measurement map has included negative value "
                           "measurements, refusing to record")
            return
        for measure, value in self.measurement_map.items():
            if value < 0:
                self._invalid = True
                logger.warning("Dropping values, value to record must be "
                               "non-negative")
                logger.info("Measure '{}' has negative value ({}), refusing "
                            "to record measurements from {}"
                            .format(measure.name, value, self))
                return

        self.measure_to_view_map.record(
                tags=tags,
                measurement_map=self.measurement_map,
                timestamp=utils.to_iso_str(),
                attachments=self.attachments
        )
337928
def delete(self, measurementId):
        
        message, count, deleted = self._measurementController.delete(measurementId)
        if count == 0:
            return message, 404
        elif deleted is None:
            return message, 500
        else:
            return deleted, 200
411312
public synchronized static Set<MeasureUnit> getAvailable() {
        Set<MeasureUnit> result = new HashSet<MeasureUnit>();
        for (String type : new HashSet<String>(MeasureUnit.getAvailableTypes())) {
            for (MeasureUnit unit : MeasureUnit.getAvailable(type)) {
                result.add(unit);
            }
        }
        // Train users not to modify returned set from the start giving us more
        // flexibility for implementation.
        return Collections.unmodifiableSet(result);
    }
77465
def append(self, measurement):
        
        assert isinstance(measurement, Measurement)
        assert measurement.station_id == self.station_id
        self.measurements.append(measurement)
680420
async def SetMeterStatus(self, statues):
        '''
        
        '''
        # map input types to rpc msg
        _params = dict()
        msg = dict(type='MetricsDebug',
                   request='SetMeterStatus',
                   version=2,
                   params=_params)
        _params['statues'] = statues
        reply = await self.rpc(msg)
        return reply
687009
def is_complete(self):
        """"""

        if 'status' in self.transfer_info:
            self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE'

        return self._complete
237302
def is_measure(self):
        """"""
        from ambry.valuetype.core import ROLE
        return self.role == ROLE.MEASURE
1129721
function finalizeMeasurement(id) {
        if (activeTests[id.id]) {
            delete activeTests[id.id];
        }

        if (updatableTests[id.id]) {
            delete updatableTests[id.id];
        }
    }
165485
def _validate_measure_count(self, times):
        
        if not self.min_measures <= times <= self.max_measures:
            raise ParameterValidationError(
                "{times} is not within the borders defined in the class".format(
                    times=times
                )
            )
1001620
def should_send(measure)
      op = op_for_measurement(measure)
      return measure.value > 0 if op == ADD_OP
      return !measure.value.nan? if op == MAX_OP

      false
    end
762484
def clean(self):
        ''''''
        if not self.metrics:
            self.metrics = dict(
                (name, spec.default)
                for name, spec in (metric_catalog.get(self.__class__, {})
                                                 .items()))
        return super(WithMetrics, self).clean()