Пример #1
0
    def param(self, name, func, *args, **kwargs):
        """Create a black box parameter and return its value."""
        if self._got_reward:
            raise ValueError("all parameter definitions must come before maximize/minimize")
        if not isinstance(name, Str):
            raise TypeError("name must be a string, not {_coconut_format_0}".format(_coconut_format_0=(name)))
        if name in self._new_params:
            raise ValueError("parameter of name {_coconut_format_0} already exists".format(_coconut_format_0=(name)))

        args = param_processor.standardize_args(func, args)
        kwargs = param_processor.standardize_kwargs(kwargs)

        _coconut_match_to = self._old_params
        _coconut_match_check = False
        if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
            _coconut_match_temp_0 = _coconut_match_to.get(name, _coconut_sentinel)
            if (_coconut_match_temp_0 is not _coconut_sentinel) and (_coconut.isinstance(_coconut_match_temp_0, _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_temp_0) == 3):
                old_func = _coconut_match_temp_0[0]
                old_args = _coconut_match_temp_0[1]
                old_kwargs = _coconut_match_temp_0[2]
                _coconut_match_check = True
        if _coconut_match_check:
            if (func, args) != (old_func, old_args):
                print("BBopt Warning: detected change in parameter {_coconut_format_0} ({_coconut_format_1} != {_coconut_format_2}) (you may need to delete your old BBopt data)".format(_coconut_format_0=(name), _coconut_format_1=((func, args)), _coconut_format_2=((old_func, old_args))))

        value = self.backend.param(name, func, *args, **kwargs)
        self._new_params[name] = (func, args, kwargs)
        self._current_example["values"][name] = value
        return value
Пример #2
0
def serve_values(
    name,
    func,
    args,
    kwargs,
    serving_values,
    fallback_func,
    backend_name=None,
    implemented_funcs=None,
    supported_kwargs=None,
):
    """Determines the parameter value to serve for the given parameter
    name and kwargs. First checks for unsupported funcs or kwargs, then
    uses the following algorithm:
    1. if name in serving_values, use serving_values[name], else
    2. if guess in kwargs, use the guess, else
    3. call fallback_func(name, func, *args, **kwargs)."""
    # validate arguments
    if implemented_funcs is not None:
        assert backend_name is not None, "serve_values expects a backend_name argument when doing func validation"
        if func not in implemented_funcs:
            raise ValueError(
                "the {_coconut_format_0} backend does not implement the {_coconut_format_1} function"
                .format(_coconut_format_0=(backend_name),
                        _coconut_format_1=(func)))
    if supported_kwargs is not None:
        assert backend_name is not None, "serve_values expects a backend_name argument when doing kwargs validation"
        unsupported_kwargs = set(kwargs) - set(supported_kwargs)
        if unsupported_kwargs:
            raise ValueError(
                "the {_coconut_format_0} backend does not support {_coconut_format_1} option(s)"
                .format(_coconut_format_0=(backend_name),
                        _coconut_format_1=(unsupported_kwargs)))

# determine value
    _coconut_match_to = serving_values
    _coconut_match_check = False
    if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
        _coconut_match_temp_0 = _coconut_match_to.get(name, _coconut_sentinel)
        if _coconut_match_temp_0 is not _coconut_sentinel:
            value = _coconut_match_temp_0
            _coconut_match_check = True
    if _coconut_match_check:
        return value
    else:
        _coconut_match_to = kwargs
        _coconut_match_check = False
        if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
            _coconut_match_temp_0 = _coconut_match_to.get(
                "guess", _coconut_sentinel)
            if _coconut_match_temp_0 is not _coconut_sentinel:
                guess = _coconut_match_temp_0
                _coconut_match_check = True
        if _coconut_match_check:
            return guess
        else:
            return fallback_func(name, func, *args, **kwargs)
Пример #3
0
def running_best(examples):
    """Yield running best examples seen at each point."""
    best_example = max_gain = min_loss = None
    for example in examples:

        _coconut_case_match_to_0 = example
        _coconut_case_match_check_0 = False
        _coconut_match_set_name_values = _coconut_sentinel
        _coconut_match_set_name_gain = _coconut_sentinel
        if _coconut.isinstance(_coconut_case_match_to_0, _coconut.abc.Mapping):
            _coconut_match_temp_0 = _coconut_case_match_to_0.get("values", _coconut_sentinel)
            _coconut_match_temp_1 = _coconut_case_match_to_0.get("gain", _coconut_sentinel)
            if (_coconut_match_temp_0 is not _coconut_sentinel) and (_coconut_match_temp_1 is not _coconut_sentinel):
                _coconut_match_set_name_values = _coconut_match_temp_0
                _coconut_match_set_name_gain = _coconut_match_temp_1
                _coconut_case_match_check_0 = True
        if _coconut_case_match_check_0:
            if _coconut_match_set_name_values is not _coconut_sentinel:
                values = _coconut_match_temp_0
            if _coconut_match_set_name_gain is not _coconut_sentinel:
                gain = _coconut_match_temp_1
        if _coconut_case_match_check_0:
            if min_loss is not None:
                raise ValueError("cannot have examples with maximize and examples with minimize")
            if max_gain is None or gain >= max_gain:
                best_example = example
                max_gain = gain

        if not _coconut_case_match_check_0:
            _coconut_match_set_name_values = _coconut_sentinel
            _coconut_match_set_name_loss = _coconut_sentinel
            if _coconut.isinstance(_coconut_case_match_to_0, _coconut.abc.Mapping):
                _coconut_match_temp_0 = _coconut_case_match_to_0.get("values", _coconut_sentinel)
                _coconut_match_temp_1 = _coconut_case_match_to_0.get("loss", _coconut_sentinel)
                if (_coconut_match_temp_0 is not _coconut_sentinel) and (_coconut_match_temp_1 is not _coconut_sentinel):
                    _coconut_match_set_name_values = _coconut_match_temp_0
                    _coconut_match_set_name_loss = _coconut_match_temp_1
                    _coconut_case_match_check_0 = True
            if _coconut_case_match_check_0:
                if _coconut_match_set_name_values is not _coconut_sentinel:
                    values = _coconut_match_temp_0
                if _coconut_match_set_name_loss is not _coconut_sentinel:
                    loss = _coconut_match_temp_1
            if _coconut_case_match_check_0:
                if max_gain is not None:
                    raise ValueError("cannot have examples with maximize and examples with minimize")
                if min_loss is None or loss <= min_loss:
                    best_example = example
                    min_loss = loss

        if not _coconut_case_match_check_0:
            raise ValueError("invalid example {_coconut_format_0}".format(_coconut_format_0=(example)))

        yield best_example
Пример #4
0
def make_features(
    values,
    params,
    fallback_func=param_processor.choose_default_placeholder,
    converters={},
    convert_fallback=True,
):
    """Return an iterator of the values for the parameters in sorted order with the given fallback function.
    If passed, converters must map funcs to functions from (value, *args) -> new_value which will be run
    on the resulting value for that func (but only on fallbacks if convert_fallback)."""
    for name, (func, args, kwargs) in sorted_items(params):
        # determine feature
        fallback = False
        _coconut_match_to = values
        _coconut_match_check = False
        if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
            _coconut_match_temp_0 = _coconut_match_to.get(
                name, _coconut_sentinel)
            if _coconut_match_temp_0 is not _coconut_sentinel:
                feature = _coconut_match_temp_0
                _coconut_match_check = True
        if _coconut_match_check:
            pass
        else:
            _coconut_match_to = kwargs
            _coconut_match_check = False
            if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
                _coconut_match_temp_0 = _coconut_match_to.get(
                    "placeholder_when_missing", _coconut_sentinel)
                if _coconut_match_temp_0 is not _coconut_sentinel:
                    placeholder_value = _coconut_match_temp_0
                    _coconut_match_check = True
            if _coconut_match_check:
                feature = placeholder_value
            else:
                fallback = True
                feature = fallback_func(name, func, *args, **kwargs)


# run converters
        if not fallback or convert_fallback:
            _coconut_match_to = converters
            _coconut_match_check = False
            if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
                _coconut_match_temp_0 = _coconut_match_to.get(
                    func, _coconut_sentinel)
                if _coconut_match_temp_0 is not _coconut_sentinel:
                    converter_func = _coconut_match_temp_0
                    _coconut_match_check = True
            if _coconut_match_check:
                feature = converter_func(feature, *args)

        yield feature
