예제 #1
0
파일: io_spec.py 프로젝트: yuhangwang/amino
 def flat_map_thrice(self) -> None:
     v = 13
     w = 29
     x = 17
     y = 11
     t = (IO.now(v).flat_map(L(IO.now)(_ + w)).flat_map(L(
         IO.now)(_ + x)).flat_map(L(IO.now)(_ + y)))
     t.attempt.should.contain(v + w + x + y)
예제 #2
0
 def _process_results(self, monitor, results: SearchResults):
     ''' returns True if a result was found to stop the find() in
     *_clean_done*
     '''
     return (
         results.choose(monitor)
         .map(L(self._add_link)(results.query, _))
         .replace(True)
         .get_or_else(L(self._no_result)(results))
     )
예제 #3
0
파일: main.py 프로젝트: tek/chiasma-py
def window_state(ui_window: Ident, twindow: Window, layout: ViewTree) -> Do:
    window_id = yield TS.from_maybe(twindow.id, 'window_state: `{twindow}` has no id')
    native_window_e = yield TS.lift(window(window_id))
    native_window = yield TS.from_either(native_window_e)
    panes = yield TS.lift(window_panes(window_id))
    native_pane, tail = yield TS.from_maybe(panes.detach_head, 'no panes in window')
    reference_pane = yield pane_by_id(native_pane.id)
    state = (
        reference_pane
        .map(L(TrackedWindow)(native_window, ui_window, layout, native_pane, _)) |
        L(PristineWindow)(native_window, ui_window, layout, native_pane)
    )
    yield TS.pure(state)
예제 #4
0
def object_from_module(mod: ModuleType, pred: Callable[[Any], bool],
                       desc: str) -> Do:
    all = yield Maybe.getattr(mod, '__all__').to_either(
        f'module `{mod.__name__}` does not define `__all__`')
    yield (Lists.wrap(all).flat_map(L(Maybe.getattr)(
        mod,
        _)).find(pred).to_either(f'no {desc} in `{mod.__name__}.__all__`'))
예제 #5
0
 def search(self, monitor):
     return (
         LazyList(self._queries(monitor))
         .filter(_.valid)
         .apzip(self._safe_search)
         .map2(L(SearchResults)(_, _, self.min_seeders, self.max_size))
     )
예제 #6
0
 def flat_map_delay(self) -> None:
     v = 13
     w = 29
     x = 17
     f = _ + x
     t = IO.delay(f, v).flat_map(L(IO.now)(_ + w))
     t.attempt.should.contain(v + w + x)
예제 #7
0
파일: tree.py 프로젝트: yangyang202/DA_GP9
    def lift(self, key: Key) -> 'SubTree':
        def err() -> 'SubTree':
            keys = ', '.join(self.data.keys())
            return SubTreeInvalid(
                key, f'MapNode({self.rule}) invalid key ({keys})')

        return (self.data.lift(key) / L(SubTree.cons)(_, key) | err)
예제 #8
0
파일: tree.py 프로젝트: yangyang202/DA_GP9
def _path_lens(a: A, sub: Callable[[A], List[A]],
               f: Callable[[A], Maybe[UnboundLens]]) -> Maybe[UnboundLens]:
    def go_sub():
        l, s = sub(lens), sub(a)
        g = lambda b: _path_lens(b, sub, f)
        return _path_lens_list(s, g) / _add(l).cons(lens)

    return (f(a) / L(List)(lens, _)).or_else(go_sub)
예제 #9
0
파일: main.py 프로젝트: tek/chiasma-py
 def layout_node(self, node: MeasuredLayoutNode, reference: P) -> Do:
     vertical = node.data.view.vertical
     layout_reference = yield reference_pane(node)
     new_reference = layout_reference | reference
     yield node.sub.traverse(position_view(vertical, new_reference), TS)
     yield node.sub.traverse(L(self)(_, new_reference), TS)
     yield node.sub.traverse(resize_view(vertical, new_reference.ident), TS)
     yield TS.unit
예제 #10
0
 def choose(self, monitor):
     available = (
         self.results.filter(lambda a: a.seeders is not None).filter(
             _.seeders >= self.min_seeders))
     matching = (available.filter(
         L(match_title)(monitor, _.title, self.query.res)).filter(
             _.magnet_link).filter_not(
                 lambda a: monitor.contains_torrent(a.magnet_link)))
     return (matching.filter(_.size < self.max_bytes).head.o(matching.head))
예제 #11
0
 def handle_show(show):
     season = List.wrap(self.tvdb.season(show.etvdb_id, num))
     if season:
         now = datetime.now().strftime('%F')
         aired = (season.filter(_['date'] < now).map(_['episode']).max)
         aired % L(self._releases.add_season)(
             show.canonical_name, num, _, search_name=show.search_name)
         return 'Done'
     else:
         return 'No such season: {} s{}'.format(show, num)
예제 #12
0
파일: io.py 프로젝트: tangleibest/untitled
    def location(self):
        files = List('io', 'anon', 'instances/io', 'tc/base')

        def filt(entry, name):
            return entry.filename.endswith('/amino/{}.py'.format(name))

        stack = self.stack.filter_not(lambda a: files.exists(L(filt)(a, _)))
        pred = (lambda a: not IOException.remove_pkgs.exists(
            lambda b: '/{}/'.format(b) in a.filename))
        return stack.find(pred)
