exponential backoff for reconnections
192412
function generateInterval (k) {
  let maxInterval = (Math.pow(2, k) - 1) * 1000

  if (maxInterval > 30 * 1000) {
    // If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
    maxInterval = 30 * 1000
  }
  // generate the interval to a random number between 0 and the maxInterval determined from above
  return Math.random() * maxInterval
}
1208483
private void backward(TrellisNode[][] trellis) {
        int n = trellis.length - 1;
        TrellisNode[] tn = trellis[n];
        for (int i = 0; i < numClasses; i++) {
            tn[i].beta = 1.0;
        }

        for (int t = n; t-- > 0;) {
            TrellisNode[] tt = trellis[t];
            TrellisNode[] tt1 = trellis[t+1];
            for (int i = 0; i < numClasses; i++) {
                TrellisNode tti = tt[i];
                tti.beta = 0.0;
                for (int j = 0; j < numClasses; j++) {
                    tti.beta += tt1[j].expScores[i] * tt1[j].beta;
                }
            }

            // Normalize beta values since they increase quickly
            double sum = 0.0;
            for (int i = 0; i < numClasses; i++) {
                sum += tt[i].beta;
            }
            for (int i = 0; i < numClasses; i++) {
                tt[i].beta /= sum;
            }
        }
    }
1314204
public void backOff(BackOffContext backOffContext)
			throws BackOffInterruptedException {
		ExponentialBackOffContext context = (ExponentialBackOffContext) backOffContext;
		try {
			long sleepTime = context.getSleepAndIncrement();
			if (logger.isDebugEnabled()) {
				logger.debug("Sleeping for " + sleepTime);
			}
			sleeper.sleep(sleepTime);
		}
		catch (InterruptedException e) {
			throw new BackOffInterruptedException("Thread interrupted while sleeping", e);
		}
	}
378993
def digraph_walker_backwards(graph, element, call_back):
    """"""
    call_back(graph, element)
    for predecessor in graph.predecessors(element):
        call_back(graph, predecessor)
    for predecessor in graph.predecessors(element):
        digraph_walker_backwards(graph, predecessor, call_back)
103158
def solve(self, lam):
        ''''''
        s = weighted_graphtf_poisson(self.nnodes, self.obs, lam,
                                 self.Dk.shape[0], self.Dk.shape[1], self.Dk.nnz,
                                 self.Dk.row.astype('int32'), self.Dk.col.astype('int32'), self.Dk.data.astype('double'),
                                 self.maxsteps, self.converge,
                                 self.beta, self.u)
        self.steps.append(s)
        return self.beta