Пример #5
0
def split_examples(
    examples,
    params,
    fallback_func=param_processor.choose_default_placeholder,
    converters={},
    convert_fallback=True,
):
    """Split examples into a list of data points and a list of losses with the given fallback function."""
    data_points, losses = [], []
    for example in examples:

        # extract values, loss
        _coconut_match_to = example
        _coconut_case_check_0 = False
        if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
            _coconut_match_temp_0 = _coconut_match_to.get(
                "values", _coconut_sentinel)
            _coconut_match_temp_1 = _coconut_match_to.get(
                "gain", _coconut_sentinel)
            if (_coconut_match_temp_0
                    is not _coconut_sentinel) and (_coconut_match_temp_1
                                                   is not _coconut_sentinel):
                values = _coconut_match_temp_0
                gain = _coconut_match_temp_1
                _coconut_case_check_0 = True
        if _coconut_case_check_0:
            loss = negate_objective(gain)
        if not _coconut_case_check_0:
            if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
                _coconut_match_temp_0 = _coconut_match_to.get(
                    "values", _coconut_sentinel)
                _coconut_match_temp_1 = _coconut_match_to.get(
                    "loss", _coconut_sentinel)
                if (_coconut_match_temp_0 is not _coconut_sentinel) and (
                        _coconut_match_temp_1 is not _coconut_sentinel):
                    values = _coconut_match_temp_0
                    loss = _coconut_match_temp_1
                    _coconut_case_check_0 = True
            if _coconut_case_check_0:
                pass
        if not _coconut_case_check_0:
            raise ValueError("invalid example {}".format(example))


# extract features
        features = (list)(make_features(values, params, fallback_func,
                                        converters, convert_fallback))

        # add to data_points, losses
        (data_points.append)(features)
        (losses.append)(loss)

    return data_points, losses
Пример #6
0
 def register_alias(self, name, alias, replace=False):
     """Register an alias for the given name."""
     if not replace:
         _coconut_match_to_2 = self.aliases
         _coconut_match_check_2 = False
         _coconut_match_set_name_stored_alias = _coconut_sentinel
         if _coconut.isinstance(_coconut_match_to_2, _coconut.abc.Mapping):
             _coconut_match_temp_0 = _coconut_match_to_2.get(
                 name, _coconut_sentinel)
             if _coconut_match_temp_0 is not _coconut_sentinel:
                 _coconut_match_set_name_stored_alias = _coconut_match_temp_0
                 _coconut_match_check_2 = True
         if _coconut_match_check_2:
             if _coconut_match_set_name_stored_alias is not _coconut_sentinel:
                 stored_alias = _coconut_match_temp_0
         if _coconut_match_check_2:
             if stored_alias == alias:
                 return
             else:
                 raise ValueError(
                     "cannot change registry for already existing alias: {_coconut_format_0}"
                     .format(_coconut_format_0=(alias)))
     if alias in self.registered:
         raise ValueError(
             "cannot register overlapping alias: {_coconut_format_0}".
             format(_coconut_format_0=(alias)))
     for registry in self.no_conflict_registries:
         if name in registry:
             raise ValueError(
                 "cannot register alias with conflicting {_coconut_format_0}: {_coconut_format_1}"
                 .format(_coconut_format_0=(registry.obj_name),
                         _coconut_format_1=(alias)))
     self.aliases[alias] = name
Пример #7
0
 def register(self, name, value, replace=False):
     """Register value under the given name."""
     if not replace:
         _coconut_match_to_1 = self.registered
         _coconut_match_check_1 = False
         _coconut_match_set_name_stored_val = _coconut_sentinel
         if _coconut.isinstance(_coconut_match_to_1, _coconut.abc.Mapping):
             _coconut_match_temp_0 = _coconut_match_to_1.get(
                 name, _coconut_sentinel)
             if _coconut_match_temp_0 is not _coconut_sentinel:
                 _coconut_match_set_name_stored_val = _coconut_match_temp_0
                 _coconut_match_check_1 = True
         if _coconut_match_check_1:
             if _coconut_match_set_name_stored_val is not _coconut_sentinel:
                 stored_val = _coconut_match_temp_0
         if _coconut_match_check_1:
             if stored_val == value:
                 return
             else:
                 raise ValueError(
                     "cannot change registry for already existing name: {_coconut_format_0}"
                     .format(_coconut_format_0=(name)))
     if name in self.aliases:
         raise ValueError(
             "cannot register name with existing alias: {_coconut_format_0}"
             .format(_coconut_format_0=(name)))
     for registry in self.no_conflict_registries:
         if name in registry:
             raise ValueError(
                 "cannot register name with conflicting {_coconut_format_0}: {_coconut_format_1}"
                 .format(_coconut_format_0=(registry.obj_name),
                         _coconut_format_1=(name)))
     self.registered[name] = value
Пример #8
0
 def _coconut_lambda_0(*_coconut_match_args,
                       **_coconut_match_kwargs):
     _coconut_match_check_0 = False
     _coconut_match_set_name_val = _coconut_sentinel
     _coconut_match_set_name_loss = _coconut_sentinel
     _coconut_FunctionMatchError = _coconut_get_function_match_error(
     )
     if _coconut.len(_coconut_match_args) == 1:
         if (_coconut.isinstance(
                 _coconut_match_args[0],
                 _coconut.abc.Sequence)) and (_coconut.len(
                     _coconut_match_args[0]) == 2):
             _coconut_match_set_name_val = _coconut_match_args[0][0]
             _coconut_match_set_name_loss = _coconut_match_args[0][
                 1]
             if not _coconut_match_kwargs:
                 _coconut_match_check_0 = True
     if _coconut_match_check_0:
         if _coconut_match_set_name_val is not _coconut_sentinel:
             val = _coconut_match_set_name_val
         if _coconut_match_set_name_loss is not _coconut_sentinel:
             loss = _coconut_match_set_name_loss
     if not _coconut_match_check_0:
         raise _coconut_FunctionMatchError(
             'best_val, min_loss = min(marginals, key=def ((val, loss)) -> loss)',
             _coconut_match_args)
     return loss
Пример #9
0
    def _load_from(self, df):
        """Load data from the given file."""
        contents = df.read()
        if contents:
            _coconut_match_to_0 = self._loads(contents)
            _coconut_match_check_2 = False
            _coconut_match_set_name_params = _coconut_sentinel
            _coconut_match_set_name_examples = _coconut_sentinel
            if _coconut.isinstance(_coconut_match_to_0, _coconut.abc.Mapping):
                _coconut_match_temp_7 = _coconut_match_to_0.get(
                    "params", _coconut_sentinel)
                _coconut_match_temp_8 = _coconut_match_to_0.get(
                    "examples", _coconut_sentinel)
                if (_coconut_match_temp_7 is not _coconut_sentinel) and (
                        _coconut_match_temp_8 is not _coconut_sentinel):
                    _coconut_match_set_name_params = _coconut_match_temp_7
                    _coconut_match_set_name_examples = _coconut_match_temp_8
                    _coconut_match_check_2 = True
            if _coconut_match_check_2:
                if _coconut_match_set_name_params is not _coconut_sentinel:
                    params = _coconut_match_set_name_params
                if _coconut_match_set_name_examples is not _coconut_sentinel:
                    examples = _coconut_match_set_name_examples
            if not _coconut_match_check_2:
                raise _coconut_MatchError(
                    '{"params": params, "examples": examples} = self._loads(contents)',
                    _coconut_match_to_0)

            self._old_params = params
            self._add_examples(examples)
