Method to convert data from the TSL2550D lux sensor
    into more easily usable ADC count values.
779789
def get_lux_count(lux_byte):
    
    LUX_VALID_MASK = 0b10000000
    LUX_CHORD_MASK = 0b01110000
    LUX_STEP_MASK = 0b00001111
    valid = lux_byte & LUX_VALID_MASK
    if valid != 0:
        step_num = (lux_byte & LUX_STEP_MASK)
        # Shift to normalize value
        chord_num = (lux_byte & LUX_CHORD_MASK) >> 4
        step_val = 2**chord_num
        chord_val = int(16.5 * (step_val - 1))
        count = chord_val + step_val * step_num
        return count
    else:
        raise SensorError("Invalid lux sensor data.")
613716
def _parse_led(self, keypad, component_xml):
    """"""
    component_num = int(component_xml.get('ComponentNumber'))
    led_num = component_num - 80
    led = Led(self._lutron, keypad,
              name=('LED %d' % led_num),
              led_num=led_num,
              component_num=component_num)
    return led
430001
def get_spectrogram(self):
        """"""
        args = self.args

        asd = self.timeseries[0].asd().value
        if (asd.min() == 0):
            self.log(0, 'Input data has a zero in ASD. '
                     'Q-transform not possible.')
            self.got_error = True
            qtrans = None
        else:
            gps = self.qxfrm_args['gps']
            outseg = Segment(gps, gps).protract(args.plot[self.plot_num])

            # This section tries to optimize the amount of data that is
            # processed and the time resolution needed to create a good
            # image. NB:For each time span specified
            # NB: the timeseries h enough data for the longest plot
            inseg = outseg.protract(4) & self.timeseries[0].span
            proc_ts = self.timeseries[0].crop(*inseg)

            #  time resolution is calculated to provide about 4 times
            # the number of output pixels for interpolation
            tres = float(outseg.end - outseg.start) / 4 / self.args.nx
            self.qxfrm_args['tres'] = tres
            self.qxfrm_args['search'] = int(len(proc_ts) * proc_ts.dt.value)

            self.log(3, 'Q-transform arguments:')
            self.log(3, '{0:>15s} = {1}'.format('outseg', outseg))
            for key in sorted(self.qxfrm_args):
                self.log(3, '{0:>15s} = {1}'.format(key, self.qxfrm_args[key]))

            qtrans = proc_ts.q_transform(outseg=outseg, **self.qxfrm_args)

            if args.ymin is None:  # set before Spectrogram.make_plot
                args.ymin = qtrans.yspan[0]

        return qtrans
1343807
def parse_value(self, value):
        
        value = value.strip()

        # Skip missing sensors
        if value == 'na':
            return None

        # Try just getting the float value
        try:
            return float(value)
        except:
            pass

        # Next best guess is a hex value
        try:
            return float.fromhex(value)
        except:
            pass

        # No luck, bail
        return None
1318033
def _decode_sensor_data(properties):
        """"""
        b64_input = ""
        for s in properties.get('payload'):
            # pylint: disable=consider-using-join
            b64_input += s

        decoded = base64.b64decode(b64_input)
        data = zlib.decompress(decoded)
        points = []
        i = 0

        while i < len(data):
            points.append({
                'timestamp': int(1e3 * ArloBaseStation._parse_statistic(
                    data[i:(i + 4)], 0)),
                'temperature': ArloBaseStation._parse_statistic(
                    data[(i + 8):(i + 10)], 1),
                'humidity': ArloBaseStation._parse_statistic(
                    data[(i + 14):(i + 16)], 1),
                'airQuality': ArloBaseStation._parse_statistic(
                    data[(i + 20):(i + 22)], 1)
            })
            i += 22

        return points
601528
def post_process_data(self, voltage=None, incremental_capacity=None,
                          voltage_step=None):
        """"""

        logging.debug("post-processing data")

        if voltage is None:
            voltage = self.voltage_processed
            incremental_capacity = self.incremental_capacity
            voltage_step = self.voltage_inverted_step

        if self.post_smoothing:
            logging.debug(" - post smoothing (gaussian)")
            logging.debug(f"    * using voltage fwhm: {self.voltage_fwhm}")
            points_fwhm = int(self.voltage_fwhm / voltage_step)

            sigma = np.amax([1, points_fwhm / 2])

            self.incremental_capacity = gaussian_filter1d(
                incremental_capacity, sigma=sigma, order=self.gaussian_order,
                mode=self.gaussian_mode,
                cval=self.gaussian_cval,
                truncate=self.gaussian_truncate
            )

        if self.normalize:
            logging.debug(" - normalizing")
            area = simps(incremental_capacity, voltage)
            self.incremental_capacity = incremental_capacity * self.normalizing_factor / abs(area)

        fixed_range = False
        if isinstance(self.fixed_voltage_range, np.ndarray):
            fixed_range = True
        else:
            if self.fixed_voltage_range:
                fixed_range = True
        if fixed_range:
            logging.debug(" - using fixed voltage range (interpolating)")
            v1, v2, number_of_points = self.fixed_voltage_range
            v = np.linspace(v1, v2, number_of_points)
            f = interp1d(x=self.voltage_processed, y=self.incremental_capacity,
                         kind=self.interpolation_method, bounds_error=False,
                         fill_value=np.NaN)

            self.incremental_capacity = f(v)
            self.voltage_processed = v
