Background process from RuuviTag Sensors
960779
def run_get_data_background(macs, queue):
    
    while True:
        datas = RuuviTagSensor.get_data_for_sensors(macs, timeout_in_sec)
        queue.put(datas)
913069
async def main():
    """"""
    async with aiohttp.ClientSession() as session:
        data = Luftdaten(SENSOR_ID, loop, session)
        await data.get_data()

        if not await data.validate_sensor():
            print("Station is not available:", data.sensor_id)
            return

        if data.values and data.meta:
            # Print the sensor values
            print("Sensor values:", data.values)

            # Print the coordinates fo the sensor
            print("Location:", data.meta['latitude'], data.meta['longitude'])
1127413
def runStretchExperiment(numObjects=25):
  
  exp = L4L2Experiment(
    "profiling_experiment",
    enableLateralSP = True,
    enableFeedForwardSP=True
  )

  objects = createObjectMachine(
    machineType="simple",
    numInputBits=20,
    sensorInputSize=1024,
    externalInputSize=1024
  )
  objects.createRandomObjects(numObjects=numObjects, numPoints=10)
  exp.learnObjects(objects.provideObjectsToLearn())
  exp.printProfile()

  inferConfig = {
    "numSteps": len(objects[0]),
    "pairs": {
      0: objects[0]
    }
  }

  exp.infer(objects.provideObjectToInfer(inferConfig), objectName=0)
  exp.printProfile()

  exp.plotInferenceStats(
    fields=["L2 Representation",
            "Overlap L2 with object",
            "L4 Representation"]
  )
772456
def estimateBackgroundLevel(img, image_is_artefact_free=False, 
                            min_rel_size=0.05, max_abs_size=11):
    '''
    
    '''

    s0,s1 = img.shape[:2]
    s = min(max_abs_size, int(max(s0,s1)*min_rel_size))
    arr = np.zeros(shape=(s0-2*s, s1-2*s), dtype=img.dtype)
    
    #fill arr:
    _spatialStd(img, arr, s)
    #most homogeneous area:
    i,j = np.unravel_index(arr.argmin(), arr.shape)
    sub = img[int(i+0.5*s):int(i+s*1.5), 
              int(j+s*0.5):int(j+s*1.5)]

    return np.median(sub)
108708
def background_estimator(bdata):
    """"""

    crowded = False

    std = numpy.std(bdata)
    std0 = std
    mean = bdata.mean()
    while True:
        prep = len(bdata)
        numpy.clip(bdata, mean - 3 * std, mean + 3 * std, out=bdata)
        if prep == len(bdata):
            if std < 0.8 * std0:
                crowded = True
            break
        std = numpy.std(bdata)
        mean = bdata.mean()

    if crowded:
        median = numpy.median(bdata)
        mean = bdata.mean()
        std = bdata.std()
        return 2.5 * median - 1.5 * mean, std

    return bdata.mean(), bdata.std()
449479
function startFPSMonitor() {
        checkInit();
        var data = new Data();
        var w = new MonitorWidget("FPS", "", 2 /* HideMax */ | 1 /* HideMin */ | 4 /* HideMean */ | 32 /* RoundValues */);
        container.appendChild(w.element);
        var samples = [];
        var last = 0;
        function update(now) {
            var elapsed = (now - (last === 0 ? now : last)) / 1000;
            var fps = 1 / elapsed;
            if (fps !== Infinity) {
                if (samples.length === 64) {
                    samples.shift();
                }
                samples.push(fps);
                var sum = 0;
                for (var i = 0; i < samples.length; i++) {
                    sum += samples[i];
                }
                var mean = sum / samples.length;
                data.addSample(mean);
                w.addResult(data.calc());
            }
            last = now;
            requestAnimationFrame(update);
        }
        requestAnimationFrame(update);
    }