예제 #13
0
파일: io.py 프로젝트: GitHub-Notables/amino
 def truncated_trace_lines(self) -> List[str]:
     try:
         tb = Lists.wrap(traceback.walk_tb(self.cause.__traceback__)) / _[0]
         error_loc = (tb.filter(
             L(non_internal_frame)(_,
                                   self._internal_packages_arg)).flat_map(
                                       frame_traceback_entry))
         return self.trace_lines_with((error_loc) +
                                      format_exception_error(self.cause))
     except Exception as e:
         return self.trace_error()
예제 #14
0
파일: io_spec.py 프로젝트: yuhangwang/amino
    def location(self) -> None:
        IO.debug = True
        IOException.remove_pkgs = List('fn')

        def fail(a: int) -> None:
            raise Exception(str(a))

        f = lambda a: a + 2
        g = lambda a, b: IO.now(a + b)
        t = IO.delay(f, 1).flat_map(L(g)(_, 3))
        t2 = t.map(fail)
        exc = t2._attempt().value
        code = (exc.location / _.code_context) | ''
        code[0].should.contain('t.map(fail)')
예제 #15
0
파일: tree.py 프로젝트: yangyang202/DA_GP9
 def lift(self, key: Key) -> 'SubTree':
     return (SubTreeInvalid(key, 'ListNode index must be int')
             if isinstance(
                 key, str) else self.sub.lift(key) / L(SubTree.cons)(_, key)
             | (lambda: SubTreeInvalid(key, 'ListNode index oob')))
예제 #16
0
파일: compute.py 프로젝트: tek/chiasma-py
def execute_read(writes: List[TmuxCmd], read: TmuxCmd) -> Do:
    results = yield execute_cmds(writes, Just(read))
    yield TmuxIO.from_either(
        results.last.map(read_result) | L(Left)(f'no output for {read}'))
예제 #17
0
파일: mod.py 프로젝트: yangyang202/DA_GP9
def objects_from_module(mod: ModuleType, pred: Callable[[Any], bool]) -> Do:
    all = yield Maybe.getattr(mod, '__all__').to_either(
        f'module `{mod.__name__}` does not define `__all__`')
    return (Lists.wrap(all).flat_map(L(Maybe.getattr)(mod, _)).filter(pred))
예제 #18
0
 def assemble(path):
     return (cb(self.rest).io('invalid arguments') /
             L(self.client.post)('{}{}'.format(path, sub), _))
예제 #19
0
 def assemble(i, a):
     return cb(a).io('invalid arguments') // L(io)(i, _)
예제 #20
0
파일: io.py 프로젝트: tangleibest/untitled
 def delay(f: Callable[..., A], *a: Any, **kw: Any) -> 'IO[A]':
     return Suspend(L(f)(*a, **kw) >> Pure, safe_fmt(f, a, kw))
예제 #21
0
class ScalarEncoder(Encoder[Union[Number, str, None]], pred=L(issubclass)(_, (Number, str, type(None)))):

    def encode(self, a: Union[Number, str, None]) -> Either[JsonError, Json]:
        return Right(JsonScalar(a))
예제 #22
0
def format_logger_tree(tree: 'amino.Map[Logger, Any]', fmt_logger: Callable[[Logger], str], level: int=0
                       ) -> 'amino.List[str]':
    from amino import _, L
    sub_f = L(format_logger_tree)(_, fmt_logger, level=level + 1)
    formatted = tree.bimap(fmt_logger, sub_f)
    return indent(formatted.flat_map2(lambda a, b: b.cons(a)), level)
예제 #23
0
def encode_json(data: A) -> Do:
    enc = yield Encoder.e_for(data).lmap(L(JsonError)(data, _))
    yield enc.encode(data)
예제 #24
0
 def _clean_done(self, a):
     p = a.proc
     if p.done.value:
         monitor = self._releases.find_by_id(p.monitor.id)
         a.proc.result % __.find(L(self._process_results)(monitor, _))
         return True
예제 #25
0
def sub_loggers(loggers, root):
    from amino import Map, _, L
    children = loggers.keyfilter(L(re.match)('{}\.[^.]+$'.format(root), _))
    sub = (children.k / L(sub_loggers)(loggers, _)).fold_left(Map())(operator.pow)
    return Map({loggers[root]: sub})
예제 #26
0
파일: io.py 프로젝트: tangleibest/untitled
 def suspend(f: Callable[..., 'IO[A]'], *a: Any, **kw: Any) -> 'IO[A]':
     return Suspend(L(f)(*a, **kw), safe_fmt(f, a, kw))
예제 #27
0
 def decode_field(field: Field) -> Do:
     value = yield data.field(field.name)
     dec = yield Decoder.e(field.tpe).lmap(L(JsonError)(data, _))
     yield dec.decode(field.tpe, value)
예제 #28
0
파일: io.py 프로젝트: tangleibest/untitled
 def _flat_map(self, f: Callable[[A], IO[B]], ts: Eval[str],
               fs: Eval[str]) -> IO[B]:
     bs = L(BindSuspend)(
         self.thunk, lambda a: self.f(a).flat_map(f, Just(ts), Just(fs)),
         ts, fs)
     return Suspend(bs, (ts & fs).map2('{}.{}'.format))
예제 #29
0
class ListEncoder(Encoder[List], pred=L(issubclass)(_, Collection)):

    def encode(self, a: Collection) -> Either[JsonError, Json]:
        return Lists.wrap(a).traverse(encode_json, Either) / JsonArray
예제 #30
0
파일: io.py 프로젝트: tangleibest/untitled
 def _flat_map(self, f: Callable[[A], IO[B]], ts: Eval[str],
               fs: Eval[str]) -> IO[B]:
     return Suspend(L(f)(self.value), (ts & fs).map2('{}.{}'.format))