waits or spins for a predicate, returning the result.
        Predicate is a function that returns a truthy or falsy value.
        An exception in the function will be returned.
        A timeout will throw a TimeoutExpired Exception.
963556
def wait_for(
        predicate,
        timeout_seconds=120,
        sleep_seconds=1,
        ignore_exceptions=True,
        inverse_predicate=False,
        noisy=False,
        required_consecutive_success_count=1):
    
    count = 0
    start_time = time_module.time()
    timeout = Deadline.create_deadline(timeout_seconds)
    while True:
        try:
            result = predicate()
        except Exception as e:
            if ignore_exceptions:
                if noisy:
                    logger.exception("Ignoring error during wait.")
            else:
                count = 0
                raise  # preserve original stack
        else:
            if (not inverse_predicate and result) or (inverse_predicate and not result):
                count = count + 1
            if count >= required_consecutive_success_count:
                return result

        if timeout.is_expired():
            funname = __stringify_predicate(predicate)
            raise TimeoutExpired(timeout_seconds, funname)
        if noisy:
            header = '{}[{}/{}]'.format(
                shakedown.cli.helpers.fchr('>>'),
                pretty_duration(time_module.time() - start_time),
                pretty_duration(timeout_seconds)
            )
            if required_consecutive_success_count > 1:
                header = '{} [{} of {} times]'.format(
                    header,
                    count,
                    required_consecutive_success_count)
            print('{} spinning...'.format(header))
        time_module.sleep(sleep_seconds)
852945
function unless(pred, f) {
  if(!isPredOrFunc(pred)) {
    throw new TypeError(
      'unless: Pred or predicate function required for first argument'
    )
  }

  if(!isFunction(f)) {
    throw new TypeError(
      'unless: Function required for second argument'
    )
  }

  return x =>
    !predOrFunc(pred, x) ? f(x) : x
}
1039946
public static <T, U> BiPredicate<T, U> biPredicate(CheckedBiPredicate<T, U> predicate, Consumer<Throwable> handler) {
        return (t, u) -> {
            try {
                return predicate.test(t, u);
            }
            catch (Throwable e) {
                handler.accept(e);

                throw new IllegalStateException("Exception handler must throw a RuntimeException", e);
            }
        };
    }
1034930
public static <T> Predicate<T> predicate(Function<T, Boolean> function) {
        dbc.precondition(function != null, "cannot adapt a null function");
        return function::apply;
    }
478796
public S handleResultIf(Predicate<R> resultPredicate) {
    Assert.notNull(resultPredicate, "resultPredicate");
    failureConditions.add(resultPredicateFor(resultPredicate));
    return (S) this;
  }
144469
@SneakyThrows
    public static <T, R> Function<T, R> doIf(final Predicate<Object> condition, final Supplier<R> trueFunction,
                                             final Supplier<R> falseFunction) {
        return t -> {
            try {
                if (condition.test(t)) {
                    return trueFunction.get();
                }
                return falseFunction.get();
            } catch (final Throwable e) {
                LOGGER.warn(e.getMessage(), e);
                return falseFunction.get();
            }
        };
    }
242473
def wait_for_successful_query(url, wait_for=300, **kwargs):
    '''
    
    '''

    starttime = time.time()

    while True:
        caught_exception = None
        result = None
        try:
            result = query(url=url, **kwargs)
            if not result.get('Error') and not result.get('error'):
                return result
        except Exception as exc:
            caught_exception = exc

        if time.time() > starttime + wait_for:
            if not result and caught_exception:
                # workaround pylint bug https://www.logilab.org/ticket/3207
                raise caught_exception  # pylint: disable=E0702

            return result
996440
def _recv_predicate(self, predicate, timeout='default', raise_eof=True):
        

        if timeout == 'default':
            timeout = self._timeout

        self.timed_out = False

        start = time.time()
        try:
            while True:
                cut_at = predicate(self.buf)
                if cut_at > 0:
                    break
                if timeout is not None:
                    time_elapsed = time.time() - start
                    if time_elapsed > timeout:
                        raise socket.timeout
                    self._settimeout(timeout - time_elapsed)

                data = self._recv(4096)
                self._log_recv(data, False)
                self.buf += data

                if not data:
                    if raise_eof:
                        raise NetcatError("Connection dropped!")
                    cut_at = len(self.buf)
                    break

        except KeyboardInterrupt:
            self._print_header('\n======== Connection interrupted! ========')
            raise
        except socket.timeout:
            self.timed_out = True
            if self._raise_timeout:
                raise NetcatTimeout()
            return b''
        except socket.error as exc:
            raise NetcatError('Socket error: %r' % exc)

        self._settimeout(self._timeout)

        ret = self.buf[:cut_at]
        self.buf = self.buf[cut_at:]
        self._log_recv(ret, True)
        return ret
911037
def wait_for(func):
    

    def wrapped(*args, **kwargs):
        timeout = kwargs.pop('timeout', 15)

        start = time()
        result = None

        while time() - start < timeout:
            result = func(*args, **kwargs)
            if result:
                break
            sleep(0.2)

        return result

    return wrapped