986645
def _initialize_background(self):
        """"""

        self.H = self.Hi.sum()
        if np.asarray(self.U).ndim == 2:
            self.Ubg = self.U * np.ones((self.ny))
        else:
            self.Ubg = np.expand_dims(self.U,axis=1) * np.ones((self.ny))


        if not (self.nz==2):
            self.gpi = self.g*(self.rhoi[1:]-self.rhoi[:-1])/self.rhoi[:-1]
            self.f2gpi = (self.f2/self.gpi)[:,np.newaxis,np.newaxis]

            assert self.gpi.size == self.nz-1, "Invalid size of gpi"

            assert np.all(self.gpi>0.), "Buoyancy jump has negative sign!"

            assert self.Hi.size == self.nz, self.logger.error('size of Hi does not' +
                     'match number of vertical levels nz')

            assert self.rhoi.size == self.nz, self.logger.error('size of rhoi does not' +
                     'match number of vertical levels nz')

            assert self.Ubg.size == self.nz * self.ny, self.logger.error('size of Ubg does not' +
                     'match number of vertical levels nz')

            assert self.Vbg.size == self.nz, self.logger.error('size of Vbg does not' +
                     'match number of vertical levels nz')

        else:
            self.f2gpi = np.array(self.rd**-2 *
                (self.Hi[0]*self.Hi[1])/self.H)[np.newaxis]


        self._initialize_stretching_matrix()

        # the meridional PV gradients in each layer
        self.Qy = self.beta - np.dot(self.S, self.Ubg) + np.gradient(np.gradient(self.Ubg, self.dy, axis=1), self.dy, axis=1)
        self.Qx = np.dot(self.S,self.Vbg)


        # complex versions, multiplied by k, speeds up computations to precompute
        self.ikQy = self.Qy[:,:,np.newaxis]*1j*self.k
        self.ilQx = self.Qx[:,np.newaxis,np.newaxis]*1j*self.l
