Run detection. x is digital signal
543074
def detect(self, x, conf, adc_zero):
        
        self.c = conf
        self.annotations = []
        self.sample_valid = False

        if len(x) < 1:
            return []

        self.x = x
        self.adc_zero = adc_zero

        self.qfv = np.zeros((self.c._BUFLN), dtype="int64")
        self.smv = np.zeros((self.c._BUFLN), dtype="int64")
        self.v1 = 0

        t0 = 0
        self.tf = len(x) - 1
        self.t = 0 - self.c.dt4

        self.annot = GQRS.Annotation(0, "NOTE", 0, 0)

        # Cicular buffer of Peaks
        first_peak = GQRS.Peak(0, 0, 0)
        tmp = first_peak
        for _ in range(1, self.c._NPEAKS):
            tmp.next_peak = GQRS.Peak(0, 0, 0)
            tmp.next_peak.prev_peak = tmp
            tmp = tmp.next_peak
        tmp.next_peak = first_peak
        first_peak.prev_peak = tmp
        self.current_peak = first_peak

        if self.c.spm > self.c._BUFLN:
            if self.tf - t0 > self.c._BUFLN:
                tf_learn = t0 + self.c._BUFLN - self.c.dt4
            else:
                tf_learn = self.tf - self.c.dt4
        else:
            if self.tf - t0 > self.c.spm:
                tf_learn = t0 + self.c.spm - self.c.dt4
            else:
                tf_learn = self.tf - self.c.dt4

        self.countdown = -1
        self.state = "LEARNING"
        self.gqrs(t0, tf_learn)

        self.rewind_gqrs()

        self.state = "RUNNING"
        self.t = t0 - self.c.dt4
        self.gqrs(t0, self.tf)

        return self.annotations
144965
def run(self, channels=None, samplerate=None, blocksize=None):
        """"""

        source = self.processors[0]
        items = self.processors[1:]

        # Check if any processor in items need to force the samplerate
        force_samplerate = set([item.force_samplerate for item in items
                                if item.force_samplerate])
        if force_samplerate:
            if len(force_samplerate) > 1:
                raise(ValueError,
                      "Some processors specify different samplerate")
            force_samplerate = force_samplerate.pop()

            if samplerate and samplerate != force_samplerate:
                raise(ValueError, "A processor try to force the samplerate")

            samplerate = force_samplerate

        source.setup(channels=channels, samplerate=samplerate,
                     blocksize=blocksize)
        source.SIG_STOP = False
        last = source

        # setup/reset processors and configure properties throughout the pipe
        for item in items:
            item.source_mediainfo = source.mediainfo()
            item.setup(channels=last.channels(),
                       samplerate=last.samplerate(),
                       blocksize=last.blocksize(),
                       totalframes=last.totalframes())
            self._register_streamer(item)
            last = item

        # now stream audio data along the pipe
        if self._stream_thread:
            self._running_cond.acquire()
        self._is_running = True
        if self._stream_thread:
            self._running_cond.notify()
            self._running_cond.release()

        eod = False

        if source.id() == 'live_decoder':
            # Set handler for Interruption signal
            import signal

            def signal_handler(signum, frame):
                source.stop()

            signal.signal(signal.SIGINT, signal_handler)

        while not eod:
            frames, eod = source.process()
            for item in items:
                frames, eod = item.process(frames, eod)

        if source.id() == 'live_decoder':
            # Restore default handler for Interruption signal
            signal.signal(signal.SIGINT, signal.SIG_DFL)

        # Post-processing
        for item in items:
            item.post_process()

        # Release source
        source.release()
        # Release processors
        for item in items:
            item.release()

        self._is_running = False
107960
def run(path, timer=False, repeat=3, number=10000, precision=2):
    
    code = extractAtCyther(path)
    if not code:
        output = "There was no '@cyther' code collected from the " \
                 "file '{}'\n".format(path)
        # TODO This should use a result, right?
        return {'returncode': 0, 'output': output}

    module_directory = os.path.dirname(path)
    module_name = os.path.splitext(os.path.basename(path))[0]
    setup_string = SETUP_TEMPLATE.format(module_directory, module_name, '{}')

    if timer:
        string = TIMER_TEMPLATE.format(setup_string, code, repeat,
                                       number, precision, '{}')
    else:
        string = setup_string + code

    script = os.path.join(os.path.dirname(__file__), 'script.py')
    with open(script, 'w+') as file:
        file.write(string)

    response = call(['python', script])
    return response
