Exemplo n.º 1
0
def collect_ast():
    type_spec: dict = collections.defaultdict(set)

    def is_python(path: str):
        return path.endswith('.py') or Path(path).is_dir()

    all_python_files = linq.Flow(
        Path(Redy.__file__).parent().collect(is_python)).concat(
            Path(flask.__file__).parent().collect(is_python))._

    for each in all_python_files:
        with each.open('r', encoding='utf8') as file:
            try:
                ast_of_src_code = ast.parse(file.read())
                service = CollectASTTypeStub(type_spec)
                feature(service).just_apply_ast_transformation(ast_of_src_code)
            except SyntaxError:
                # other py version
                pass

    def snd(tp):
        return tp[1]

    stub_code = \
    (linq.Flow(type_spec)
         .map(lambda class_name, fields:
                linq.Flow(fields)
                    .group_by(lambda fst, snd: fst)
                    .map(lambda field_name, pairs:
                            '{}: {}'.format(
                            field_name,
                            compose(
                                str,
                                curry(reduce)(lambda a, b: a.union(b)),
                                curry(map)(snd))(pairs)))
                    .then(
                        compose(
                            'class {}(AST):\n'.format(class_name).__add__,
                            lambda _: textwrap.indent(_, " " * 4),
                            lambda any_code: any_code if any_code else 'pass',
                            '\n'.join))
                    ._)
         .then(
            compose(
                'import typing, abc\nNoneType = None\n'.__add__,
                'class AST(abc.ABC):\n    def __init__(self, *args, lineno: int=None, colno: int=None, **kwargs): pass\n'.__add__,
                '\n'.join
                )))._

    with Path('./').into('ast.pyi').open('w', encoding='utf8') as stub:
        stub.write(stub_code)

    with Path(ast.__file__).parent().into('ast.pyi').open(
            'w', encoding='utf8') as stub:
        stub.write(stub_code)
Exemplo n.º 2
0
def room(group_id, channel: str):
    user: db.User = g.user

    public = msg_rx.Group.Channel.Public
    board = msg_rx.Group.Channel.Board
    user_group = RxList(user.ref_groups).where(group_id=group_id).first()
    if not user_group:
        flash('您不是该群成员')
        return redirect(url_for('group.center'))
    group = user_group.group

    activity_refs: 'Dict[int, List[db.GroupActivity]]' = linq.Flow(
        each for each in group.ref_activitys).GroupBy(
            lambda each: each.is_active).Unboxed()

    activated_acts = tuple(each.activity for each in activity_refs[True])
    deactivated_acts = tuple(each.activity for each in activity_refs[False])

    def for_specific_channel(specific_channel: msg_rx.Group.Channel):
        limit = 50
        lst = msg_rx.Group.get_msg_list(group_id, specific_channel)
        datetime_lst = [parse(each.time) for each in lst]
        lst2 = zip(datetime_lst, enumerate(lst))
        lst_shorter = sorted(lst2, key=lambda tp: tp[0], reverse=True)[:limit]
        return dict(map(lambda x: x[1], lst_shorter))

    AdminPermission = not (RxTable(db.UserGroup).where(
        user_id=user.id, group_id=group.id).first().user_cls == db.Role.normal)

    return render_template(
        'group/room.html',
        AdminPermission=AdminPermission,
        activated_acts=activated_acts,
        deactivated_acts=deactivated_acts,
        msg_dict_public=for_specific_channel(board),
        msg_dict_chat=for_specific_channel(public),
        msg_dict_req=for_specific_channel(msg_rx.Group.Channel.ApplyIn),
        group=group,
        user=user,
        db=db,
        channel_branch=channel,

        # default_layers
        side_info=load_side_info(user),
        side_options=load_side_options())
Exemplo n.º 3
0
def center():
    user: db.User = g.user

    def group_fn(e: db.UserGroup):
        return e.user_cls == db.Role.normal

    res = linq.Flow(user.ref_groups).GroupBy(group_fn).Unboxed()
    manage_groups: List[db.UserGroup] = res.get(False)
    my_groups: List[db.UserGroup] = res.get(True)
    if not my_groups:
        my_groups = ()
    if not manage_groups:
        manage_groups = ()
    manage_groups = [each.group for each in manage_groups]
    my_groups = [each.group for each in my_groups]

    return render_template('group/center.html',
                           title='群组',
                           my_groups=my_groups,
                           manage_groups=manage_groups,
                           side_info=load_side_info(user),
                           side_options=load_side_options())