48608
def _backward_slice_indirect(self, cfgnode, sim_successors, current_function_addr):
        
        # TODO: make this a real indirect jump resolver under the new paradigm

        irsb = sim_successors.artifacts['irsb']  # shorthand

        l.debug("Resolving indirect jump at IRSB %s", irsb)

        # Let's slice backwards from the end of this exit
        next_tmp = irsb.next.tmp
        stmt_id = [i for i, s in enumerate(irsb.statements)
                   if isinstance(s, pyvex.IRStmt.WrTmp) and s.tmp == next_tmp][0]

        cdg = self.project.analyses.CDG(cfg=self, fail_fast=self._fail_fast)
        ddg = self.project.analyses.DDG(cfg=self, start=current_function_addr, call_depth=0, fail_fast=self._fail_fast)

        bc = self.project.analyses.BackwardSlice(self,
                                                 cdg,
                                                 ddg,
                                                 targets=[(cfgnode, stmt_id)],
                                                 same_function=True,
                                                 fail_fast=self._fail_fast)
        taint_graph = bc.taint_graph
        # Find the correct taint
        next_nodes = [cl for cl in taint_graph.nodes() if cl.block_addr == sim_successors.addr]

        if not next_nodes:
            l.error('The target exit is not included in the slice. Something is wrong')
            return []

        next_node = next_nodes[0]

        # Get the weakly-connected subgraph that contains `next_node`
        all_subgraphs = networkx.weakly_connected_component_subgraphs(taint_graph)
        starts = set()
        for subgraph in all_subgraphs:
            if next_node in subgraph:
                # Make sure there is no symbolic read...
                # FIXME: This is an over-approximation. We should try to limit the starts more
                nodes = [n for n in subgraph.nodes() if subgraph.in_degree(n) == 0]
                for n in nodes:
                    starts.add(n.block_addr)

        # Execute the slice
        successing_addresses = set()
        annotated_cfg = bc.annotated_cfg()
        for start in starts:
            l.debug('Start symbolic execution at 0x%x on program slice.', start)
            # Get the state from our CFG
            node = self.get_any_node(start)
            if node is None:
                # Well, we have to live with an empty state
                base_state = self.project.factory.blank_state(addr=start)
            else:
                base_state = node.input_state.copy()
                base_state.set_mode('symbolic')
                base_state.ip = start

                # Clear all initial taints (register values, memory values, etc.)
                initial_nodes = [n for n in bc.taint_graph.nodes() if bc.taint_graph.in_degree(n) == 0]
                for cl in initial_nodes:
                    # Iterate in all actions of this node, and pick corresponding actions
                    cfg_nodes = self.get_all_nodes(cl.block_addr)
                    for n in cfg_nodes:
                        if not n.final_states:
                            continue
                        actions = [ac for ac in n.final_states[0].history.recent_actions
                                   # Normally it's enough to only use the first final state
                                   if ac.bbl_addr == cl.block_addr and
                                   ac.stmt_idx == cl.stmt_idx
                                   ]
                        for ac in actions:
                            if not hasattr(ac, 'action'):
                                continue
                            if ac.action == 'read':
                                if ac.type == 'mem':
                                    unconstrained_value = base_state.solver.Unconstrained('unconstrained',
                                                                                      ac.size.ast * 8)
                                    base_state.memory.store(ac.addr,
                                                            unconstrained_value,
                                                            endness=self.project.arch.memory_endness)
                                elif ac.type == 'reg':
                                    unconstrained_value = base_state.solver.Unconstrained('unconstrained',
                                                                                      ac.size.ast * 8)
                                    base_state.registers.store(ac.offset,
                                                               unconstrained_value,
                                                               endness=self.project.arch.register_endness)

                # Clear the constraints!
                base_state.release_plugin('solver')

            # For speed concerns, we are limiting the timeout for z3 solver to 5 seconds
            base_state.solver._solver.timeout = 5000

            sc = self.project.factory.simulation_manager(base_state)
            sc.use_technique(Slicecutor(annotated_cfg))
            sc.use_technique(LoopSeer(bound=1))
            sc.run()

            if sc.cut or sc.deadended:
                all_deadended_states = sc.cut + sc.deadended
                for s in all_deadended_states:
                    if s.addr == sim_successors.addr:
                        # We want to get its successors
                        succs = s.step()
                        for succ in succs.flat_successors:
                            successing_addresses.add(succ.addr)

            else:
                l.debug("Cannot determine the exit. You need some better ways to recover the exits :-(")

        l.debug('Resolution is done, and we have %d new successors.', len(successing_addresses))

        return list(successing_addresses)
398697
def PartialDynamicSystem(self, ieq, variable):
        

        if ieq == 0:

            #            if variable==self.physical_nodes[0].variable:
            # print('1')
            #                # U1 is output
            #                # U1=i1/pC+U2
            #                Uc=Variable(hidden=True)
            #                block1=ODE(self.variables[0],Uc,[1],[0,self.C])
            #                sub1=Sum([self.physical_nodes[1].variable,Uc],variable)
            #                return [block1,sub1]
            #            elif variable==self.physical_nodes[1].variable:
            #                print('2')
            #                # U2 is output
            #                # U2=U1-i1/pC
            #                Uc=Variable(hidden=True)
            #                block1=ODE(self.variables[0],Uc,[-1],[0,self.C])
            #                sum1=Sum([self.physical_nodes[0].variable,Uc],variable)
            #                return [block1,sum1]
            if variable == self.variables[0]:  # i1=(u1-u2)/Lp
                print('3')
                # i1 is output
                # i1=pC(U1-U2)
                Uc = Variable(hidden=True)
                subs1 = Subtraction(
                    self.physical_nodes[0].variable, self.physical_nodes[1].variable, Uc)
                block1 = ODE(Uc, variable, [1], [0, self.L])
                return [block1, subs1]
        elif ieq == 1:
            # i1=-i2
            if variable == self.variables[0]:
                # i1 as output
                return [Gain(self.variables[1], self.variables[0], -1)]
            elif variable == self.variables[1]:
                # i2 as output
                return [Gain(self.variables[0], self.variables[1], -1)]
892447
def backoff_generator(self):
        """"""
        for x in self.config.backoff_delays:
            yield x
        while True:
            yield self.config.backoff_delays[-1]
1161636
public static Function<Flux<Throwable>, Publisher<?>> exponentialBackOffError(Duration minimum, Duration maximum, Duration timeout) {
        Instant finish = Instant.now().plus(timeout);
        return errors -> getDelay(minimum, maximum, finish, errors.zipWith(Flux.range(0, Integer.MAX_VALUE), (error, iteration) -> iteration.longValue()));
    }
771800
def shutdown(self):
        
        self._shuttingDown = {key: Deferred()
                              for key in self.cachedConnections.keys()}
        return DeferredList(
            [maybeDeferred(p.transport.loseConnection)
             for p in self.cachedConnections.values()]
             + self._shuttingDown.values())