Пример #10
0
def examples_to_trials(examples, params):
    """Create hyperopt trials from the given examples."""
    trials = []
    NA = object()  # used to mark missing values

    for tid, ex in enumerate(examples):

        _coconut_match_to_0 = ex
        _coconut_match_check_0 = False
        _coconut_match_set_name_gain = _coconut_sentinel
        if _coconut.isinstance(_coconut_match_to_0, _coconut.abc.Mapping):
            _coconut_match_temp_4 = _coconut_match_to_0.get("gain", _coconut_sentinel)
            if _coconut_match_temp_4 is not _coconut_sentinel:
                _coconut_match_set_name_gain = _coconut_match_temp_4
                _coconut_match_check_0 = True
        if _coconut_match_check_0:
            if _coconut_match_set_name_gain is not _coconut_sentinel:
                gain = _coconut_match_set_name_gain
        if _coconut_match_check_0:
            loss = negate_objective(gain)
        else:
            loss = ex["loss"]
        result = {"status": STATUS_OK, "loss": loss}

        vals = {}
        idxs = {}
        for k, v in get_names_and_features(ex["values"], params, fallback_func=lambda name, func, *args, **kwargs: NA, converters={"choice": lambda val, choices: choices.index(val), "randrange": lambda val, start, stop, step: val - start}, convert_fallback=False):
            vals[k] = [v,] if v is not NA else []
            idxs[k] = [tid,] if v is not NA else []

        misc = {"tid": tid, "idxs": idxs, "vals": vals, "cmd": None}

        trials.append({"tid": tid, "result": result, "misc": misc, "spec": spec_from_misc(misc), "state": JOB_STATE_DONE, "owner": None, "book_time": None, "refresh_time": None, "exp_key": None})

    return trials
Пример #11
0
 def bbopt_actor(env):
     _coconut_match_to_0 = env
     _coconut_match_check_0 = False
     if _coconut.isinstance(_coconut_match_to_0, _coconut.abc.Mapping):
         _coconut_match_temp_0 = _coconut_match_to_0.get(bb_name, _coconut_sentinel)
         if _coconut_match_temp_0 is not _coconut_sentinel:
             bb = _coconut_match_temp_0
             _coconut_match_check_0 = True
     if _coconut_match_check_0 and not (bb is not None):
         _coconut_match_check_0 = False
     if _coconut_match_check_0:
         if isinstance(util_func, Str):
             util = env[util_func]
         else:
             util = util_func(env)
         bb.maximize(util)
     else:
         bb = BlackBoxOptimizer(file=file, tag=env["game"].name + "_" + name)
         env[bb_name] = bb
     bb.run(alg=alg if not env["game"].final_step else None)
     if print_chosen_alg:
         chosen_alg = bb.get_current_run()["values"].get(meta_opt_alg_var)
         if chosen_alg is not None:
             print("\nusing BBopt alg =", chosen_alg)
     return tunable_actor(bb, env)
Пример #12
0
 def get_points_values(self, new_data, new_losses):
     """Convert data and losses into pySOT-compatible points and values."""
     points = []
     values = []
     for ex_dict, loss in zip(new_data, new_losses):
         pt = []
         for name, val in ex_dict.items():
             _coconut_match_to_1 = self.choices
             _coconut_match_check_1 = False
             _coconut_match_set_name_choices = _coconut_sentinel
             if _coconut.isinstance(_coconut_match_to_1,
                                    _coconut.abc.Mapping):
                 _coconut_match_temp_0 = _coconut_match_to_1.get(
                     name, _coconut_sentinel)
                 if _coconut_match_temp_0 is not _coconut_sentinel:
                     _coconut_match_set_name_choices = _coconut_match_temp_0
                     _coconut_match_check_1 = True
             if _coconut_match_check_1:
                 if _coconut_match_set_name_choices is not _coconut_sentinel:
                     choices = _coconut_match_temp_0
             if _coconut_match_check_1:
                 chosen_ind = choices.index(val)
                 pt.append(chosen_ind)
             else:
                 pt.append(val)
         points.append(pt)
         values.append(loss)
     return np.array(points), np.array(values)
Пример #13
0
def factorial(n, acc=1):
    """Compute n! where n is an integer >= 0."""
    def _coconut_mock_func(n, acc=1): return n, acc
    while True:
        _coconut_match_to = n
        _coconut_case_check_2 = False
        if _coconut_match_to == 0:
            _coconut_case_check_2 = True
        if _coconut_case_check_2:
            return acc
        if not _coconut_case_check_2:
            if _coconut.isinstance(_coconut_match_to, int):
                _coconut_case_check_2 = True
            if _coconut_case_check_2 and not (n > 0):
                _coconut_case_check_2 = False
            if _coconut_case_check_2:
                try:
                    _coconut_is_recursive = factorial is _coconut_recursive_func_4
                except _coconut.NameError:
                    _coconut_is_recursive = False
                if _coconut_is_recursive:
                    n, acc = _coconut_mock_func(n - 1, acc * n)
                    continue
                else:
                    return _coconut_tail_call(factorial, n - 1, acc * n)

        if not _coconut_case_check_2:
            raise TypeError("the argument to factorial must be an integer >= 0")

# Test cases:
        return None
    def sieve(*_coconut_match_to_args, **_coconut_match_to_kwargs):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to_args)
                == 1) and (_coconut.isinstance(_coconut_match_to_args[0],
                                               _coconut.abc.Iterable)):
            xs = _coconut.iter(_coconut_match_to_args[0])
            _coconut_match_temp_0 = _coconut.tuple(
                _coconut_igetitem(xs, _coconut.slice(None, 1)))
            if (_coconut.len(_coconut_match_temp_0)
                    == 1) and (not _coconut_match_to_kwargs):
                x = _coconut_match_temp_0[0]
                _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError(
                "pattern-matching failed for "
                "'def sieve([x] :: xs) = [x] :: sieve(n for n in xs if n % x)'"
                " in " + _coconut.repr(_coconut.repr(_coconut_match_to_args)))
            _coconut_match_err.pattern = 'def sieve([x] :: xs) = [x] :: sieve(n for n in xs if n % x)'
            _coconut_match_err.value = _coconut_match_to_args
            raise _coconut_match_err

        return _coconut_tail_call(
            _coconut.itertools.chain.from_iterable,
            (f()
             for f in (lambda: [x], lambda: sieve((n for n in xs if n % x)))))
Пример #15
0
def factorial(n, acc=1):
    def _coconut_mock_func(n, acc=1): return n, acc
    while True:
        """Compute n! where n is an integer >= 0."""
        _coconut_match_check = False
        _coconut_match_to = n
        if (_coconut_match_to == 0):
            _coconut_match_check = True
        if _coconut_match_check:
            return acc
        if not _coconut_match_check:
            _coconut_match_to = n
            if (_coconut.isinstance(_coconut_match_to, int)):
                if (n > 0):
                    _coconut_match_check = True
            if _coconut_match_check:
                if factorial is _coconut_recursive_func_3:
                    n, acc = _coconut_mock_func(n - 1, acc * n)
                    continue
                else:
                    raise _coconut_tail_call(factorial, n - 1, acc * n)

        if not _coconut_match_check:
            raise TypeError("the argument to factorial must be an integer >= 0")

# Test cases:
        return None
Пример #16
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    try:
        _coconut_match_check = False
        _coconut_match_to = n
        if (_coconut_match_to == 0):
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'0 = n   # destructuring assignment'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = '0 = n   # destructuring assignment'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err
# destructuring assignment
    except MatchError:
        try:
            _coconut_match_check = False
            _coconut_match_to = n
            if (_coconut.isinstance(_coconut_match_to, int)):
                _coconut_match_check = True
            if not _coconut_match_check:
                _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'_ is int = n   # also destructuring assignment'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
                _coconut_match_err.pattern = '_ is int = n   # also destructuring assignment'
                _coconut_match_err.value = _coconut_match_to
                raise _coconut_match_err
# also destructuring assignment
        except MatchError:
            pass
        else:
            if n > 0:  # in Coconut, if, match, and try are allowed after else
                return n * factorial(n - 1)
    else:
        return 1
    raise TypeError("the argument to factorial must be an integer >= 0")
Пример #17
0
 def __eq__(self, other):
     """Compare whether two vectors are equal."""
     _coconut_match_check = False
     _coconut_match_to = other
     if (_coconut.isinstance(_coconut_match_to, vector)) and (_coconut.len(_coconut_match_to) == 1) and (_coconut_match_to[0] == self.pts):
         _coconut_match_check = True
     if _coconut_match_check:
         return True
     else:
         return False