1360325
def signal_catcher(callback):
    """"""
    def _catch_exit_signal(sig_num, _frame):
        print('Received signal {:d} invoking callback...'.format(sig_num))
        callback()

    signal.signal(signal.SIGINT, _catch_exit_signal)
    signal.signal(signal.SIGQUIT, _catch_exit_signal)
    signal.signal(signal.SIGTERM, _catch_exit_signal)
    yield
534255
def xrun(command, options, log=None, _log_container_as_started=False, logfile=None, timeout=-1, kill_callback=None):
    
    
    cmd = " ".join([command] + list(map(str, options)) )

    def _print_info(msg):
        if msg is None: return
        if log:
            log.info(msg)
        else:
            print(msg)

    def _print_warn(msg):
        if msg is None: return
        if log:
            log.warn(msg)
        else:
            print(msg)
    
    _print_info(u"Running: {0:s}".format(cmd))

    sys.stdout.flush()
    starttime = time.time()
    process = p = None
    try:
        foutname = os.path.join("/tmp", "stimela_output_{0:s}_{1:f}".format(hashlib.md5(cmd.encode('utf-8')).hexdigest(), starttime))
        with open(foutname, "w+") as fout:
            p = process = subprocess.Popen(cmd,
                                            stderr=fout,
                                            stdout=fout,
                                            shell=True)

            def clock_killer(p):
                while process.poll() is None and (timeout >= 0):
                    currenttime = time.time()
                    if (currenttime - starttime < timeout):
                        DEBUG and _print_warn(u"Clock Reaper: has been running for {0:f}, must finish in {1:f}".format(currenttime - starttime, timeout))
                    else:
                        _print_warn(u"Clock Reaper: Timeout reached for '{0:s}'... sending the KILL signal".format(cmd))
                        (kill_callback is not None) and kill_callback()
                    time.sleep(INTERRUPT_TIME)

            Thread(target=clock_killer, args=tuple([p])).start()

            while (process.poll() is None):
                currenttime = time.time()
                DEBUG and _print_info(u"God mode on: has been running for {0:f}".format(currenttime - starttime))
                time.sleep(INTERRUPT_TIME) # this is probably not ideal as it interrupts the process every few seconds, 
                #check whether there is an alternative with a callback
            assert hasattr(process, "returncode"), "No returncode after termination!"
        with open(foutname, "r") as fout:
            _print_info(fout.read())
    finally:
        if (process is not None) and process.returncode:
            raise StimelaCabRuntimeError('%s: returns errr code %d' % (command, process.returncode))
822751
def main(self, x):
        
        self.acc[0] = x * self.TAPS[-1]
        for i in range(1, len(self.acc)):
            self.acc[i] = self.acc[i - 1] + x * self.TAPS[len(self.TAPS) - 1 - i]

        self.out = self.acc[-1]
        return self.out
373778
def if_running(meth):
        """"""

        @wraps(meth)
        def check_running(self, *args, **kwargs):
            if not self.running:
                return
            return meth(self, *args, **kwargs)

        return check_running
1295568
def fingerprint(channel_samples: list, Fs: int = DEFAULT_FS,
                wsize: int = DEFAULT_WINDOW_SIZE,
                wratio: Union[int, float] = DEFAULT_OVERLAP_RATIO,
                fan_value: int = DEFAULT_FAN_VALUE,
                amp_min: Union[int, float] = DEFAULT_AMP_MIN)-> Iterator[tuple]:
    
    # FFT the signal and extract frequency components
    arr2D = mlab.specgram(
        channel_samples,
        NFFT=wsize,
        Fs=Fs,
        window=mlab.window_hanning,
        noverlap=int(wsize * wratio))[0]

    arr2D = 10 * np.log10(arr2D)

    arr2D[arr2D == -np.inf] = 0  # replace infs with zeros

    # find local maxima
    local_maxima = get_2D_peaks(arr2D, plot=False, amp_min=amp_min)

    # return hashes
    return generate_hashes(local_maxima, fan_value=fan_value)
