Accelerometer x y z raw data in Gs
480858
def get_accelerometer_raw(self):
        

        raw = self._get_raw_data('accelValid', 'accel')

        if raw is not None:
            self._last_accel_raw = raw

        return deepcopy(self._last_accel_raw)
69614
def plot_triaxial(height, width, tools):
    ''''''
    import bokeh.plotting

    p = bokeh.plotting.figure(x_axis_type='datetime',
                              plot_height=height,
                              plot_width=width,
                              title=' ',
                              toolbar_sticky=False,
                              tools=tools,
                              active_drag=BoxZoomTool(),
                              output_backend='webgl')

    p.yaxis.axis_label = 'Acceleration (count)'
    p.xaxis.axis_label = 'Time (timezone as programmed)'

    # Plot accelerometry data as lines and scatter (for BoxSelectTool)
    colors = ['#1b9e77', '#d95f02', '#7570b3']
    axes = ['x', 'y', 'z']
    lines = [None,]*3
    scats = [None,]*3
    for i, (ax, c) in enumerate(zip(axes, colors)):
        lines[i] = p.line(y=ax, x='dt', color=c, legend=False, source=source)
        scats[i] = p.scatter(y=ax, x='dt', color=c, legend=False, size=1,
                             source=source)
    return p, lines, scats
1234706
def earth_accel(RAW_IMU,ATTITUDE):
    ''''''
    r = rotation(ATTITUDE)
    accel = Vector3(RAW_IMU.xacc, RAW_IMU.yacc, RAW_IMU.zacc) * 9.81 * 0.001
    return r * accel
794900
def earth_accel2_df(IMU,IMU2,ATT):
    ''''''
    r = rotation_df(ATT)
    accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ)
    accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ)
    accel = 0.5 * (accel1 + accel2)
    return r * accel
117829
@Override
	public <U extends SensorEvent> HorizontalMotionEvent getMotionEvent(final U sensorEvent) 
	throws MotionDetectorException {

		try {
			
			Sensor sensor = sensorEvent.sensor;
	
			if (sensor.getType() != Sensor.TYPE_ACCELEROMETER) { 
	
				return null;
			}
	
			final float[] input = sensorEvent.values;
			final float[] output = new float[input.length];
	
			try {
	
				smoothingFilter.filter(input, output, null);
			} 
			catch (SmoothingFilterException sfe) {
	
				Log.w(getClass().getName(), 
					  "Failed to execute " + smoothingFilter.getClass().getName() + " on " + input);
			}
	
			float max = sensorEvent.sensor.getMaximumRange();
			float mid = max / 2.0f;
	
			float midRangeHigh = mid + 1.0f;
			float midRangeLow = mid - 1.0f;
	
			HORIZONTAL_DIRECTION direction = processHorizontalDirection(output, midRangeHigh, midRangeLow);
			
			return new HorizontalMotionEvent(sensorEvent, direction, output);
		}
		catch (Exception e) {
	
			throw new MotionDetectorException(getClass(), sensorEvent, e);
		}
	}
1218536
def gpgga_to_dms(gpgga):
    '''
    
    '''
    deg_min, dmin = gpgga.split('.')
    degrees = int(deg_min[:-2])
    minutes = float('%s.%s' % (deg_min[-2:], dmin))
    decimal = degrees + (minutes / 60)
    return decimal