Пример #18
0
def to_json(a: 'Any') -> 'Json':  # line 8
    _coconut_match_to = a  # line 9
    _coconut_match_check = False  # line 9
    if _coconut.isinstance(_coconut_match_to, (list, tuple)):  # line 9
        a = _coconut_match_to  # line 9
        _coconut_match_check = True  # line 9
    if _coconut_match_check:  # line 9
        result = JsonArray(Lists.wrap(a) / to_json)  # line 11
    if not _coconut_match_check:  # line 12
        if _coconut.isinstance(_coconut_match_to, dict):  # line 12
            a = _coconut_match_to  # line 12
            _coconut_match_check = True  # line 12
        if _coconut_match_check:  # line 12
            result = JsonObject(Map(a).valmap(to_json))  # line 13
    if not _coconut_match_check:  # line 14
        a = _coconut_match_to  # line 14
        _coconut_match_check = True  # line 14
        if _coconut_match_check:  # line 14
            result = JsonScalar(a)  # line 15
    return result  # line 16
Пример #19
0
 def __new__(cls, *pts):
     """Create a new vector from the given pts."""
     _coconut_match_to = pts
     _coconut_match_check = False
     if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], vector)):
         v = _coconut_match_to[0]
         _coconut_match_check = True
     if _coconut_match_check:
         return v  # vector(v) where v is a vector should return v
     else:
         return _coconut_tail_call(makedata, cls, *pts)  # accesses base constructor
Пример #20
0
def quick_sort(*_coconut_match_to):
    _coconut_match_check = False
    if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to[0]) == 0):
        _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def quick_sort([]) = []'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'def quick_sort([]) = []'
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    return []
Пример #21
0
def mean(*_coconut_match_args, **_coconut_match_kwargs):
    _coconut_match_check_0 = False
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if (_coconut.len(_coconut_match_args) == 1) and (_coconut.isinstance(_coconut_match_args[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_args[0]) >= 0):
        xs = _coconut.list(_coconut_match_args[0])
        if not _coconut_match_kwargs:
            _coconut_match_check_0 = True
    if not _coconut_match_check_0:
        raise _coconut_FunctionMatchError('match def mean([] + xs) =', _coconut_match_args)

    return sum(xs) / len(xs)
Пример #22
0
 def __mul__(self, other):
     """Scalar multiplication and dot product."""
     _coconut_match_to = other
     _coconut_match_check = False
     if _coconut.isinstance(_coconut_match_to, vector):
         other_pts = _coconut_match_to[0:]
         _coconut_match_check = True
     if _coconut_match_check:
         assert len(other_pts) == len(self.pts)
         return _coconut_tail_call((sum), map(_coconut.operator.mul, self.pts, other_pts))  # dot product
     else:
         return _coconut_tail_call((vector), *map(_coconut.functools.partial(_coconut.operator.mul, other), self.pts))  # scalar multiplication
Пример #23
0
def mean(*_coconut_match_args, **_coconut_match_kwargs):
    """Compute the arithmetic mean of the given sequence."""
    _coconut_match_check_1 = False
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if (_coconut.len(_coconut_match_args) == 1) and (_coconut.isinstance(_coconut_match_args[0], _coconut.abc.Iterable)):
        xs = _coconut_match_args[0]
        if not _coconut_match_kwargs:
            _coconut_match_check_1 = True
    if not _coconut_match_check_1:
        raise _coconut_FunctionMatchError('addpattern def mean(() :: xs) =', _coconut_match_args)

    return (mean)((tuple)(xs))
Пример #24
0
 def __mul__(self, other):
     """Scalar multiplication and dot product."""
     _coconut_match_check = False
     _coconut_match_to = other
     if (_coconut.isinstance(_coconut_match_to, vector)) and (_coconut.len(_coconut_match_to) == 1):
         other_pts = _coconut_match_to[0]
         _coconut_match_check = True
     if _coconut_match_check:
         assert len(other_pts) == len(self.pts)
         raise _coconut_tail_call((sum), map(_coconut.operator.mul, self.pts, other_pts))  # dot product
     else:
         raise _coconut_tail_call((vector), *map(_coconut.functools.partial(_coconut.operator.mul, other), self.pts))  # scalar multiplication
Пример #25
0
 def _coconut_lambda_18(*_coconut_match_to):
     _coconut_match_check = False
     if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to[0]) >= 1):
         xs = _coconut.list(_coconut_match_to[0][1:])
         x = _coconut_match_to[0][0]
         _coconut_match_check = True
     if not _coconut_match_check:
         _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'assert (def ([x] + xs) -> x, xs) <| range(5) == (0, [1,2,3,4])'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
         _coconut_match_err.pattern = 'assert (def ([x] + xs) -> x, xs) <| range(5) == (0, [1,2,3,4])'
         _coconut_match_err.value = _coconut_match_to
         raise _coconut_match_err
     return x, xs
Пример #26
0
    async def async_map_4(*_coconut_match_to):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to[0]) >= 1):
            iters = _coconut.list(_coconut_match_to[0][1:])
            func = _coconut_match_to[0][0]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'match async def async_map_4([func] + iters) = parallel_map(func, *iters)'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'match async def async_map_4([func] + iters) = parallel_map(func, *iters)'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

        return parallel_map(func, *iters)
Пример #27
0
    def angle(*_coconut_match_to):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to) == 2) and (_coconut.isinstance(_coconut_match_to[1], vector)):
            self = _coconut_match_to[0]
            other = _coconut_match_to[1]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

        raise _coconut_tail_call(math.acos, self.unit() * other.unit())
Пример #28
0
def quick_sort(*_coconut_match_to_args, **_coconut_match_to_kwargs):
    _coconut_match_check = False
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if (_coconut.len(_coconut_match_to_args) == 1) and (_coconut.isinstance(_coconut_match_to_args[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to_args[0]) == 0):
        if not _coconut_match_to_kwargs:
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_val_repr = _coconut.repr(_coconut_match_to_args)
        _coconut_match_err = _coconut_FunctionMatchError("pattern-matching failed for " "'def quick_sort([]) = []'" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
        _coconut_match_err.pattern = 'def quick_sort([]) = []'
        _coconut_match_err.value = _coconut_match_to_args
        raise _coconut_match_err

    return []
Пример #29
0
def quick_sort(*_coconut_match_to):
    _coconut_match_check = False
    if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to[0]) >= 1):
        tail = _coconut.list(_coconut_match_to[0][1:])
        head = _coconut_match_to[0][0]
        _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def quick_sort([head] + tail) ='" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'def quick_sort([head] + tail) ='
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    """Sort the input sequence using the quick sort algorithm."""
    return (quick_sort([x for x in tail if x < head]) + [head] + quick_sort([x for x in tail if x >= head]))
Пример #30
0
def factorial(*_coconut_match_to):
    _coconut_match_check = False
    if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], int)):
        n = _coconut_match_to[0]
        if (n > 0):
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def factorial(n is int if n > 0) ='" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'def factorial(n is int if n > 0) ='
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    """Compute n! where n is an integer >= 0."""
    return n * factorial(n - 1)
Пример #31
0
    def __sub__(self, other):
        """Subtract one vector from another."""
        _coconut_match_check = False
        _coconut_match_to = other
        if (_coconut.isinstance(_coconut_match_to, vector)) and (_coconut.len(_coconut_match_to) == 1):
            other_pts = _coconut_match_to[0]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'vector(other_pts) = other'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'vector(other_pts) = other'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

        assert len(other_pts) == len(self.pts)
        raise _coconut_tail_call((vector), *map(_coconut_minus, self.pts, other_pts))
Пример #32
0
def quick_sort(l):
    """Sort the input iterator, using the quick sort algorithm, and without using any data until necessary."""
    _coconut_match_check = False
    _coconut_match_to = l
    if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Iterable)):
        tail = _coconut.iter(_coconut_match_to)
        _coconut_match_iter_0 = _coconut.tuple(_coconut_igetitem(tail, _coconut.slice(None, 1)))
        if (_coconut.len(_coconut_match_iter_0) == 1):
            head = _coconut_match_iter_0[0]
            _coconut_match_check = True
    if _coconut_match_check:
        tail, tail_ = tee(tail)
        _coconut_yield_from = (_coconut.itertools.chain.from_iterable((_coconut_lazy_item() for _coconut_lazy_item in (lambda: quick_sort((x for x in tail if x < head)), lambda: (head,), lambda: quick_sort((x for x in tail_ if x >= head))))))
        for _coconut_yield_item in _coconut_yield_from:
            yield _coconut_yield_item