Exemplo n.º 4
0
def center():
    """签到中心主页"""

    user: db.User = g.user
    form = request.form

    normal_signs: 'Dict[int, List[db.UserSign]]' = linq.Flow(
        user_sign
        for user_sign in user.ref_signs
        if
        user_sign.user_cls == db.Role.normal
    ).GroupBy(
        lambda user_sign: user_sign.is_sign
    ).Unboxed()

    sign_completed = (each.sign for each in normal_signs[1])

    sign_on = (each.sign for each in normal_signs[0])

    now = SyncCurrent.get_date()
    half_a_month = date.timedelta(30)

    # 只选激活的
    sign_completed = tuple(each for each in sign_completed if not each.end or now < each.end + half_a_month)
    sign_on = tuple(each for each in sign_on if each.is_active and (not each.end or now < each.end + half_a_month))

    manager_ids = [each.ref_users.filter(db.UserSign.user_cls == db.Role.leader).first().user_id for each in
                   sign_completed]

    sign_completed = tuple(zip(manager_ids, sign_completed))

    def get_group_status_and_activities(user_group: db.UserGroup) -> Tuple[db.Group, List[db.Activity]]:
        group = user_group.group
        acts = [each.activity for each in group.ref_activitys if each.is_active]
        return group, acts

    managing_activities: List[Tuple[db.Group, List[db.Activity]]] = [get_group_status_and_activities(each) for each
                                                                     in user.ref_groups if
                                                                     each.user_cls != db.Role.normal]

    current_courses = [uc.course for uc in user.ref_courses
                       if course_helper.Controller.is_ready(uc.course, date=date.SyncCurrent.get_date())]

    if user.permission == Permission.teacher:
        # 所有管理的课程
        managing_courses = current_courses
        # taking_courses = ()

    else:
        managing_courses = ()
        # taking_courses = current_courses

    return render_template('attendance/center.html',
                           title="签到中心",
                           user=user,
                           form=form,
                           sign_stats=inc.Collection(
                               inc.CollectionItemA("历史统计记录", inc.Href(url_for('attendance.course_list')))
                           ) if user.permission == Permission.teacher else "<br>",
                           sign_on=sign_on,
                           sign_completed=sign_completed,
                           activity_ready=managing_activities,
                           course_ready=managing_courses,
                           side_info=load_side_info(user),
                           side_options=load_side_options())
Exemplo n.º 5
0
 def getp(d: dict):
     d["ops"] = linq.Flow(GroupOption).index(d["ops"]).Unboxed()
     d["cls"] = linq.Flow(GroupClass).index(d["cls"]).Unboxed()
     d["start"] = parse(d["start"])
     return d
Exemplo n.º 6
0
}

large_data = {
    'C1': {
        'lst': list(range(500)),
        'bar': "1213"
    },
    'C2': {
        'foo': 42
    },
    'C3': {f'bar{i}': list(range(500))
           for i in range(1, 12)}
}

test_files = list(filter(lambda x: x.startswith('test_'), os.listdir('.')))
split_set = linq.Flow(test_files).GroupBy(lambda _: 'content' in _).Unboxed()

with_contents = split_set[True]
singles = split_set[False]

with open('result.json', 'w') as f:
    f.write('{}')

for spec_script in ('test_load.py', 'test_new.py', 'test_save.py',
                    'test_new_by_id.py'):

    for cell_type in ('C1', 'C2', 'C3'):

        for backend in ('co', 'swig', 'redis', 'pynet'):

            # cmd(['python', spec_script, backend, cell_type])
Exemplo n.º 7
0
 def course_ready(cls, courses: List[Course],
                  date: datetime) -> Iterator[Course]:
     return linq.Flow(courses).Filter(cls.is_ready(date=date)).Unboxed()
Exemplo n.º 8
0
        except FileExistsError:
            pass
    if then_call is not None:
        return then_call(path)
    return path


if is_windows:
    # build dlls
    if cmdparser.parse_args().nocache:
        os.system('{} "{}"'.format(BUILD_SCRIPT_CMD, BUILD_SCRIPT_PATH))

    to_pymodule_dir = lambda path, with_suffix, to_module, cond=(
        lambda _: True
    ): (linq.Flow(path).Then(recur_listdir).Filter(lambda _: any(
        _.endswith(suffix) for suffix in with_suffix)).Filter(cond).Each(
            dir_at(CURRENT_DIR, 'GraphEngine', to_module, then_call=copy_to)))
    # copy dlls

    to_pymodule_dir(CORECLR_PATH,
                    with_suffix=['.py', '.dll', '.pyd'],
                    to_module='ffi')

    # build Trinity.StorageVersionController.csproj
    dir_at(
        pardir_of(pardir_of(BUILD_SCRIPT_PATH)),
        'GraphEngine.Storage.Composite',
        then_call=lambda _: os.system(
            'cd {} && dotnet restore && dotnet build --configuration Release'.
            format(_)))