294565
def backgroundMMD(self, catalog, method='cloud-in-cells', weights=None):
        

        # Select objects in annulus
        cut_annulus = self.roi.inAnnulus(catalog.lon,catalog.lat)
        mag_1 = catalog.mag_1[cut_annulus]
        mag_2 = catalog.mag_2[cut_annulus]

        # Units are (deg^2)
        solid_angle = ugali.utils.binning.take2D(self.solid_angle_mmd, mag_2, mag_1,
                                                 self.roi.bins_mag, self.roi.bins_mag)

        # Weight each object before binning
        # Divide by solid angle and bin size in magnitudes to get number density 
        # [objs / deg^2 / mag^2]
        if weights is None:
            number_density = (solid_angle*self.roi.delta_mag**2)**(-1)
        else:
            number_density = weights*(solid_angle*self.roi.delta_mag**2)**(-1)

        method = str(method).lower()
        if method == 'cloud-in-cells':
            # Apply cloud-in-cells algorithm
            mmd_background = ugali.utils.binning.cloudInCells(mag_2,mag_1,
                                                              [self.roi.bins_mag,self.roi.bins_mag],
                                                              weights=number_density)[0]
        elif method == 'bootstrap':
            # Not implemented
            raise ValueError("Bootstrap method not implemented")
            mag_1 + (mag_1_err * np.random.normal(0, 1., len(mag_1)))
            mag_2 + (mag_2_err * np.random.normal(0, 1., len(mag_2)))

        elif method == 'histogram':
            # Apply raw histogram
            mmd_background = np.histogram2d(mag_1,mag_2,bins=[self.roi.bins_mag,self.roi.bins_mag],
                                            weights=number_density)[0]

        elif method == 'kde':
            # Gridded kernel density estimator
            logger.warning("### KDE not implemented properly")
            mmd_background = ugali.utils.binning.kernelDensity(mag_2,mag_1,
                                                               [self.roi.bins_mag,self.roi.bins_mag],
                                                               weights=number_density)[0]
        elif method == 'uniform':
            logger.warning("### WARNING: Uniform CMD")
            hist = np.histogram2d(mag_1,mag_2,bins=[self.roi.bins_mag,self.roi.bins_mag], 
                                  weights=number_density)[0]
            mmd_background = np.mean(hist)*np.ones(hist.shape)
            observable = (self.solid_angle_mmd > self.minimum_solid_angle)
            mmd_background *= observable
            return mmd_background
        else:
            raise ValueError("Unrecognized method: %s"%method)
        ## Account for the objects that spill out of the observable space
        ## But what about the objects that spill out to red colors??
        #for index_color in range(0, len(self.roi.centers_color)):
        #    for index_mag in range(0, len(self.roi.centers_mag)):
        #        if self.solid_angle_cmd[index_mag][index_color] < self.minimum_solid_angle:
        #            cmd_background[index_mag - 1][index_color] += cmd_background[index_mag][index_color]
        #            cmd_background[index_mag][index_color] = 0.
        #            break

        mmd_area = self.solid_angle_mmd*self.roi.delta_mag**2 # [deg^2 * mag^2]

        # ADW: This accounts for leakage to faint magnitudes
        # But what about the objects that spill out to red colors??
        # Maximum obsevable magnitude index for each color (uses the fact that
        # np.argmin returns first minimum (zero) instance found.
        # NOTE: More complicated maps may have holes causing problems

        observable = (self.solid_angle_mmd > self.minimum_solid_angle)
        index_mag_1 = observable.argmin(axis=0) - 1
        index_mag_2 = np.arange(len(self.roi.centers_mag))
        # Add the cumulative leakage back into the last bin of the CMD
        leakage = (mmd_background * ~observable).sum(axis=0)
        ### mmd_background[[index_mag_1,index_mag_2]] += leakage
        # Zero out all non-observable bins
        ### mmd_background *= observable

        # Avoid dividing by zero by setting empty bins to the value of the 
        # minimum filled bin of the CMD. This choice is arbitrary and 
        # could be replaced by a static minimum, some fraction of the 
        # CMD maximum, some median clipped minimum, etc. However, should 
        # be robust against outliers with very small values.
        min_mmd_background = max(mmd_background[mmd_background > 0.].min(),
                                 1e-4*mmd_background.max())
        mmd_background[observable] = mmd_background[observable].clip(min_mmd_background)

        ### # ADW: This is a fudge factor introduced to renormalize the CMD
        ### # to the number of input stars in the annulus. While leakage
        ### # will still smooth the distribution, it shouldn't result in 
        ### fudge_factor = len(mag) / float((cmd_background*cmd_area).sum())
        ### cmd_background *= fudge_factor

        return mmd_background
288750
def initialize(self):
        """"""
        device_info = self.get_device_info()

        if device_info is None:
            self.name = None
            self.cam_id = None
            self.event_states = None
            return

        for key in device_info:
            if key == 'deviceName':
                self.name = device_info[key]
            elif key == 'deviceID':
                if len(device_info[key]) > 10:
                    self.cam_id = device_info[key]
                else:
                    self.cam_id = uuid.uuid4()

        events_available = self.get_event_triggers()
        if events_available:
            for event, channel_list in events_available.items():
                for channel in channel_list:
                    try:
                        self.event_states.setdefault(
                            SENSOR_MAP[event.lower()], []).append(
                                [False, channel, 0, datetime.datetime.now()])
                    except KeyError:
                        # Sensor type doesn't have a known friendly name
                        # We can't reliably handle it at this time...
                        _LOGGING.warning(
                            'Sensor type "%s" is unsupported.', event)

            _LOGGING.debug('Initialized Dictionary: %s', self.event_states)
        else:
            _LOGGING.debug('No Events available in dictionary.')

        self.get_motion_detection()
1039810
def background(self):
        """"""
        if self._background is None:
            self._background = GSBackgroundLayer()
            self._background._foreground = self
        return self._background