Пример #33
0
    def test_match_error_addpattern(*_coconut_match_to_args, **_coconut_match_to_kwargs):
        _coconut_match_check = False
        _coconut_FunctionMatchError = _coconut_get_function_match_error()
        if (_coconut.len(_coconut_match_to_args) <= 1) and (_coconut.sum((_coconut.len(_coconut_match_to_args) > 0, "x" in _coconut_match_to_kwargs)) == 1):
            _coconut_match_temp_0 = _coconut_match_to_args[0] if _coconut.len(_coconut_match_to_args) > 0 else _coconut_match_to_kwargs.pop("x")
            if (_coconut.isinstance(_coconut_match_temp_0, int)) and (not _coconut_match_to_kwargs):
                x = _coconut_match_temp_0
                _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_val_repr = _coconut.repr(_coconut_match_to_args)
            _coconut_match_err = _coconut_FunctionMatchError("pattern-matching failed for " "'def test_match_error_addpattern(x is int): raise MatchError()'" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
            _coconut_match_err.pattern = 'def test_match_error_addpattern(x is int): raise MatchError()'
            _coconut_match_err.value = _coconut_match_to_args
            raise _coconut_match_err

        raise MatchError()
Пример #34
0
 def __getitem__(self, name):
     name = self.aliases.get(name, name)
     _coconut_match_to = self.registered
     _coconut_match_check = False
     if _coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping):
         _coconut_match_temp_0 = _coconut_match_to.get(name, _coconut_sentinel)
         if _coconut_match_temp_0 is not _coconut_sentinel:
             value = _coconut_match_temp_0
             _coconut_match_check = True
     if _coconut_match_check:
         return self.registered[name]
     else:
         if name in self.generators:
             return self.run_gen(name)
         else:
             valid_names = ", ".join((repr(name) for name in self))
             raise ValueError("unknown {_coconut_format_0}: {_coconut_format_1} (valid {_coconut_format_2}s: {_coconut_format_3})".format(_coconut_format_0=(self.obj_name), _coconut_format_1=(name), _coconut_format_2=(self.obj_name), _coconut_format_3=(valid_names)))
Пример #35
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_to = n
    _coconut_case_check_3 = False
    if _coconut_match_to == 0:
        _coconut_case_check_3 = True
    if _coconut_case_check_3:
        return 1
    if not _coconut_case_check_3:
        if _coconut.isinstance(_coconut_match_to, int):
            _coconut_case_check_3 = True
        if _coconut_case_check_3 and not (n > 0):
            _coconut_case_check_3 = False
        if _coconut_case_check_3:
            return _coconut_tail_call(reduce, _coconut.operator.mul, range(1, n + 1))
    if not _coconut_case_check_3:
        raise TypeError("the argument to factorial must be an integer >= 0")
Пример #36
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_to = n
    _coconut_case_check_1 = False
    if _coconut_match_to == 0:
        _coconut_case_check_1 = True
    if _coconut_case_check_1:
        return 1
    if not _coconut_case_check_1:
        if _coconut.isinstance(_coconut_match_to, int):
            _coconut_case_check_1 = True
        if _coconut_case_check_1 and not (n > 0):
            _coconut_case_check_1 = False
        if _coconut_case_check_1:
            return n * factorial(n - 1)
    if not _coconut_case_check_1:
        raise TypeError("the argument to factorial must be an integer >= 0")
Пример #37
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_check = False
    _coconut_match_to = n
    if (_coconut_match_to == 0):
        _coconut_match_check = True
    if _coconut_match_check:
        return 1
    if not _coconut_match_check:
        _coconut_match_to = n
        if (_coconut.isinstance(_coconut_match_to, int)):
            if (n > 0):
                _coconut_match_check = True
        if _coconut_match_check:
            raise _coconut_tail_call(reduce, _coconut.operator.mul, range(1, n + 1))
    if not _coconut_match_check:
        raise TypeError("the argument to factorial must be an integer >= 0")
Пример #38
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_check = False
    _coconut_match_to = n
    if (_coconut_match_to == 0):
        _coconut_match_check = True
    if _coconut_match_check:
        return 1
    if not _coconut_match_check:
        _coconut_match_to = n
        if (_coconut.isinstance(_coconut_match_to, int)):
            if (n > 0):
                _coconut_match_check = True
        if _coconut_match_check:
            return n * factorial(n - 1)
    if not _coconut_match_check:
        raise TypeError("the argument to factorial must be an integer >= 0")
Пример #39
0
def mean(*_coconut_match_args, **_coconut_match_kwargs):
    _coconut_match_check_0 = False
    _coconut_match_set_name_xs = _coconut_sentinel
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if _coconut.len(_coconut_match_args) == 1:
        if _coconut.isinstance(_coconut_match_args[0], _coconut.abc.Sequence):
            _coconut_match_temp_4 = _coconut.list(_coconut_match_args[0])
            _coconut_match_set_name_xs = _coconut_match_temp_4
            if not _coconut_match_kwargs:
                _coconut_match_check_0 = True
    if _coconut_match_check_0:
        if _coconut_match_set_name_xs is not _coconut_sentinel:
            xs = _coconut_match_set_name_xs
    if not _coconut_match_check_0:
        raise _coconut_FunctionMatchError('match def mean([] + xs) =',
                                          _coconut_match_args)

    return sum(xs) / len(xs)
Пример #40
0
    def _load_from(self, df):
        """Load data from the given file."""
        contents = df.read()
        if contents:
            _coconut_match_to = self._loads(contents)
            _coconut_match_check = False
            if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping)) and (_coconut.len(_coconut_match_to) == 2):
                _coconut_match_temp_0 = _coconut_match_to.get("params", _coconut_sentinel)
                _coconut_match_temp_1 = _coconut_match_to.get("examples", _coconut_sentinel)
                if (_coconut_match_temp_0 is not _coconut_sentinel) and (_coconut_match_temp_1 is not _coconut_sentinel):
                    params = _coconut_match_temp_0
                    examples = _coconut_match_temp_1
                    _coconut_match_check = True
            if not _coconut_match_check:
                raise _coconut_MatchError('{"params": params, "examples": examples} = self._loads(contents)', _coconut_match_to)

            self._old_params = params
            self._add_examples(examples)