1249876
def convert_rgb_to_real(x):
  """"""
  with tf.name_scope("rgb_to_real", values=[x]):
    x = to_float(x)
    x /= 255.0
    return x
789995
def _counts_to_amber(t_vals, n_vals):
    
    t_depth = int(t_vals["REF_COUNT"]) + int(t_vals["ALT_COUNT"])
    n_depth = int(n_vals["REF_COUNT"]) + int(n_vals["ALT_COUNT"])
    if n_depth > 0 and t_depth > 0:
        t_baf = float(t_vals["ALT_COUNT"]) / float(t_depth)
        n_baf = float(n_vals["ALT_COUNT"]) / float(n_depth)
        return [t_vals["CONTIG"], t_vals["POSITION"], t_baf, _normalize_baf(t_baf), t_depth,
                n_baf, _normalize_baf(n_baf), n_depth]
1130181
def __demodulate_data(self, data):
        
        if len(data) == 0:
            return

        power_spectrum = data.real ** 2 + data.imag ** 2
        is_above_noise = np.sqrt(np.mean(power_spectrum)) > self.signal.noise_threshold

        if self.adaptive_noise and not is_above_noise:
            self.signal.noise_threshold = 0.9 * self.signal.noise_threshold + 0.1 * np.sqrt(np.max(power_spectrum))

        if is_above_noise:
            self.__add_to_buffer(data)
            self.pause_length = 0
            if not self.__buffer_is_full():
                return
        else:
            self.pause_length += len(data)
            if self.pause_length < 10 * self.signal.bit_len:
                self.__add_to_buffer(data)
                if not self.__buffer_is_full():
                    return

        if self.__current_buffer_index == 0:
            return

        # clear cache and start a new message
        self.signal._fulldata = self.__buffer[0:self.__current_buffer_index]
        self.__clear_buffer()
        self.signal._qad = None

        bit_len = self.signal.bit_len
        if self.automatic_center:
            self.signal.qad_center = AutoInterpretation.detect_center(self.signal.qad, max_size=150*self.signal.bit_len)

        ppseq = grab_pulse_lens(self.signal.qad, self.signal.qad_center,
                                self.signal.tolerance, self.signal.modulation_type, self.signal.bit_len)

        bit_data, pauses, bit_sample_pos = self._ppseq_to_bits(ppseq, bit_len, write_bit_sample_pos=False)

        for bits, pause in zip(bit_data, pauses):
            message = Message(bits, pause, bit_len=bit_len, message_type=self.default_message_type,
                              decoder=self.decoder)
            self.messages.append(message)
            self.message_sniffed.emit(len(self.messages) - 1)
788617
def scale_dataset(self, dsid, variable, info):
        """"""

        variable = remove_empties(variable)
        scale = variable.attrs.get('scale_factor', np.array(1))
        offset = variable.attrs.get('add_offset', np.array(0))
        if np.issubdtype((scale + offset).dtype, np.floating) or np.issubdtype(variable.dtype, np.floating):
            if '_FillValue' in variable.attrs:
                variable = variable.where(
                    variable != variable.attrs['_FillValue'])
                variable.attrs['_FillValue'] = np.nan
            if 'valid_range' in variable.attrs:
                variable = variable.where(
                    variable <= variable.attrs['valid_range'][1])
                variable = variable.where(
                    variable >= variable.attrs['valid_range'][0])
            if 'valid_max' in variable.attrs:
                variable = variable.where(
                    variable <= variable.attrs['valid_max'])
            if 'valid_min' in variable.attrs:
                variable = variable.where(
                    variable >= variable.attrs['valid_min'])
        attrs = variable.attrs
        variable = variable * scale + offset
        variable.attrs = attrs

        variable.attrs.update({'platform_name': self.platform_name,
                               'sensor': self.sensor})

        variable.attrs.setdefault('units', '1')

        ancillary_names = variable.attrs.get('ancillary_variables', '')
        try:
            variable.attrs['ancillary_variables'] = ancillary_names.split()
        except AttributeError:
            pass

        if 'palette_meanings' in variable.attrs:
            variable.attrs['palette_meanings'] = [int(val)
                                                  for val in variable.attrs['palette_meanings'].split()]
            if variable.attrs['palette_meanings'][0] == 1:
                variable.attrs['palette_meanings'] = [0] + variable.attrs['palette_meanings']
                variable = xr.DataArray(da.vstack((np.array(variable.attrs['fill_value_color']), variable.data)),
                                        coords=variable.coords, dims=variable.dims, attrs=variable.attrs)

            val, idx = np.unique(variable.attrs['palette_meanings'], return_index=True)
            variable.attrs['palette_meanings'] = val
            variable = variable[idx]

        if 'standard_name' in info:
            variable.attrs.setdefault('standard_name', info['standard_name'])
        if self.sw_version == 'NWC/PPS version v2014' and dsid.name == 'ctth_alti':
            # pps 2014 valid range and palette don't match
            variable.attrs['valid_range'] = (0., 9000.)
        if self.sw_version == 'NWC/PPS version v2014' and dsid.name == 'ctth_alti_pal':
            # pps 2014 palette has the nodata color (black) first
            variable = variable[1:, :]

        return variable