1343303
def convert_to_influx(mac, payload):
    '''
    
    '''
    dataFormat = payload["data_format"] if ('data_format' in payload) else None
    fields = {}
    fields["temperature"]               = payload["temperature"] if ('temperature' in payload) else None
    fields["humidity"]                  = payload["humidity"] if ('humidity' in payload) else None
    fields["pressure"]                  = payload["pressure"] if ('pressure' in payload) else None
    fields["accelerationX"]             = payload["acceleration_x"] if ('acceleration_x' in payload) else None
    fields["accelerationY"]             = payload["acceleration_y"] if ('acceleration_y' in payload) else None
    fields["accelerationZ"]             = payload["acceleration_z"] if ('acceleration_z' in payload) else None
    fields["batteryVoltage"]            = payload["battery"]/1000.0 if ('battery' in payload) else None
    fields["txPower"]                   = payload["tx_power"] if ('tx_power' in payload) else None
    fields["movementCounter"]           = payload["movement_counter"] if ('movement_counter' in payload) else None
    fields["measurementSequenceNumber"] = payload["measurement_sequence_number"] if ('measurement_sequence_number' in payload) else None
    fields["tagID"]                     = payload["tagID"] if ('tagID' in payload) else None
    fields["rssi"]                      = payload["rssi"] if ('rssi' in payload) else None
    return {
        "measurement": "ruuvi_measurements",
        "tags": {
            "mac": mac,
            "dataFormat": dataFormat
        },
        "fields": fields
    }
136685
def parse_estimote_service_data(data):
    """"""
    if data['frame_type'] & 0xF == ESTIMOTE_TELEMETRY_FRAME:
        protocol_version = (data['frame_type'] & 0xF0) >> 4
        if data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_A:
            return EstimoteTelemetryFrameA(data['frame'], protocol_version)
        elif data['frame']['subframe_type'] == ESTIMOTE_TELEMETRY_SUBFRAME_B:
            return EstimoteTelemetryFrameB(data['frame'], protocol_version)
    return None
593746
function(x, y, roundBy5, dragging) {
            var radian = Math.atan2(x, - y),
                isHours = this.currentView === 'hours',
                unit = Math.PI / (isHours || roundBy5 ? 6 : 30),
                z = Math.sqrt(x * x + y * y),
                options = this.options,
                inner = isHours && z < (outerRadius + innerRadius) / 2,
                radius = inner ? innerRadius : outerRadius,
                value;

            if (options.format === '12h') {
                radius = outerRadius;
            }

            // Radian should in range [0, 2PI]
            if (radian < 0) {
                radian = Math.PI * 2 + radian;
            }

            // Get the round value
            value = Math.round(radian / unit);

            // Get the round radian
            radian = value * unit;

            // Correct the hours or minutes
            if (options.format === '12h') {
                if (isHours) {
                    if (value === 0) {
                        value = 12;
                    }
                } else {
                    if (roundBy5) {
                        value *= 5;
                    }
                    if (value === 60) {
                        value = 0;
                    }
                }
            } else {
                if (isHours) {
                    if (value === 12) {
                        value = 0;
                    }
                    value = inner ? (value === 0 ? 12 : value) : value === 0 ? 0 : value + 12;
                } else {
                    if (roundBy5) {
                        value *= 5;
                    }
                    if (value === 60) {
                        value = 0;
                    }
                }
            }

            // Ignore out of range ticks.
            var minTime = this._parseTime(this.options.minTime);

            if (isHours) {
                if (value < minTime.hours) {
                    return;
                }
            } else {
                var hours = this.hours;
                if (this.options.format === '12h') {
                    if (this.amOrPm === 'PM') {
                        hours += 12;
                    }
                }
                if (hours <= minTime.hours && value < minTime.minutes) {
                    return;
                }
            }

            // Once hours or minutes changed, vibrate the device
            if (this[this.currentView] !== value) {
                if (vibrate && this.options.vibrate) {
                    // Do not vibrate too frequently
                    if (!this.vibrateTimer) {
                        navigator[vibrate](10);
                        this.vibrateTimer = setTimeout($.proxy(function() {
                            this.vibrateTimer = null;
                        }, this), 100);
                    }
                }
            }

            this[this.currentView] = value;
            this[isHours ? 'hoursLabel' : 'minutesLabel'].html(leadingZero(value));

            // Add active class to current tick
            this[isHours ? 'hoursView' : 'minutesView'].find('.jqclockpicker-tick').each(function() {
                var tick = $(this);
                tick.toggleClass('jqclockpicker-tick-active', value === + tick.html());
            });

            if (!svgSupported) {
                return;
            }

            // Set clock hand and others' position
            var cx = Math.sin(radian) * radius,
                cy = - Math.cos(radian) * radius,
                x2 = Math.sin(radian) * (radius - this.bg.getAttribute('r')),
                y2 = - Math.cos(radian) * (radius - this.bg.getAttribute('r'));
            
            this.hand.setAttribute('x2', x2);
            this.hand.setAttribute('y2', y2);
            this.bg.setAttribute('cx', cx);
            this.bg.setAttribute('cy', cy);
            this.fg.setAttribute('visibility', 'hidden');
            this.bg.setAttribute('class', 'jqclockpicker-canvas-bg');

            if (!isHours && value % 5) {
                this.fg.setAttribute('cx', cx);
                this.fg.setAttribute('cy', cy);
                this.fg.setAttribute('visibility', 'visible');
            }

            // Place clock hand at the top when dragging
            if (dragging) {
                this.g.insertBefore(this.hand, this.bearing);
            } else {
                // Or place it at the bottom
                this.g.insertBefore(this.hand, this.bg);
            }

            return true;
        }