68157
function GetFilters () {
  let result = []
  log.debug(`Fetching filters in the existing ${motionDetectors.length} detector(s)...`)
  for (let i in motionDetectors) {
    result = result.concat(motionDetectors[i].filters)
  }
  log.debug(`Getting ${result.length} filters...`)
  return result
}
1202113
def face_and_energy_detector(image_path, detect_faces=True):
    
    source = Image.open(image_path)
    work_width = 800
    if source.mode != 'RGB' or source.bits != 8:
        source24 = source.convert('RGB')
    else:
        source24 = source.copy()

    grayscaleRMY = source24.convert('L', (0.5, 0.419, 0.081, 0))
    w = min(grayscaleRMY.size[0], work_width)
    h = w * grayscaleRMY.size[1] / grayscaleRMY.size[0]
    b = grayscaleRMY.resize((w, h), Image.BICUBIC)
    # b.save('step2.jpg')
    if detect_faces:
        info = do_face_detection(image_path)
        if info:
            return CropInfo(gravity=info)
    b = b.filter(ImageFilter.GaussianBlur(7))
    # b.save('step3.jpg')
    sobelXfilter = ImageFilter.Kernel((3, 3), (1, 0, -1, 2, 0, -2, 1, 0, -1), -.5)
    sobelYfilter = ImageFilter.Kernel((3, 3), (1, 2, 1, 0, 0, 0, -1, -2, -1), -.5)
    b = ImageChops.lighter(b.filter(sobelXfilter), b.filter(sobelYfilter))
    b = b.filter(ImageFilter.FIND_EDGES)
    # b.save('step4.jpg')
    ec = energy_center(b)
    return CropInfo(gravity=ec)
668196
function outputData()
{
    sensor.update();

    var floatData = sensor.getEulerAngles();
    console.log("Euler: Heading: " + floatData.get(0)
                + " Roll: " + floatData.get(1)
                + " Pitch: " + floatData.get(2)
                + " degrees");

    floatData = sensor.getQuaternions();
    console.log("Quaternion: W: " + floatData.get(0)
                + " X:" + floatData.get(1)
                + " Y: " + floatData.get(2)
                + " Z: " + floatData.get(3));

    floatData = sensor.getLinearAcceleration();
    console.log("Linear Acceleration: X: " + floatData.get(0)
                + " Y: " + floatData.get(1)
                + " Z: " + floatData.get(2)
                + " m/s^2");

    floatData = sensor.getGravityVectors();
    console.log("Gravity Vector: X: " + floatData.get(0)
                + " Y: " + floatData.get(1)
                + " Z: " + floatData.get(2)
                + " m/s^2");

    console.log("");
}
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
711552
def background_scan(content_dir):
    
    observer = watchdog.observers.Observer()
    observer.schedule(IndexWatchdog(content_dir),
                      content_dir, recursive=True)
    logging.info("Watching %s for changes", content_dir)
    observer.start()
1213905
def _initialize_background(self):
        """"""

        # background vel.
        if len(np.shape(self.U)) == 0:
          self.U = (self.U * np.ones((self.ny)))
        print(np.shape(self.U))
        self.set_U(self.U)

        # the meridional PV gradients in each layer
        self.Qy = (self.beta + np.gradient(np.gradient(self.U, self.dy), self.dy))[np.newaxis,...]


        # complex versions, multiplied by k, speeds up computations to pre-compute
        self.ikQy = np.expand_dims(self.Qy, axis=2) *  1j * self.k

        self.ilQx = 0.
917328
function getBackgroundPosition(image) {
	var logicValue = image.isSVG ? 1 : -1;
	var x = logicValue * (image.ratio > 1 ? image.coordinates.x / image.ratio : image.coordinates.x);
	var y = logicValue * (image.ratio > 1 ? image.coordinates.y / image.ratio : image.coordinates.y);
	var template = _.template('<%= (x ? x + "px" : x) %> <%= (y ? y + "px" : y) %>');
	return template({x: x, y: y});
}