1326303
def _erads2bt(self, data, channel_name):
        """"""
        cal_info = CALIB[self.platform_id][channel_name]
        alpha = cal_info["ALPHA"]
        beta = cal_info["BETA"]
        wavenumber = CALIB[self.platform_id][channel_name]["VC"]

        return (self._tl15(data, wavenumber) - beta) / alpha
36244
function (x0, y0, width, height, c)
    {
        _c = c || _c
        const data = _c.getImageData(x0, y0, width, height)
        const bits = data.data

        const pixels = []
        for (let y = 0; y < height; y += _scale)
        {
            for (let x = 0; x < width; x += _scale)
            {
                const index = x * 4 + y * width * 4
                if (bits[index + 3] === 0)
                {
                    pixels.push(null)
                }
                else
                {
                    const color = Color.rgbToHex(bits[index], bits[index + 1], bits[index + 2])
                    pixels.push(parseInt(color, 16))
                }
            }
        }
        return pixels
    }
1249962
def _convert_np_data(data, data_type, num_elems):   # @NoSelf
        '''
        
        '''
        if (data_type == 51 or data_type == 52):
            if (data == ''):
                return ('\x00'*num_elems).encode()
            else:
                return data.ljust(num_elems, '\x00').encode('utf-8')
        elif (data_type == 32):
            data_stream = data.real.tobytes()
            data_stream += data.imag.tobytes()
            return data_stream
        else:
            return data.tobytes()
991570
def convert_ints_floats(self, flds):
        """"""
        for idx in self.idxs_float:
            flds[idx] = float(flds[idx])
        for idx in self.idxs_int:
            dig = flds[idx]
            #print 'idx={} ({}) {}'.format(idx, flds[idx], flds) # DVK
            flds[idx] = int(flds[idx]) if dig.isdigit() else dig
        for idx in self.idxs_strpat:
            hdr = self.hdr2idx.items()[idx][0]
            pat = self.strpat_hdrs[hdr]
            flds[idx] = pat.format(flds[idx])
793895
public AffineTransform metersToTilePixelsTransform(int tx, int ty, int zoomLevel) {
        AffineTransform result = new AffineTransform();
        double scale = 1.0 / resolution(zoomLevel);
        int nTiles = 2 << (zoomLevel - 1);
        int px = tx * -256;
        int py = (nTiles - ty) * -256;
        // flip y for upper-left origin
        result.scale(1, -1);
        result.translate(px, py);
        result.scale(scale, scale);
        result.translate(originShift, originShift);
        return result;
    }
471144
def convert_ram_dp_ar(ADDR_WIDTH=8, DATA_WIDTH=8):
    '''  '''
    clka = Signal(bool(0))
    clkb = Signal(bool(0))
    wea = Signal(bool(0))
    web = Signal(bool(0))
    addra = Signal(intbv(0)[ADDR_WIDTH:])
    addrb = Signal(intbv(0)[ADDR_WIDTH:])
    dia = Signal(intbv(0)[DATA_WIDTH:])
    dib = Signal(intbv(0)[DATA_WIDTH:])
    doa = Signal(intbv(0)[DATA_WIDTH:])
    dob = Signal(intbv(0)[DATA_WIDTH:])
    toVerilog(ram_dp_ar, clka, clkb, wea, web, addra, addrb, dia, dib, doa, dob)
242204
def ttotdev(data, rate=1.0, data_type="phase", taus=None):
    

    (taus, mtotdevs, mde, ns) = mtotdev(data, data_type=data_type,
                                        rate=rate, taus=taus)
    td = taus*mtotdevs / np.sqrt(3.0)
    tde = td / np.sqrt(ns)
    return taus, td, tde, ns