854186
def calibrate_signal(signal, resp, fs, frange):
    """"""
    # remove dc offset from recorded response (synthesized orignal shouldn't have one)
    dc = np.mean(resp)
    resp = resp - dc

    npts = len(signal)
    f0 = np.ceil(frange[0] / (float(fs) / npts))
    f1 = np.floor(frange[1] / (float(fs) / npts))

    y = resp
    # y = y/np.amax(y) # normalize
    Y = np.fft.rfft(y)

    x = signal
    # x = x/np.amax(x) # normalize
    X = np.fft.rfft(x)

    H = Y / X

    # still issues warning because all of Y/X is executed to selected answers from
    # H = np.where(X.real!=0, Y/X, 1)
    # H[:f0].real = 1
    # H[f1:].real = 1
    # H = smooth(H)

    A = X / H

    return np.fft.irfft(A)
32165
def xstep(self):
        """

        self.YU[:] = self.Y - self.U
        YUf = sl.rfftn(self.YU, None, self.cri.axisN)
        YUf0 = self.block_sep0(YUf)
        YUf1 = self.block_sep1(YUf)

        b = self.rho * np.sum(np.conj(self.GDf) * YUf1, axis=-1)
        if self.cri.Cd > 1:
            b = np.sum(b, axis=self.cri.axisC, keepdims=True)
        b += self.DSf + self.rho*YUf0

        # Concatenate multiple GDf components on axisC. For
        # single-channel signals, and multi-channel signals with a
        # single-channel dictionary, we end up with sl.solvemdbi_ism
        # solving a linear system of rank dimN+1 (corresponding to the
        # dictionary and a gradient operator per spatial dimension) plus
        # an identity. For multi-channel signals with a multi-channel
        # dictionary, we end up with sl.solvemdbi_ism solving a linear
        # system of rank C.d (dimN+1) (corresponding to the dictionary
        # and a gradient operator per spatial dimension for each
        # channel) plus an identity.

        # The structure of the linear system to be solved depends on the
        # number of channels in the signal and dictionary. Both branches are
        # the same in the single-channel signal case (the choice of handling
        # it via the 'else' branch is somewhat arbitrary).
        if self.cri.C > 1 and self.cri.Cd == 1:
            # Concatenate multiple GDf components on the final axis
            # of GDf (that indexes the number of gradient operators). For
            # multi-channel signals with a single-channel dictionary,
            # sl.solvemdbi_ism has to solve a linear system of rank dimN+1
            # (corresponding to the dictionary and a gradient operator per
            # spatial dimension)
            DfGDf = np.concatenate(
                [self.Df[..., np.newaxis],] +
                [np.sqrt(self.rho)*self.GDf[..., k, np.newaxis] for k
                 in range(self.GDf.shape[-1])], axis=-1)
            self.Xf[:] = sl.solvemdbi_ism(DfGDf, self.rho, b[..., np.newaxis],
                                          self.cri.axisM, -1)[..., 0]
        else:
            # Concatenate multiple GDf components on axisC. For multi-channel
            # signals with a multi-channel dictionary, sl.solvemdbi_ism has
            # to solve a linear system of rank C.d (dimN+1) (corresponding to
            # the dictionary and a gradient operator per spatial dimension
            # for each channel) plus an identity.
            DfGDf = np.concatenate(
                [self.Df,] + [np.sqrt(self.rho)*self.GDf[..., k] for k
                              in range(self.GDf.shape[-1])],
                axis=self.cri.axisC)
            self.Xf[:] = sl.solvemdbi_ism(DfGDf, self.rho, b, self.cri.axisM,
                                          self.cri.axisC)

        self.X = sl.irfftn(self.Xf, self.cri.Nv, self.cri.axisN)

        if self.opt['LinSolveCheck']:
            if self.cri.C > 1 and self.cri.Cd == 1:
                Dop = lambda x: sl.inner(DfGDf, x[..., np.newaxis],
                                         axis=self.cri.axisM)
                DHop = lambda x: sl.inner(np.conj(DfGDf), x, axis=-1)
                ax = DHop(Dop(self.Xf))[..., 0] + self.rho*self.Xf
            else:
                Dop = lambda x: sl.inner(DfGDf, x, axis=self.cri.axisM)
                DHop = lambda x: sl.inner(np.conj(DfGDf), x,
                                          axis=self.cri.axisC)
                ax = DHop(Dop(self.Xf)) + self.rho*self.Xf
            self.xrrs = sl.rrs(ax, b)
        else:
            self.xrrs = None
739950
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t):
    X,Y = t.shape
    pt = np.zeros((X,Y))
    ""
    for i in range(X):
        for j in range(Y):
            for k in t:
                tmp = 6368.* np.arccos( np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+  np.sin(xmin+step*i)*np.sin(k[0]))
                if tmp < range_:
                    pt[i][j]+=k[2] / (1+tmp)
    return pt
152570
private int hunt(double x) {
        int jl = jsav, jm, ju, inc = 1;

        boolean ascnd = (xx[n - 1] >= xx[0]);

        if (jl < 0 || jl > n - 1) {
            jl = 0;
            ju = n - 1;
        } else {
            if (x >= xx[jl] == ascnd) {
                for (;;) {
                    ju = jl + inc;
                    if (ju >= n - 1) {
                        ju = n - 1;
                        break;
                    } else if (x < xx[ju] == ascnd) {
                        break;
                    } else {
                        jl = ju;
                        inc += inc;
                    }
                }
            } else {
                ju = jl;
                for (;;) {
                    jl = jl - inc;
                    if (jl <= 0) {
                        jl = 0;
                        break;
                    } else if (x >= xx[jl] == ascnd) {
                        break;
                    } else {
                        ju = jl;
                        inc += inc;
                    }
                }
            }
        }

        while (ju - jl > 1) {
            jm = (ju + jl) >> 1;
            if (x >= xx[jm] == ascnd) {
                jl = jm;
            } else {
                ju = jm;
            }
        }

        cor = Math.abs(jl - jsav) <= dj;
        jsav = jl;
        return Math.max(0, Math.min(n - 2, jl));
    }
79078
def alertingNetToMs(Facility_presence=0, ProgressIndicator_presence=0,
                    UserUser_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x1)  # 00000001
    packet = a / b
    if Facility_presence is 1:
        c = FacilityHdr(ieiF=0x1C)
        packet = packet / c
    if ProgressIndicator_presence is 1:
        d = ProgressIndicatorHdr(ieiPI=0x1E)
        packet = packet / d
    if UserUser_presence is 1:
        e = UserUserHdr(ieiUU=0x7E)
        packet = packet / e
    return packet
858392
def _run(
        self,
        circuit: circuits.Circuit,
        param_resolver: study.ParamResolver,
        repetitions: int,
    ) -> Dict[str, List[np.ndarray]]:
        """"""

        circuit = protocols.resolve_parameters(circuit, param_resolver)
        _verify_xmon_circuit(circuit)

        # Delegate to appropriate method based on contents.
        if circuit.are_all_measurements_terminal():
            return self._run_sweep_sample(circuit, repetitions)
        else:
            return self._run_sweep_repeat(circuit, repetitions)
1075953
def run(self, interval):
        """"""
        self._halt = False
        
        # TODO: some error checking to make sure valid paramenters are set
        if self.save_data:
            # initize data set
            self.current_dataset_name = self.set_name
            self.datafile.init_data(self.current_dataset_name, self.aitimes.shape, mode='open')
            self.set_name = increment_title(self.set_name)

        # save the start time and set last tick to expired, so first
        # acquisition loop iteration executes immediately
        self.start_time = time.time()
        self.last_tick = self.start_time - (interval/1000)
        self.interval = interval
        self.acq_thread = threading.Thread(target=self._worker)

        # arm the first read
        self.player.set_aochan(self.aochan)
        self.player.set_aichan(self.aichan)

        # make sure a signal is loaded
        self.reset_stim()
        
        # and go!
        self.acq_thread.start()

        return self.acq_thread
1081383
def isRunning(self, waitTime=0):
        
        waitUntil = time.time() + waitTime
        while True:
            if self.getPID() > 0:
                return True
            else:
                self._pid = PlatformManager.getWindowPID(PlatformManager.getWindowByTitle(re.escape(self._title)))

            # Check if we've waited long enough
            if time.time() > waitUntil:
                break
            else:
                time.sleep(self._defaultScanRate)
        return self.getPID() > 0
169093
function run (x, cb) {
  const s = speculum(null, Echo, x)
  s.on('end', cb)
  s.on('error', cb)

  const reader = new Count({ highWaterMark: 0 }, 10)

  reader.pipe(s).resume()
}