Пример #41
0
    def angle(*_coconut_match_to_args, **_coconut_match_to_kwargs):
        _coconut_match_check = False
        _coconut_FunctionMatchError = _coconut_get_function_match_error()
        if (_coconut.len(_coconut_match_to_args) <= 2) and (_coconut.sum((_coconut.len(_coconut_match_to_args) > 0, "self" in _coconut_match_to_kwargs)) == 1) and (_coconut.sum((_coconut.len(_coconut_match_to_args) > 1, "other" in _coconut_match_to_kwargs)) == 1):
            _coconut_match_temp_0 = _coconut_match_to_args[0] if _coconut.len(_coconut_match_to_args) > 0 else _coconut_match_to_kwargs.pop("self")
            _coconut_match_temp_1 = _coconut_match_to_args[1] if _coconut.len(_coconut_match_to_args) > 1 else _coconut_match_to_kwargs.pop("other")
            if (_coconut.isinstance(_coconut_match_temp_1, vector)) and (not _coconut_match_to_kwargs):
                self = _coconut_match_temp_0
                other = _coconut_match_temp_1
                _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_val_repr = _coconut.repr(_coconut_match_to_args)
            _coconut_match_err = _coconut_FunctionMatchError("pattern-matching failed for " "'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
            _coconut_match_err.pattern = 'def angle(self, other is vector) = math.acos(self.unit() * other.unit())'
            _coconut_match_err.value = _coconut_match_to_args
            raise _coconut_match_err

        return _coconut_tail_call(math.acos, self.unit() * other.unit())
Пример #42
0
def factorial(*_coconut_match_to_args, **_coconut_match_to_kwargs):
    """Compute n! where n is an integer >= 0."""
    _coconut_match_check = False
    _coconut_FunctionMatchError = _coconut_get_function_match_error()
    if (_coconut.len(_coconut_match_to_args) <= 1) and (_coconut.sum((_coconut.len(_coconut_match_to_args) > 0, "n" in _coconut_match_to_kwargs)) == 1):
        _coconut_match_temp_0 = _coconut_match_to_args[0] if _coconut.len(_coconut_match_to_args) > 0 else _coconut_match_to_kwargs.pop("n")
        if (_coconut.isinstance(_coconut_match_temp_0, int)) and (not _coconut_match_to_kwargs):
            n = _coconut_match_temp_0
            _coconut_match_check = True
    if _coconut_match_check and not (n > 0):
        _coconut_match_check = False
    if not _coconut_match_check:
        _coconut_match_val_repr = _coconut.repr(_coconut_match_to_args)
        _coconut_match_err = _coconut_FunctionMatchError("pattern-matching failed for " "'def factorial(n is int if n > 0) ='" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
        _coconut_match_err.pattern = 'def factorial(n is int if n > 0) ='
        _coconut_match_err.value = _coconut_match_to_args
        raise _coconut_match_err

    return n * factorial(n - 1)
Пример #43
0
def factorial(n):
    """Compute n! where n is an integer >= 0."""
    try:
# The only value that can be assigned to 0 is 0, since 0 is an
# immutable constant; thus, this assignment fails if n is not 0.
        _coconut_match_to = n
        _coconut_match_check = False
        if _coconut_match_to == 0:
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_val_repr = _coconut.repr(_coconut_match_to)
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'0 = n'" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
            _coconut_match_err.pattern = '0 = n'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

    except MatchError:
        pass
    else:
        return 1
    try:
# This attempts to assign n to x, which has been declared to be
# an int; since only an int can be assigned to an int, this
# fails if n is not an int.
        _coconut_match_to = n
        _coconut_match_check = False
        if _coconut.isinstance(_coconut_match_to, int):
            x = _coconut_match_to
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_val_repr = _coconut.repr(_coconut_match_to)
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'x is int = n'" " in " + (_coconut_match_val_repr if _coconut.len(_coconut_match_val_repr) <= 500 else _coconut_match_val_repr[:500] + "..."))
            _coconut_match_err.pattern = 'x is int = n'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err

    except MatchError:
        pass
    else:  # in Coconut, statements can be nested on the same line
        if x > 0:  # in Coconut, statements can be nested on the same line
            return x * factorial(x - 1)
    raise TypeError("the argument to factorial must be an integer >= 0")
Пример #44
0
 def substitute_elements(self, subs, **kwargs):
     if not can_sub(kwargs):
         return self
     _coconut_match_to_1 = subs
     _coconut_match_check_1 = False
     if _coconut.isinstance(_coconut_match_to_1, _coconut.abc.Mapping):
         _coconut_match_temp_0 = _coconut_match_to_1.get(self.proposition(), _coconut_sentinel)
         if _coconut_match_temp_0 is not _coconut_sentinel:
             sub = _coconut_match_temp_0
             _coconut_match_check_1 = True
     if _coconut_match_check_1:
         assert isinstance(sub, Atom), sub
         do_sub(kwargs)
         name = sub.name
     else:
         name = self.name
     if can_sub(kwargs):
         return (Pred)(name, *(map)(_coconut.operator.methodcaller("substitute", subs, **kwargs), self.args))
     else:
         return _coconut_tail_call(Pred, name, *self.args)
Пример #45
0
def main_test():
    """Basic no-dependency tests."""
    assert "\n" == ('''
''') == """
"""
    assert _coconut
    assert "_coconut" in globals()
    assert "_coconut" not in locals()
    x = 5
    assert x == 5
    x == 6
    assert x == 5
    assert r"hello, world" == "hello, world" == "hello," " " "world"
    assert "\n " == """
 """
    assert "\\" "\"" == "\\\""
    assert """

""" == "\n\n"
    assert {"a": 5}["a"] == 5
    a, = [24]
    assert a == 24
    assert set((1, 2, 3)) == _coconut.set((1, 2, 3))
    olist = [0, 1, 2]
    olist[1] += 4
    assert olist == [0, 5, 2]
    assert +5e+5 == +5 * +10**+5
    assert repr(3) == "3" == ascii(3)
    assert _coconut.operator.mul(2, _coconut_minus(2, 5)) == -6
    assert (list)(map(_coconut.functools.partial(pow, 2), (range)(0, 5))) == [1, 2, 4, 8, 16]
    iter1 = range(0, 10)
    iter1, iter2 = tee(iter1)
    assert (list)(_coconut_igetitem(iter1, _coconut.slice(2, 8))) == (list)(_coconut_igetitem(iter2, _coconut.slice(2, 8)))
    data = 5
    assert data == 5
    data = 3
    assert data == 3
    def backslash_test():
        return lambda x: x
    assert 1 == 1 == backslash_test()(1)
    assert (
            "hello"
         == "hello" == 
            'hello'
        )
    def multiline_backslash_test(
                                   x,
                                   y):
        return x + y
    assert multiline_backslash_test(1, 2) == 3
    assert True
    class one_line_class(_coconut.object):
        pass
    assert isinstance(one_line_class(), one_line_class)
    assert ((_coconut.operator.attrgetter("join"))(""))(["1", "2", "3"]) == "123" == ((_coconut.functools.partial(_coconut.getattr, ""))("join"))(["1", "2", "3"])
    assert (_coconut.functools.partial(_coconut.operator.getitem, [1, 2, 3]))(1) == 2 == (_coconut.functools.partial(_coconut_igetitem, [1, 2, 3]))(1)
    assert (_coconut.functools.partial(_coconut.operator.getitem, "123"))(1) == "2" == (_coconut.functools.partial(_coconut_igetitem, "123"))(1)
    assert (list)(_coconut.itertools.chain.from_iterable((_coconut_lazy_item() for _coconut_lazy_item in (lambda: (_coconut_lazy_item() for _coconut_lazy_item in (lambda: -1, lambda: 0)), lambda: range(1, 5))))) == [-1, 0, 1, 2, 3, 4]
    assert (list)(_coconut.itertools.chain.from_iterable((_coconut_lazy_item() for _coconut_lazy_item in (lambda: (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1,)), lambda: (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 2,)))))) == [1, 2]
    assert not isinstance(map(_coconut.functools.partial(_coconut.operator.add, 2), [1, 2, 3]), list)
    assert not isinstance(range(10), list)
    assert isinstance(10**100, int)
    assert chr(1000)
    assert (abs)(3 + 4j) == 5
    assert 3.14j == 3.14j
    assert 10.j == 10.j
    assert 10j == 10j
    assert .001j == .001j
    assert 1e100j == 1e100j
    assert 3.14e-10j == 3.14e-10j
    _coconut_match_check = False
    _coconut_match_to = {"text": "abc", "tags": [1, 2, 3]}
    if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Mapping)) and (_coconut.len(_coconut_match_to) == 2) and ("text" in _coconut_match_to) and ("tags" in _coconut_match_to) and (_coconut.isinstance(_coconut_match_to["tags"], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to["tags"]) >= 1):
        text = _coconut_match_to["text"]
        rest = _coconut.list(_coconut_match_to["tags"][1:])
        first = _coconut_match_to["tags"][0]
        _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " '\'{"text": text, "tags": [first] + rest} = {"text": "abc", "tags": [1, 2, 3]}\'' " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = '{"text": text, "tags": [first] + rest} = {"text": "abc", "tags": [1, 2, 3]}'
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    assert text == "abc"
    assert first == 1
    assert rest == [2, 3]
    assert isinstance("a", str)
    assert isinstance(b"a", bytes)
    global glob_a, glob_b
    glob_a, glob_b = 0, 0
    assert glob_a == 0 == glob_b
    def set_globs(x):
        global glob_a, glob_b
        glob_a, glob_b = x, x
    set_globs(2)
    assert glob_a == 2 == glob_b
    def set_globs_again(x):
        global glob_a, glob_b
        glob_a, glob_b = (x, x)
    set_globs_again(10)
    assert glob_a == 10 == glob_b
    assert _coconut_minus(1) == -1 == _coconut.functools.partial(_coconut_minus, 1)(2)
    assert (_coconut.operator.le)(3, 3)
    assert (list)((consume)(range(10))) == []
    assert (list)(consume(range(10), keep_last=2)) == [8, 9]
    i = int()
    try:
        i.x = 12
    except AttributeError as err:
        assert err
    else:
        assert False
    r = range(10)
    try:
        r.x = 12
    except AttributeError as err:
        assert err
    else:
        assert False
    if _coconut_sys.version_info < (3,):
        import Queue as q
    else:
        import queue as q
    if _coconut_sys.version_info < (3,):
        import __builtin__ as builtins
    else:
        import builtins
    if _coconut_sys.version_info < (3,):
        import email.MIMEBase as _coconut_import
        try:
            email
        except:
            email = _coconut.imp.new_module("email")
        else:
            if not _coconut.isinstance(email, _coconut.types.ModuleType):
                email = _coconut.imp.new_module("email")
        try:
            email.mime
        except:
            email.mime = _coconut.imp.new_module("email.mime")
        else:
            if not _coconut.isinstance(email.mime, _coconut.types.ModuleType):
                email.mime = _coconut.imp.new_module("email.mime")
        email.mime.base = _coconut_import
    else:
        import email.mime.base
    assert q.Queue
    assert builtins.len([1, 1]) == 2
    assert email.mime.base
    if _coconut_sys.version_info < (3,):
        import email.MIMEBase as mimebase
    else:
        from email.mime import base as mimebase
    assert mimebase
    from_err = TypeError()
    try:
        _coconut_raise_from = ValueError()
        _coconut_raise_from.__cause__ = from_err
        raise _coconut_raise_from
    except ValueError as err:
        assert err.__cause__ is from_err
    else:
        assert False
    class doc(_coconut.collections.namedtuple("doc", "")):
        "doc"
        __slots__ = ()
    class doc_(_coconut.collections.namedtuple("doc_", "")):
        """doc"""
        __slots__ = ()
    assert doc.__doc__ == "doc" == doc_.__doc__
    assert 10000000.0 == 10000000.0
    assert (tuple)(_coconut.iter(())) == ()
    import collections
    if _coconut_sys.version_info < (3, 3):
        import collections as _coconut_import
        try:
            collections
        except:
            collections = _coconut.imp.new_module("collections")
        else:
            if not _coconut.isinstance(collections, _coconut.types.ModuleType):
                collections = _coconut.imp.new_module("collections")
        collections.abc = _coconut_import
    else:
        import collections.abc
    assert isinstance([], collections.abc.Sequence)
    assert isinstance(range(1), collections.abc.Sequence)
    assert collections.defaultdict(int)[5] == 0
    assert len(range(10)) == 10
    assert (tuple)((reversed)(range(4))) == (3, 2, 1, 0)
    assert (tuple)(range(5)[1:]) == (1, 2, 3, 4) == (tuple)(_coconut_igetitem(range(5), _coconut.slice(1, None)))
    assert (tuple)(range(10)[-3:-1]) == (7, 8) == (tuple)(_coconut_igetitem(range(10), _coconut.slice(-3, -1)))
    assert (tuple)(_coconut_igetitem(map(abs, (1, -2, -5, 2)), _coconut.slice(None, None))) == (1, 2, 5, 2)
    assert _coconut_igetitem((_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1, lambda: 2)), -1) == 2
    assert (tuple)(_coconut_igetitem((_coconut_lazy_item() for _coconut_lazy_item in (lambda: 0, lambda: 1, lambda: 2, lambda: 3)), _coconut.slice(-2, None))) == (2, 3)
    assert (tuple)(_coconut_igetitem((_coconut_lazy_item() for _coconut_lazy_item in (lambda: 0, lambda: 1, lambda: 2, lambda: 3)), _coconut.slice(None, -2))) == (0, 1)
    assert _coconut_igetitem(map(_coconut.operator.add, (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 10, lambda: 20)), (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1, lambda: 2))), -1) == 22 == map(_coconut.operator.add, (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 10, lambda: 20)), (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1, lambda: 2)))[-1]
    assert _coconut_igetitem(map(lambda x: x + 1, range(10**9)), -1) == 10**9 == _coconut_igetitem(count(), 10**9)
    assert (tuple)(_coconut_igetitem(count(), _coconut.slice(10, 15))) == (10, 11, 12, 13, 14) == (tuple)(count()[10:15])
    assert (tuple)(zip((1, 2), (3, 4))) == ((1, 3), (2, 4)) == (tuple)(_coconut_igetitem(zip((1, 2), (3, 4)), _coconut.slice(None, None)))
    assert (tuple)(_coconut_igetitem(zip((_coconut_lazy_item() for _coconut_lazy_item in (lambda: 10, lambda: 20)), (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1, lambda: 2))), -1)) == (20, 2) == (tuple)(zip((_coconut_lazy_item() for _coconut_lazy_item in (lambda: 10, lambda: 20)), (_coconut_lazy_item() for _coconut_lazy_item in (lambda: 1, lambda: 2)))[-1])
    assert (tuple)(_coconut_igetitem(zip(count(), count()), 10**9)) == (10**9, 10**9) == (tuple)(zip(count(), count())[10**9])
    assert _coconut_igetitem(count(1.5, 0.5), 0) == 1.5 == _coconut_igetitem((1.5, 2, 2.5, 3), 0)
    assert (tuple)(_coconut_igetitem(count(1.5, 0.5), _coconut.slice(1, 3))) == (2, 2.5) == (tuple)(_coconut_igetitem((1.5, 2, 2.5, 3), _coconut.slice(1, 3)))
    assert (tuple)(_coconut_igetitem(iter((0, 1, 2, 3, 4)), _coconut.slice(None, None, 2))) == (0, 2, 4)
    assert (tuple)(_coconut_igetitem(iter((0, 1, 2, 3, 4)), _coconut.slice(None, None, -1))) == (4, 3, 2, 1, 0)
    assert dict(((x), (x)) for x in range(5)) == {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
    _coconut_match_check = False
    _coconut_match_to = 12
    x = _coconut_match_to
    _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'match x = 12'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'match x = 12'
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    assert x == 12
    get_int = lambda: int
    _coconut_match_check = False
    _coconut_match_to = 5
    if (_coconut.isinstance(_coconut_match_to, get_int())):
        x = _coconut_match_to
        _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'x is get_int() = 5'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'x is get_int() = 5'
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    assert x == 5
    class a(get_int()):
        pass
    assert isinstance(a(), int)
    assert (len)(map(_coconut.operator.add, range(5), range(6))) == 5 == (len)(zip(range(5), range(6)))
    assert map(_coconut_minus, range(5))._func(3) == -3
    assert (tuple)(map(_coconut_minus, range(5))._iters[0]) == (tuple)(range(5)) == (tuple)(zip(range(5), range(6))._iters[0])
    assert repr(zip((0, 1), (1, 2))) == "zip((0, 1), (1, 2))"
    assert repr(map(_coconut_minus, range(5))).startswith("map(")
    assert repr(parallel_map(_coconut_minus, range(5))).startswith("parallel_map(")
    assert (tuple)(parallel_map(_coconut_minus, range(5))) == (0, -1, -2, -3, -4) == (tuple)(_coconut_igetitem(parallel_map(_coconut.functools.partial(map, _coconut_minus), (range(5),)), 0))
    assert (tuple)(map(tuple, parallel_map(zip, (range(2),), (range(2),)))) == (((0, 0), (1, 1)),)
    assert (tuple)(map(_coconut.operator.add, *(range(0, 5), range(5, 10)))) == (5, 7, 9, 11, 13)
    assert (tuple)(parallel_map(_coconut_compose(_coconut.functools.partial(_coconut.operator.mul, 2), _coconut.functools.partial(_coconut.operator.add, 1)), range(5))) == (2, 4, 6, 8, 10)
    assert repr(concurrent_map(_coconut_minus, range(5))).startswith("concurrent_map(")
    assert (tuple)(concurrent_map(_coconut_minus, range(5))) == (0, -1, -2, -3, -4) == (tuple)(_coconut_igetitem(concurrent_map(_coconut.functools.partial(map, _coconut_minus), (range(5),)), 0))
    assert (tuple)(map(tuple, concurrent_map(zip, (range(2),), (range(2),)))) == (((0, 0), (1, 1)),)
    assert (tuple)(map(_coconut.operator.add, *(range(0, 5), range(5, 10)))) == (5, 7, 9, 11, 13)
    assert (tuple)(concurrent_map(_coconut_compose(_coconut.functools.partial(_coconut.operator.mul, 2), _coconut.functools.partial(_coconut.operator.add, 1)), range(5))) == (2, 4, 6, 8, 10)
    assert 0 in range(1)
    assert range(1).count(0) == 1
    assert 2 in range(5)
    assert range(5).count(2) == 1
    assert 10 not in range(3)
    assert range(3).count(10) == 0
    assert 1 in range(1, 2, 3)
    assert range(1, 2, 3).count(1) == 1
    assert range(1, 2, 3).index(1) == 0
    assert range(1, 2, 3)[0] == 1
    assert range(1, 5, 3).index(4) == 1
    assert range(1, 5, 3)[1] == 4
    try:
        range(1, 2, 3).index(2)
    except ValueError as err:
        assert err
    else:
        assert False
    assert 0 in count()
    assert count().count(0) == 1
    assert -1 not in count()
    assert count().count(-1) == 0
    assert 1 not in count(5)
    assert count(5).count(1) == 0
    assert 2 not in count(1, 2)
    assert count(1, 2).count(2) == 0
    try:
        count(1, 2).index(2)
    except ValueError as err:
        assert err
    else:
        assert False
    assert count(1, 3).index(1) == 0
    assert count(1, 3)[0] == 1
    assert count(1, 3).index(4) == 1
    assert count(1, 3)[1] == 4
    assert (len)(map(lambda x: x, [1, 2])) == 2
    assert repr("hello") == "'hello'" == ascii("hello")
    assert (_coconut.operator.methodcaller("index", 1))(count(1, 3)) == 0
    assert _coconut_igetitem(count(1).__copy__(), 0) == 1
    assert _coconut_igetitem(map(_coconut.operator.add, count(1), count(1)).__copy__(), 0) == 2
    assert (tuple)(_coconut_igetitem(zip(count(1), count(1)).__copy__(), 0)) == (1, 1)
    assert (all)(map(lambda t: isinstance(t, count), tee(count())))
    assert (all)(map(lambda t: isinstance(t, range), tee(range(10))))
    assert (all)(map(lambda t: isinstance(t, list), tee([1, 2, 3])))
    assert (lambda _=None: 5)() == 5
    assert (lambda _=None: _[0])([1, 2, 3]) == 1
    assert (list)(_coconut_igetitem(iter(range(10)), _coconut.slice(-5, -8))) == [5, 6]
    assert (list)(_coconut_igetitem(iter(range(10)), _coconut.slice(-2, None))) == [8, 9]
    assert (_coconut.operator.itemgetter(1))(range(1, 5)) == 2 == (_coconut.functools.partial(_coconut_igetitem, index=1))(range(1, 5))
    assert (list)((_coconut.operator.itemgetter(_coconut.slice(None, 5)))(range(10))) == [0, 1, 2, 3, 4] == (list)((_coconut.functools.partial(_coconut_igetitem, index=_coconut.slice(None, 5)))(range(10)))
    def _coconut_lambda_0(x):
        y = x
    assert (list)(map(_coconut_lambda_0, range(10))) == [None] * 10
    def _coconut_lambda_1(x):
        yield x
    assert (list)(map(list, map(_coconut_lambda_1, range(5)))) == [[0], [1], [2], [3], [4]]
    def do_stuff(x):
        return True
    def _coconut_lambda_2(x=3):
        return do_stuff(x)
    assert (_coconut_lambda_2)() is True
    def _coconut_lambda_3(x=4):
        do_stuff(x)
        return x
    assert (_coconut_lambda_3)() == 4
    def _coconut_lambda_4(x=5):
        do_stuff(x)
    assert (_coconut_lambda_4)() is None
    def _coconut_lambda_5(x=6):
        do_stuff(x)
        assert x
    (_coconut_lambda_5)()
    def _coconut_lambda_6(x=7):
        do_stuff(x)
        assert x
        yield x
    assert (list)((_coconut_lambda_6)()) == [7]
    def _coconut_lambda_7(_=None):
        do_stuff(_)
        assert _
        return _
    assert (_coconut_lambda_7)(8) == 8
    def _coconut_lambda_8(x=9):
        return x
    assert (_coconut_lambda_8)() == 9
    def _coconut_lambda_9(x=10):
        do_stuff(x)
        return x
    assert (_coconut_lambda_9)() == 10
    def _coconut_lambda_12(_=None):
        def _coconut_lambda_11(_=None):
            return 11
        return _coconut_lambda_11
    assert (_coconut_lambda_12)()() == 11
    def _coconut_lambda_13(_=None):
        return 12
    def _coconut_lambda_14(_=None):
        return 12
    assert (_coconut_lambda_13)() == 12 == (_coconut_lambda_14)()
    def _coconut_lambda_15(x):
        return lambda _=None: x
    assert (list)(map(lambda _=None: _(), ((_coconut_lambda_15)(x) for x in range(5)))) == [0, 1, 2, 3, 4]
    herpaderp = 5
    def derp():
        herp = 10
        def _coconut_lambda_16(_=None):
            return herpaderp + herp
        return (_coconut_lambda_16)
    assert derp()() == 15
    class abc(_coconut.collections.namedtuple("abc", "xyz")):
        __slots__ = ()
    assert abc(10).xyz == 10
    class aclass(_coconut.object): pass
    assert isinstance(aclass, object)
    assert (_coconut.operator.is_)(*tee((1, 2)))
    assert (_coconut.operator.is_)(*tee(_coconut.frozenset((1, 2))))
    assert (lambda x: 2 / x)(4) == 1 / 2
    _coconut_match_check = False
    _coconut_match_to = range(10)
    if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Iterable)):
        _coconut_match_iter_0 = _coconut.list(_coconut_match_to)
        if (_coconut.len(_coconut_match_iter_0) >= 2):
            b = _coconut_match_iter_0[1:-1]
            a = _coconut_match_iter_0[0]
            c = _coconut_match_iter_0[-1]
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'match [a, *b, c] = range(10)'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
        _coconut_match_err.pattern = 'match [a, *b, c] = range(10)'
        _coconut_match_err.value = _coconut_match_to
        raise _coconut_match_err

    assert a == 0
    assert b == [1, 2, 3, 4, 5, 6, 7, 8]
    assert c == 9
    _coconut_match_check = False
    _coconut_match_to = range(10)
    if (_coconut.isinstance(_coconut_match_to, _coconut.abc.Iterable)):
        _coconut_match_iter_0 = _coconut.list(_coconut_match_to)
        if (_coconut.len(_coconut_match_iter_0) >= 2) and (_coconut_match_iter_0[0] == _coconut_match_iter_0[-1]):
            b = _coconut_match_iter_0[1:-1]
            a = _coconut_match_iter_0[0]
            _coconut_match_check = True
    if _coconut_match_check:
        assert False
    else:
        assert True
    a = 1
    b = 1
    assert a == 1 == b
    assert count(5) == count(5)
    assert count(5) != count(3)
    assert {count(5): True}[count(5)]
    def _coconut_lambda_17(x):
        return x
    assert (_coconut_lambda_17)(1) == 1
    def _coconut_lambda_18(*_coconut_match_to):
        _coconut_match_check = False
        if (_coconut.len(_coconut_match_to) == 1) and (_coconut.isinstance(_coconut_match_to[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to[0]) >= 1):
            xs = _coconut.list(_coconut_match_to[0][1:])
            x = _coconut_match_to[0][0]
            _coconut_match_check = True
        if not _coconut_match_check:
            _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'assert (def ([x] + xs) -> x, xs) <| range(5) == (0, [1,2,3,4])'" " in " + _coconut.repr(_coconut.repr(_coconut_match_to)))
            _coconut_match_err.pattern = 'assert (def ([x] + xs) -> x, xs) <| range(5) == (0, [1,2,3,4])'
            _coconut_match_err.value = _coconut_match_to
            raise _coconut_match_err
        return x, xs
    assert ((_coconut_lambda_18))(range(5)) == (0, [1, 2, 3, 4])
    s = "hello"  # type: str
    assert s == "hello"
    return True