1232469
def unpackSample(self, rawData):
        
        length = len(rawData)
        # TODO error if not multiple of 2
        # logger.debug(">> unpacking sample %d length %d", self._sampleIdx, length)
        unpacked = struct.unpack(">" + ('h' * (length // 2)), memoryview(bytearray(rawData)).tobytes())
        # store the data in a dictionary
        mpu6050 = collections.OrderedDict()
        mpu6050[SAMPLE_TIME] = self._sampleIdx / self.fs
        sensorIdx = 0
        if self.isAccelerometerEnabled():
            mpu6050[ACCEL_X] = unpacked[sensorIdx] * self._accelerationFactor
            sensorIdx += 1
            mpu6050[ACCEL_Y] = unpacked[sensorIdx] * self._accelerationFactor
            sensorIdx += 1
            mpu6050[ACCEL_Z] = unpacked[sensorIdx] * self._accelerationFactor
            sensorIdx += 1

        if self.isTemperatureEnabled():
            mpu6050[TEMP] = unpacked[sensorIdx] * self._temperatureGain + self._temperatureOffset
            sensorIdx += 1

        if self.isGyroEnabled():
            mpu6050[GYRO_X] = unpacked[sensorIdx] * self._gyroFactor
            sensorIdx += 1
            mpu6050[GYRO_Y] = unpacked[sensorIdx] * self._gyroFactor
            sensorIdx += 1
            mpu6050[GYRO_Z] = unpacked[sensorIdx] * self._gyroFactor
            sensorIdx += 1
        # TODO should we send as a dict so the keys are available?
        output = list(mpu6050.values())
        self._sampleIdx += 1
        # logger.debug("<< unpacked sample length %d into vals size %d", length, len(output))
        return output
450184
function(sensorInfo, options) {
  var gpioNum;

  if (sensorInfo.model) {
    this.model = sensorInfo.model;
  } else {
    if (options) {
      this.model = options.model;
    }
  }
  if (!options) { options = {}; }

  options.gpioPort = SWITCH_GPIO_NUM;
  gpioNum = Number(sensorInfo.device.address, 10);

  if (!_.isNaN(gpioNum)) {
    options.gpioPort = gpioNum;
  } else {
    console.warn('MotionDetector sensor address is not provided');
  }

  this.savedValue = 0;

  OnOff.call(this, sensorInfo, options, 'motion');
}
616591
def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type, time_step=None):
        
        if 'radiation' in gssha_var:
            conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_type]
            if gssha_var.startswith('direct_radiation') and not isinstance(lsm_var, basestring):
                # direct_radiation = (1-DIFFUSIVE_FRACION)*global_radiation
                global_radiation_var, diffusive_fraction_var = lsm_var
                global_radiation = self._load_lsm_data(global_radiation_var, conversion_factor)
                diffusive_fraction = self._load_lsm_data(diffusive_fraction_var)
                if gssha_var.endswith("cc"):
                    diffusive_fraction /= 100.0

                self.data = ((1-diffusive_fraction)*global_radiation)

            elif gssha_var.startswith('diffusive_radiation') and not isinstance(lsm_var, basestring):
                # diffusive_radiation = DIFFUSIVE_FRACION*global_radiation
                global_radiation_var, diffusive_fraction_var = lsm_var
                global_radiation = self._load_lsm_data(global_radiation_var, conversion_factor)
                diffusive_fraction = self._load_lsm_data(diffusive_fraction_var)
                if gssha_var.endswith("cc"):
                    diffusive_fraction /= 100
                self.data = (diffusive_fraction*global_radiation)

            elif isinstance(lsm_var, basestring):
                self.data = self._load_lsm_data(lsm_var, self.netcdf_attributes[gssha_var]['conversion_factor'][load_type])
            else:
                raise ValueError("Invalid LSM variable ({0}) for GSSHA variable {1}".format(lsm_var, gssha_var))

        elif gssha_var == 'relative_humidity' and not isinstance(lsm_var, str):
            ##CONVERSION ASSUMPTIONS:
            ##1) These equations are for liquid water and are less accurate below 0 deg C
            ##2) Not adjusting the pressure for the fact that the temperature
            ##   and moisture measurements are given at 2 m AGL.

            ##Neither of these should have a significant impact on RH values
            ##given the uncertainty in the model values themselves.

            specific_humidity_var, pressure_var, temperature_var = lsm_var
            specific_humidity = self._load_lsm_data(specific_humidity_var)
            pressure = self._load_lsm_data(pressure_var)
            temperature = self._load_lsm_data(temperature_var)
            ##To compute the relative humidity at 2m,
            ##given T, Q (water vapor mixing ratio) at 2 m and PSFC (surface pressure):
            ##Es(saturation vapor pressure in Pa)
            ##Qs(saturation mixing ratio)=(0.622*es)/(PSFC-es)
            ##RH = 100*Q/Qs
            es = esat(temperature)
            self.data = 100 * specific_humidity/((0.622*es)/(pressure-es))

        elif gssha_var == 'relative_humidity_dew':
            # https://software.ecmwf.int/wiki/display/CKB/Do+ERA+datasets+contain+parameters+for+near-surface+humidity
            # temperature in Kelvin
            # RH = 100 * es(Td)/es(T)
            dew_point_temp_var, temperature_var = lsm_var
            dew_point_temp = self._load_lsm_data(dew_point_temp_var)
            temperature = self._load_lsm_data(temperature_var)
            self.data = 100 * esat(dew_point_temp)/esat(temperature)

        elif gssha_var == 'wind_speed' and not isinstance(lsm_var, str):
            # WRF:  http://www.meteo.unican.es/wiki/cordexwrf/OutputVariables
            u_vector_var, v_vector_var = lsm_var
            conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_type]
            u_vector = self._load_lsm_data(u_vector_var, conversion_factor)
            v_vector = self._load_lsm_data(v_vector_var, conversion_factor)
            self.data = (xu.sqrt(u_vector**2 + v_vector**2))

        elif 'precipitation' in gssha_var and not isinstance(lsm_var, str):
            # WRF:  http://www.meteo.unican.es/wiki/cordexwrf/OutputVariables
            rain_c_var, rain_nc_var = lsm_var
            conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_type]
            rain_c = self._load_lsm_data(rain_c_var, conversion_factor)
            rain_nc = self._load_lsm_data(rain_nc_var, conversion_factor)
            self.data = rain_c + rain_nc

        else:
            self.data = self._load_lsm_data(lsm_var,
                                            self.netcdf_attributes[gssha_var]['conversion_factor'][load_type],
                                            self.netcdf_attributes[gssha_var].get('calc_4d_method'),
                                            self.netcdf_attributes[gssha_var].get('calc_4d_dim'),
                                            time_step=time_step)
            conversion_function = self.netcdf_attributes[gssha_var].get('conversion_function')
            if conversion_function:
                self.data.values = self.netcdf_attributes[gssha_var]['conversion_function'][load_type](self.data.values)

        if 'precipitation' in gssha_var:
            # NOTE: Precipitation is converted from mm/s to mm/hr
            # with the conversion factor when it is a rate.
            if 'units' in self.data.attrs:
                if self.data.attrs['units'] == 'm':
                    # convert from m to mm
                    self.data.values *= 1000

            if load_type == 'ascii' or load_type == 'netcdf':
                # CONVERT TO INCREMENTAL
                if gssha_var == 'precipitation_acc':
                    self.data.values = np.lib.pad(self.data.diff(self.lsm_time_dim).values,
                                                  ((1, 0), (0, 0), (0, 0)),
                                                  'constant',
                                                  constant_values=0)

                # CONVERT PRECIP TO RADAR (mm/hr) IN FILE
                if gssha_var == 'precipitation_inc' or gssha_var == 'precipitation_acc':
                    # convert from mm to mm/hr
                    time_step_hours = np.diff(self.xd[self.lsm_time_var].values)[0]/np.timedelta64(1, 'h')
                    self.data.values /= time_step_hours

        # convert to dataset
        gssha_data_var_name = self.netcdf_attributes[gssha_var]['gssha_name']
        self.data = self.data.to_dataset(name=gssha_data_var_name)
        self.data.rename(
            {
                self.lsm_lon_dim: 'x',
                self.lsm_lat_dim: 'y',
                self.lsm_lon_var: 'lon',
                self.lsm_lat_var: 'lat'
            },
            inplace=True
        )
        self.data.attrs = {'proj4': self.xd.lsm.projection.ExportToProj4()}
        self.data[gssha_data_var_name].attrs = {
           'standard_name': self.netcdf_attributes[gssha_var]['standard_name'],
           'long_name': self.netcdf_attributes[gssha_var]['long_name'],
           'units': self.netcdf_attributes[gssha_var]['units'][load_type],
        }