270280
function safe(pred, x) {
  if(!isPredOrFunc(pred)) {
    throw new TypeError('safe: Pred or predicate function required for first argument')
  }

  return predOrFunc(pred, x)
    ? Just(x)
    : Nothing()
}
782071
public static <T, R> Function<T, R> doIf(final Predicate<T> condition, final CheckedFunction<T, R> trueFunction,
                                             final CheckedFunction<T, R> falseFunction) {
        return t -> {
            try {
                if (condition.test(t)) {
                    return trueFunction.apply(t);
                }
                return falseFunction.apply(t);
            } catch (final Throwable e) {
                LOGGER.warn(e.getMessage(), e);
                try {
                    return falseFunction.apply(t);
                } catch (final Throwable ex) {
                    throw new IllegalArgumentException(ex.getMessage());
                }
            }
        };
    }
997767
def _DoPredicates(args, context, callback, trace):
    
    block = args
    value = context.Lookup('@')
    for (predicate, args, func_type), statements in block.clauses:
        if func_type == ENHANCED_FUNC:
            do_clause = predicate(value, context, args)
        else:
            do_clause = predicate(value)
        
        if do_clause:
            if trace: trace.Push(predicate)
            _Execute(statements, context, callback, trace)
            if trace: trace.Pop()
            break
560102
private Selector parsePredicate(String predicate, String fullPath) 
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      tc.entry(cclass,
               "parsePredicate",
               "predicate: " + predicate); 

    Selector parsed = null;
    try
    {
      // Preprocess predicate for special characters
      String parserInput = preProcessForSpecials(predicate);
      
      // Attempt to parse predicate with "JMS" parser
      predicateParser =  MatchParserImpl.prime(predicateParser, parserInput, true);     
      parsed = predicateParser.getSelector(parserInput);
      if (parsed.getType() == Selector.INVALID)
      {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
          tc.debug(this,cclass, "parsePredicate", "Unable to parse predicate");           
        // reset the output to null
        parsed = null;
      }
      else
      {
        postProcessSelectorTree(parsed, fullPath);
      }
    }
    catch (Exception ex)
    {
      // No FFDC Code Needed.
      // In this case we will only trace the exception that we encountered.
      // It could be that the XPath parser is able to process this predicate
      // and that we've encountered a discrepancy between the syntax of an
      // expression supported by JMS and by XPath.
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        tc.debug(this,cclass, "parsePredicate", ex);   
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      tc.exit(this,cclass, "parsePredicate", parsed);     
    return parsed;
  }
878672
function predicate(str) {
                var prefix = fs.readFileSync(prefixTestFile, "utf8");
                var postfix = fs.readFileSync(postfixTestFile, "utf8");
                fs.writeFileSync(tmpTestFile, prefix + str + postfix, "utf8");
                process.stdout.write('.');
                var result = shelljs.exec("gtimeout 30s node " + tmpTestFile+ " > /dev/null 2>&1");
                if (result.code !== 0) {
                    return MAX_COST + 1;
                } else {
                    var results = JSON.parse(fs.readFileSync(resultFile, "utf8"));
                    if (results.featuresCovered[i]) {
                        if (results.modified) {
                            console.log("New feature splitting test found: " + str);
                            console.log("Writing test to " + newTestFileName + newTestIndex + ".js. Ignoring the test.");
                            fs.writeFileSync(newTestFileName + newTestIndex + ".js", prefix + str + postfix, "utf8");
                            return MAX_COST + 1;
                        } else {
                            var curMin = Object.keys(results.featuresCovered).length;
                            if (min > curMin) {
                                min = curMin;
                            }
                            console.log("Found a passing test");
                            console.log(str);
                            return curMin;
                        }
                    } else {
                        return MAX_COST + 1;
                    }
                }
            }
880284
public boolean detect(Predicate<Row> predicate) {
        Row row = new Row(this);
        while (row.hasNext()) {
            if (predicate.test(row.next())) {
                return true;
            }
        }
        return false;
    }
67149
public static <T> Predicate<T> predicate(CheckedPredicate<T> predicate) {
        return predicate(predicate, THROWABLE_TO_RUNTIME_EXCEPTION);
    }
195329
def _current_select():
    

    # helper to create the conjuction of predicates
    def and_with_possible_none(a, b):
        assert(a is not None or b is not None)
        if a is None:
            return b
        if b is None:
            return a
        return a & b

    def between_otherwise_and_current(predlist):
        lastother = None
        for i, p in enumerate(predlist[:-1]):
            if p is otherwise:
                lastother = i
        if lastother is None:
            return predlist[:-1]
        else:
            return predlist[lastother+1:-1]

    select = None
    pred_set = set()

    # for all conditions except the current children (which should be [])
    for predlist in _conditions_list_stack[:-1]:
        # negate all of the predicates between "otherwise" and the current one
        for predicate in between_otherwise_and_current(predlist):
            select = and_with_possible_none(select, ~predicate)
            pred_set.add((predicate, True))
        # include the predicate for the current one (not negated)
        if predlist[-1] is not otherwise:
            predicate = predlist[-1]
            select = and_with_possible_none(select, predicate)
            pred_set.add((predicate, False))

    if select is None:
        raise PyrtlError('problem with conditional assignment')
    if len(select) != 1:
        raise PyrtlInternalError('conditional predicate with length greater than 1')

    return select, pred_set