952346
private void linkFirst(E e) {
        final Node<E> newNode = new Node<E>(Objects.requireNonNull(e));

        restartFromHead:
        for (;;)
            for (Node<E> h = head, p = h, q;;) {
                if ((q = p.prev) != null &&
                    (q = (p = q).prev) != null)
                    // Check for head updates every other hop.
                    // If p == q, we are sure to follow head instead.
                    p = (h != (h = head)) ? h : q;
                else if (p.next == p) // PREV_TERMINATOR
                    continue restartFromHead;
                else {
                    // p is first node
                    newNode.lazySetNext(p); // CAS piggyback
                    if (p.casPrev(null, newNode)) {
                        // Successful CAS is the linearization point
                        // for e to become an element of this deque,
                        // and for newNode to become "live".
                        if (p != h) // hop two nodes at a time
                            casHead(h, newNode);  // Failure is OK.
                        return;
                    }
                    // Lost CAS race to another thread; re-read prev
                }
            }
    }
789405
def backoff_strategy(options)
      available_types = [:constant, :linear, :fibonacci, :exponential]
      raise ArgumentError, 'Incorrect backoff type' unless available_types.include?(options[:type])
      self.backoff_intervals = Backoff.new(options[:type], options[:start]).intervals
    end
633919
def _flux(t, n, duration, std, offs=1):
    '''
    
    '''
    duration *= len(t) / t[-1]
    duration = int(max(duration, 1))

    pos = []
    n *= t[-1]
    pp = np.arange(len(t))
    valid = np.ones_like(t, dtype=bool)
    for _ in range(int(round(n))):
        try:
            ppp = np.random.choice(pp[valid], 1)[0]
            pos.append(ppp)
            valid[max(0, ppp - duration - 1):ppp + duration + 1] = False
        except ValueError:
            break
    sign = np.random.randint(0, 2, len(pos))
    sign[sign == 0] = -1

    out = np.zeros_like(t)

    amps = np.random.normal(loc=0, scale=1, size=len(pos))

    if duration > 2:
        evt = gaussian(duration, duration)
        evt -= evt[0]
    else:
        evt = np.ones(shape=duration)


    for s, p, a in zip(sign, pos, amps):
        pp = duration
        if p + duration > len(out):
            pp = len(out) - p

        out[p:p + pp] = s * a * evt[:pp]

    out /= out.std() / std
    out += offs
    return out
270525
def advance(self, dt_msec):
        
        # TODO: Make the time step adjustable, and choose an appropriate
        # numerical integration method to maintain stability.
        # TODO: The need to catch overflows indicates that the current method is
        # not stable for all possible network configurations and states.
        try:
            self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
            self.v += 0.5 * dt_msec * (0.04 * self.v ** 2 + 5 * self.v + 140 - self.u + self.current)
            self.u += dt_msec * self.a * (self.b * self.v - self.u)
        except OverflowError:
            # Reset without producing a spike.
            self.v = self.c
            self.u = self.b * self.v

        self.fired = 0.0
        if self.v > 30.0:
            # Output spike and reset.
            self.fired = 1.0
            self.v = self.c
            self.u += self.d
610793
def _remove_layer_and_reconnect(self, layer):
        
        successors = self.get_successors(layer)
        predecessors = self.get_predecessors(layer)
        # remove layer's edges
        for succ in successors:
            self._remove_edge(layer, succ)
        for pred in predecessors:
            self._remove_edge(pred, layer)

        # connect predecessors and successors
        for pred in predecessors:
            for succ in successors:
                self._add_edge(pred, succ)

        # remove layer in the data structures
        self.layer_list.remove(layer)
        self.keras_layer_map.pop(layer)

        # re-assign input and output layers if layer happens to be an
        # input / output layer
        if layer in self.input_layers:
            idx = self.input_layers.index(layer)
            self.input_layers.pop(idx)
            for pred in predecessors:
                self.input_layers.insert(idx, pred)
                idx += 1
        if layer in self.output_layers:
            idx = self.output_layers.index(layer)
            self.output_layers.pop(idx)
            for succ in successors:
                self.output_layers.insert(idx, succ)
                idx += 1
989821
def policy_backward(eph, epx, epdlogp, model):
    """"""
    dW2 = np.dot(eph.T, epdlogp).ravel()
    dh = np.outer(epdlogp, model["W2"])
    # Backprop relu.
    dh[eph <= 0] = 0
    dW1 = np.dot(dh.T, epx)
    return {"W1": dW1, "W2": dW2}
405656
@Override
    public void backward() {
        // TODO: This is less numerically stable than the O(n^2) method of
        // multiplying \prod_{j=1}^{i-1} x_j \prod_{j+1}^n x_j  
        Tensor x = modIn.getOutput();
        Tensor xAdj = modIn.getOutputAdj();
        Tensor tmp = new Tensor(xAdj); // copy
        tmp.fill(yAdj.getValue(0));
        tmp.multiply(y.getValue(0));
        tmp.elemDivide(x);
        xAdj.elemAdd(tmp);
    }