1243246
def _srads2bt(self, data, channel_name):
        """"""
        a__, b__, c__ = BTFIT[channel_name]
        wavenumber = CALIB[self.platform_id][channel_name]["VC"]
        temp = self._tl15(data, wavenumber)

        return a__ * temp * temp + b__ * temp + c__
1117931
public void readAccelerometerRange(Callback<AccelerometerRange> callback) {
        addCallback(BeanMessageID.CC_ACCEL_GET_RANGE, callback);
        sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_GET_RANGE);
    }
1023104
def _loadRecordingDevices(self):
        
        return {device.name: device for device in
                [self.createDevice(deviceCfg) for deviceCfg in self.config['accelerometers']]}
1074064
function () {
            var i,
                len = trackerPoints.length,
                trackPoint,
                gPoint,
                now = $.now(),
                elapsedTime,
                distance,
                speed;

            elapsedTime = now - lastTime;
            lastTime = now;

            for ( i = 0; i < len; i++ ) {
                trackPoint = trackerPoints[ i ];
                gPoint = trackPoint.gPoint;
                // Math.atan2 gives us just what we need for a velocity vector, as we can simply
                //   use cos()/sin() to extract the x/y velocity components.
                gPoint.direction = Math.atan2( gPoint.currentPos.y - trackPoint.lastPos.y, gPoint.currentPos.x - trackPoint.lastPos.x );
                // speed = distance / elapsed time
                distance = trackPoint.lastPos.distanceTo( gPoint.currentPos );
                trackPoint.lastPos = gPoint.currentPos;
                speed = 1000 * distance / ( elapsedTime + 1 );
                // Simple biased average, favors the most recent speed computation. Smooths out erratic gestures a bit.
                gPoint.speed = 0.75 * speed + 0.25 * gPoint.speed;
            }
        }
282537
def handle_abs(self):
        """"""
        # pylint: disable=no-member
        x_raw = self.microbit.accelerometer.get_x()
        y_raw = self.microbit.accelerometer.get_y()
        x_abs = ('Absolute', 0x00, x_raw)
        y_abs = ('Absolute', 0x01, y_raw)
        return x_abs, y_abs