Пример #1
0
def get_unit_route(request, unit_id):
    """
    Get a specific unit given an ID.
    """

    db_conn = request["db_conn"]

    unit = Unit.get_latest_accepted(db_conn, unit_id)
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(db_conn, unit_id)
    versions = Unit.get_versions(db_conn, unit_id)
    requires = Unit.list_requires(db_conn, unit_id)
    required_by = Unit.list_required_by(db_conn, unit_id)
    sets = Set.list_by_unit_id(db_conn, unit_id)

    return (
        200,
        {
            "unit": unit.deliver(),
            # 'unit_parameters': unit.fetch_parameters(),
            "topics": [topic.deliver() for topic in topics],
            "versions": [version.deliver() for version in versions],
            "requires": [require.deliver() for require in requires],
            "required_by": [require.deliver() for require in required_by],
            "belongs_to": [set_.deliver() for set_ in sets],
        },
    )
Пример #2
0
def get_unit_route(request, unit_id):
    """
    Get a specific unit given an ID.
    """

    unit = Unit.get_latest_accepted(unit_id)
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(unit_id)
    versions = Unit.get_versions(unit_id)
    requires = Unit.list_requires(unit_id)
    required_by = Unit.list_required_by(unit_id)
    sets = Set.list_by_unit_id(unit_id)

    return 200, {
        'unit': unit.deliver(),
        # 'unit_parameters': unit.fetch_parameters(),
        'topics': [topic.deliver() for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
        'belongs_to': [set_.deliver() for set_ in sets],
    }
Пример #3
0
def get_unit_route(request, unit_id):
    """
    Get a specific unit given an ID.
    """

    db_conn = request['db_conn']

    unit = Unit.get_latest_accepted(db_conn, unit_id)
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = list_topics_by_entity_id(unit_id, {}, db_conn)
    versions = Unit.get_versions(db_conn, unit_id)
    requires = Unit.list_requires(db_conn, unit_id)
    required_by = Unit.list_required_by(db_conn, unit_id)
    sets = Set.list_by_unit_id(db_conn, unit_id)

    return 200, {
        'unit': unit.deliver(),
        # 'unit_parameters': unit.fetch_parameters(),
        'topics': [deliver_topic(topic) for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
        'belongs_to': [set_.deliver() for set_ in sets],
    }
Пример #4
0
    def add_unit(self, board_id, text, position):
        pith, transclusions = self.gm._get_pith(board_id, text)
        position = Position(x=position["x"], y=position["y"])
        unit = Unit(board_id=board_id, pith=pith, position=position)
        unit.id = "{}:{}".format(unit.board_id, unit.short_id)

        self.gm.units.insert_one(unit.to_mongo())
        unit_id = unit.short_id
        self.gm._insert_transclusions(board_id, unit_id, transclusions)
        self._record_unit_update(board_id, unit_id)
        return {"unit": self.gm._get_extended_unit(board_id, unit_id)}
def dummy_unit() -> Unit:
    """
    Creates a dummy unit
    :yields: A unit instance
    """
    dummy_unit = Unit("NOT_A_SYMBOL", "DUMMY_DESCRIPTION")
    dummy_unit.save()
    dummy_unit.commit()
    yield dummy_unit
    dummy_unit.delete()
    dummy_unit.commit()
    def create_unit(self, _type: str, description: str) -> db.Model:
        """
        Create Unit
        :param _type: Unit type
        :param description: Description of unit
        :return: Unit

        """
        unit = Unit(_type=_type, description=description)
        unit.save()
        return unit
    def post(
        self) -> ({
            "message": str,
            "symbol": str,
            "description": str
        }, HTTPStatus):
        """
        Fetches a specified unit instance from the database by its symbol or description
        :post:
        :arg symbol:        Symbol string of the unit eg 'kg'
        :arg description:   The description of the unit
        :type symbol:       str
        :type description:  str

        :return: on success a JSON of the unit and an HTTPStatus code 200 is return otherwise a JSON decription of the
        error and the appropriate HTTPStatus code
        """
        if not get_jwt_claims()['admin']:
            return {"message": "Not Authorized."}, HTTPStatus.UNAUTHORIZED

        # Get arguments passed in POST request
        args = self.reqparser.parse_args()
        # is symbol or discription present?
        if args["symbol"] is None and args["description"] is None:
            # no symbol or description of the unit to find is present.
            return {
                "message": "symbol or description is required.",
                "symbol": "not supplied",
                "description": "not supplied"
            }, HTTPStatus.BAD_REQUEST
        # try fetch the unit from the database
        unit = Unit.get_by_symbol(
            args["symbol"]
        ) if args["symbol"] is not None else Unit.get_by_description(
            args["description"])

        # was the unit found?
        if not unit:
            # the unit with the symbol or description was not found
            return {
                "message":
                "Unit not found.",
                "symbol":
                args["symbol"] if "symbol" in args else "-",
                "description":
                args["description"] if "description" in args else "-"
            }, HTTPStatus.NOT_FOUND

        return unit.json(), HTTPStatus.OK
Пример #8
0
    def __init__(self,
                 input_x_vector,
                 num_hidden_layers,
                 num_units_per_layer,
                 activation_func=None,
                 unit_weight_mean=0,
                 unit_bias_mean=0,
                 unit_weight_logsigma=1,
                 unit_bias_logsigma=1):

        if num_units_per_layer < 1:
            print(
                "num units per layer should be at least 1. If you want no hidden layers, set num hidden layers to 0"
            )
            exit(1)

        self.input_layer = [Unit(x) for x in input_x_vector
                            ]  # weights are not important here

        self.hidden_layers = []

        for layer_index in range(0, num_hidden_layers):
            new_layer = []

            for unit_index in range(0, num_units_per_layer):

                # Implementation detail: the units in first hidden layer should have weight vectors of length equal
                # to the input vector length. In the rest of hidden layers, the units should have weight vectors with
                # length of the previous layer length. In this implementation, all hidden layers have same num of units!
                # Therefore, the units have a weight vector of the length of num_units_per_layer
                if layer_index == 0:  # first hidden layer (not the input layer)
                    new_unit = Unit(0, len(self.input_layer), unit_weight_mean,
                                    ag_np.exp(unit_weight_logsigma)**2,
                                    unit_bias_mean,
                                    ag_np.exp(unit_bias_logsigma)**2)
                else:
                    new_unit = Unit(0, num_units_per_layer, unit_weight_mean,
                                    ag_np.exp(unit_weight_logsigma)**2,
                                    unit_bias_mean,
                                    ag_np.exp(unit_bias_logsigma)**2)

                new_layer.append(new_unit)

            self.hidden_layers.append(new_layer)

        # should be set separately
        self.activation_func = activation_func

        self.output_unit = Unit(0, num_units_per_layer)
Пример #9
0
def flush_entities(db_conn, descs):
    """
    Given a list of kinds and entity_ids,
    return a list filled out with entities.
    """

    output = []

    for desc in descs:
        if desc['kind'] == 'card':
            card = Card.get_latest_accepted(db_conn, entity_id=desc['id'])
            card = flip_card_into_kind(card)
            if card:
                output.append(card)
        elif desc['kind'] == 'unit':
            output.append(Unit.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        elif desc['kind'] == 'subject':
            output.append(Subject.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        else:
            output.append(None)

    return output
Пример #10
0
    def merge_units(self, attribute_data, base_importer):
        # Fetch units from database
        self._print_in_middle('\nUnits available in Database')
        units = Unit.get()
        # show units
        for unit in range(len(units)):
            print(str(unit) + '.', units[unit]._type)

        self._questions('Does the listed units contains all the respective units for this dataset: (Y/N) ')
        unit_available = input()
        if unit_available == 'y' or unit_available == 'Y':
            # This is repetition of code from above
            self._print_in_middle('\nAttributes and their respective Unit Values')
            self._print_attribute_data(attribute_data)

            self._questions(Statuses.CHOOSE_UNIT_ID, end='\n')

            for unit in range(len(units)):
                print(units[int(unit)]._type + ':', end='')
                attr_unit_ids = input().split()
                base_importer.join_attr_unit_type([attribute_data[int(i)] for i in attr_unit_ids], 
                                                    units[int(unit)].id)

        else:
            # Need to give user an option here to create new Units for their datasets
            pass
Пример #11
0
def flush_entities(db_conn, descs):
    """
    Given a list of kinds and entity_ids,
    return a list filled out with entities.
    """

    output = []

    for desc in descs:
        if desc['kind'] == 'card':
            card = Card.get_latest_accepted(db_conn, entity_id=desc['id'])
            card = flip_card_into_kind(card)
            if card:
                output.append(card)
        elif desc['kind'] == 'unit':
            output.append(Unit.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        elif desc['kind'] == 'set':
            output.append(Set.get_latest_accepted(
                db_conn,
                entity_id=desc['id']
            ))
        else:
            output.append(None)

    return output
    def post(self) -> ({"message": str, "symbol": str, "description": str}, HTTPStatus):
        """
        Deletes a unit of measure in the unit database table by the _type value
        for example symbol = 'kg'. if the the symbol='kg' exists in the table it will be deleted
        Parameters can be passed using a POST request that contains a JSON with the following fields:
                :param symbol: units symbol eg kg for kilograms
                :type symbol: string
        :return: A json response  containing a message, unit type and unit description with an http status code of 204
        """
        if not get_jwt_claims()['admin']:
            return {"message": "Not Authorized."}, HTTPStatus.UNAUTHORIZED

        args = self.reqparser.parse_args()
        # get unit instance from db by symbol
        unit = Unit.get_by_symbol(args["symbol"])

        if not unit:
            # Unit symbol not found
            return {"message": "Unit not found",
                    "symbol": args["symbol"]
                    }, HTTPStatus.NOT_FOUND
        # delete unit from db
        unit.delete()
        unit.commit()

        return {"message": "Unit deleted",
                "symbol": unit.symbol,
                "description": unit.description
                }, HTTPStatus.NO_CONTENT
Пример #13
0
def instance_entities(data):
    """
    Given a kind and some json, call insert on that kind
    and return the results.
    A little safer.
    """

    fields = ('id', 'created', 'modified',
              'entity_id', 'previous_id', 'status', 'available')
    entities = []
    if 'cards' in data:
        for card_data in data['cards']:
            kind = card_data.get('kind')
            if kind in card_map:
                entities.push(
                    card_map[kind](omit(card_data, fields))
                )
    if 'units' in data:
        entities = entities + [
            Unit(omit(unit_data, fields))
            for unit_data in data['units']
        ]
    if 'subjects' in data:
        entities = entities + [
            Subject(omit(subject_data, fields))
            for subject_data in data['subjects']
        ]
    return entities
Пример #14
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    card = get_card_by_kind(card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(entity_id=card_id)
    versions = Card.get_versions(entity_id=card_id)
    requires = Card.list_requires(entity_id=card_id)
    required_by = Card.list_required_by(entity_id=card_id)
    params = CardParameters.get(entity_id=card_id)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters': params.get_values(),
        'unit': unit.deliver(),
        'topics': [topic.deliver() for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #15
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    db_conn = request['db_conn']

    card = get_card_by_kind(db_conn, card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(db_conn, entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = list_topics_by_entity_id(card_id, {}, db_conn)
    versions = Card.get_versions(db_conn, entity_id=card_id)
    requires = Card.list_requires(db_conn, entity_id=card_id)
    required_by = Card.list_required_by(db_conn, entity_id=card_id)
    params = get_card_parameters({'entity_id': card_id}, db_conn)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters':
        (get_card_parameters_values(params) if params else None),
        'unit': unit.deliver(),
        'topics': [deliver_topic(topic) for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #16
0
def get_card_route(request, card_id):
    """
    Get a specific card given an ID. Show all relevant data, but
    not used for the learning interface.
    """

    card = get_card_by_kind(card_id)
    if not card:
        return abort(404)

    unit = Unit.get_latest_accepted(entity_id=card['unit_id'])
    if not unit:
        return abort(404)

    # TODO-2 SPLITUP create new endpoints for these instead
    topics = Topic.list_by_entity_id(entity_id=card_id)
    versions = Card.get_versions(entity_id=card_id)
    requires = Card.list_requires(entity_id=card_id)
    required_by = Card.list_required_by(entity_id=card_id)
    params = CardParameters.get(entity_id=card_id)

    return 200, {
        'card': card.deliver(access='view'),
        'card_parameters': params.get_values(),
        'unit': unit.deliver(),
        'topics': [topic.deliver() for topic in topics],
        'versions': [version.deliver() for version in versions],
        'requires': [require.deliver() for require in requires],
        'required_by': [require.deliver() for require in required_by],
    }
Пример #17
0
    def post(self, board_id, discussion_id, user_id, text, flairs):
      pith, transclusions = self.gm._get_pith(board_id, text)
      user = self.gm.users.find_one({"board_id": board_id, "short_id": user_id})

      unit = Unit(board_id=board_id, pith=pith, chat=True, 
        author=user_id, author_name=user["nickname"], flairs=flairs)
      unit.id = "{}:{}".format(unit.board_id, unit.short_id)

      self.gm.units.insert_one(unit.to_mongo())
      unit_id = unit.short_id
      self.gm._insert_transclusions(board_id, unit_id, transclusions)
      self.gm.discussions.update_one(
        {"short_id" : discussion_id, "board_id": board_id},
        {"$push": {"chat": unit_id}}
      )
      return {"unit": self.gm._get_chat_unit(board_id, unit_id)}
Пример #18
0
def get_version(db_conn, kind, id_):
    if kind == 'card':
        card = Card.get(db_conn, id=id_)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get(db_conn, id=id_)
    elif kind == 'set':
        return Set.get(db_conn, id=id_)
Пример #19
0
def get_unit_versions_route(request, unit_id):
    """
    Get unit versions given an ID. Paginates.
    """

    db_conn = request["db_conn"]
    versions = Unit.get_versions(db_conn, entity_id=unit_id, **request["params"])
    return 200, {"versions": [version.deliver(access="view") for version in versions]}
Пример #20
0
def get_version(db_conn, kind, id_):
    if kind == 'card':
        card = Card.get(db_conn, id=id_)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get(db_conn, id=id_)
    elif kind == 'set':
        return Set.get(db_conn, id=id_)
Пример #21
0
def get_version(kind, id_):
    if kind == 'card':
        return Card.get(id=id_)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get(id=id_)
    elif kind == 'set':
        return Set.get(id=id_)
Пример #22
0
def get_version(kind, id_):
    if kind == 'card':
        return Card.get(id=id_)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get(id=id_)
    elif kind == 'set':
        return Set.get(id=id_)
Пример #23
0
    def publish(self, board_id, discussion_id, unit_id, position):
        # make copy
        orig_unit = self.gm.units.find_one({
            "short_id": unit_id,
            "board_id": board_id
        })
        position = Position(x=position["x"], y=position["y"])

        pith, transclusions = self.gm._get_pith(board_id, orig_unit["pith"])
        unit = Unit(board_id=board_id, pith=pith, position=position)
        unit.id = "{}:{}".format(unit.board_id, unit.short_id)

        self.gm.units.insert_one(unit.to_mongo())
        unit_id = unit.short_id
        self.gm._insert_transclusions(board_id, unit_id, transclusions)
        self._record_unit_update(board_id, unit_id)
        return {"unit": self.gm._get_extended_unit(board_id, unit_id)}
Пример #24
0
    def log_likelihood(self, n_outputs, n_inputs, sigma=0.1):
        loglik = 0

        for index, input in enumerate(n_inputs):
            f_x_w_b = self.propagate_forward_and_calculate_output(Unit(input))
            loglik += ag_norm.logpdf(n_outputs[index], f_x_w_b, sigma**2)

        return loglik
Пример #25
0
        def _():
            # *** First, we need to break down
            #     the set into a list of known units. ***

            unit_ids = set()
            sets = [self]

            while sets:
                set_ids = set()
                for set_ in sets:
                    unit_ids.update({
                        member['id']
                        for member in set_.data.get('members')
                        if member['kind'] == 'unit'
                    })
                    set_ids.update({
                        member['id']
                        for member in set_.data.get('members')
                        if member['kind'] == 'set'
                    })
                sets = Set.list_by_entity_ids(set_ids)

            # *** Second, we need to find all
            #     the required connecting units. ***

            next_grab, units, unit_requires = unit_ids, [], {}

            while next_grab:
                tier_units = Unit.list_by_entity_ids(next_grab)
                units += tier_units
                next_grab = set()

                for unit in tier_units:
                    if 'require_ids' not in unit:
                        continue
                    unit_id = unit['entity_id']
                    require_ids = unit_requires[unit_id] = \
                        set(unit['require_ids'])
                    for require_id in require_ids:
                        if require_id in unit_ids:
                            ids = {unit_id}
                            while ids:
                                unit_ids.update(ids)
                                ids = {
                                    unit_id
                                    for unit_id, require_ids in
                                    unit_requires.items()
                                    if unit_id not in unit_ids and require_ids
                                    & ids
                                }
                        elif require_id not in unit_requires:
                            next_grab.add(require_id)

            units = [
                unit.data for unit in units if unit['entity_id'] in unit_ids
            ]

            return units
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(entity_id='add')
    user = User.get(id='user')
    assert judge(unit, user) == "done"
def test_judge_diagnose(db_conn, users_table, units_table, responses_table):
    """
    Expect to add no known ability to "diagnose".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(entity_id='divide')
    user = User.get(id='user')
    assert judge(unit, user) == "diagnose"
def test_judge_learn(db_conn, units_table, users_table, responses_table):
    """
    Expect to add known low ability to "learn".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="multiply")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "learn"
def test_judge_review(db_conn, users_table, units_table, responses_table):
    """
    Expect to add older, high ability to "review".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(entity_id='subtract')
    user = User.get(id='user')
    assert judge(unit, user) == "review"
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="add")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "done"
def test_judge_diagnose(db_conn, users_table, units_table, responses_table):
    """
    Expect to add no known ability to "diagnose".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="divide")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "diagnose"
def test_judge_learn(db_conn, units_table, users_table, responses_table):
    """
    Expect to add known low ability to "learn".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(entity_id='multiply')
    user = User.get(id='user')
    assert judge(unit, user) == "learn"
Пример #33
0
def get_my_recently_created_units(current_user, db_conn):
    """
    Get the user's most recently created units.
    """

    proposals = get_my_recent_proposals(current_user, db_conn)
    unit_version_ids = get_proposal_entity_versions(proposals, 'unit')
    units = Unit.list_by_version_ids(db_conn, unit_version_ids)
    return units
Пример #34
0
def approximate_loss(m_tilda, m_bar, s_tilda, s_bar, x_train_N, y_train_N):
    bnn = Bnn([Unit()], 0, 1, ag_np.tanh, m_tilda, m_bar, s_tilda, s_bar)
    log_p_w = bnn.get_log_p_w()
    log_p_b = bnn.get_log_p_b()
    log_p_w_b = log_p_w + log_p_b
    log_p_y_given_x_w_b = bnn.log_likelihood(y_train_N, x_train_N)
    log_q = bnn.get_log_q_w_b_given_m_s(m_tilda, m_bar, s_tilda, s_bar)
    L = log_p_w_b + log_p_y_given_x_w_b - log_q
    return L
def test_judge_learn(db_conn, units_table, users_table, responses_table):
    """
    Expect to add known low ability to "learn".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='multiply')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "learn"
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='add')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "done"
def test_judge_diagnose(db_conn, users_table, units_table, responses_table):
    """
    Expect to add no known ability to "diagnose".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='divide')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "diagnose"
def test_judge_review(db_conn, users_table, units_table, responses_table):
    """
    Expect to add older, high ability to "review".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id='subtract')
    user = get_user({'id': 'user'}, db_conn)
    assert judge(db_conn, unit, user) == "review"
Пример #39
0
def get_unit_versions_route(request, unit_id):
    """
    Get unit versions given an ID. Paginates.
    """

    versions = Unit.get_versions(entity_id=unit_id, **request['params'])
    return 200, {
        'versions': [version.deliver(access='view') for version in versions]
    }
def test_judge_done(db_conn, units_table, users_table, responses_table):
    """
    Expect to show "done".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(entity_id='add')
    user = User.get(id='user')
    assert judge(unit, user) == "done"
def test_judge_review(db_conn, users_table, units_table, responses_table):
    """
    Expect to add older, high ability to "review".
    """

    add_test_set(db_conn, users_table, units_table, responses_table)
    unit = Unit.get(db_conn, entity_id="subtract")
    user = get_user({"id": "user"}, db_conn)
    assert judge(db_conn, unit, user) == "review"
Пример #42
0
def test_language(db_conn, units_table):
    """
    Expect a unit to require a language.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
        'body': 'Learn how to do this',
    })
    assert len(errors) == 0
    assert unit['language'] == 'en'
    def setUp(self):
        """
        Setup a FlaskClient, AppContext, Admin user, Authorization header for requests to
        the Flask Client and a dummy Theme
        """
        self.client, self.app_context = self.create_test_client()
        self.user = self.create_admin_user()
        self.auth_header = self.get_auth_header()
        self.unit = Unit("_test_unit_type_", "A test unit")
        self.unit.save()
        self.unit.commit()
        self.attribute = Attributes.get_by_name("_test_attribute_")
        self.theme = self.create_dummy_theme()
        self.subtheme = self.create_dummy_subtheme()
        if not self.attribute:
            self.attribute = Attributes("1234567890-123456789-123456789", "_test_attribute_", "_table_name_",
                                        self.subtheme.id, self.unit.id)
            self.attribute.save()
            self.attribute.commit()

        self.clean_up = [self.user, self.attribute, self.theme, self.subtheme, self.theme, self.unit]
Пример #44
0
    def tearDown(self) -> None:
        """ Clean up all dependencies after tests"""

        for alias in self.aliases:
            try:
                if AttrAlias.get_by_user_id(self.user.id):
                    alias.delete()
                    alias.commit()
            except Exception:
                pass

        for attr in self.attributes:
            try:
                if Attributes.get_by_id(attr.id):
                    attr.delete()
                    attr.commit()
            except Exception:
                pass

        for sub_theme in self.sub_themes:
            try:
                if SubTheme.get_by_id(sub_theme.id):
                    sub_theme.delete()
                    sub_theme.commit()
            except Exception:
                pass

        for unit in self.units:
            try:
                if Unit.get_by_id(unit.id):
                    unit.delete()
                    unit.commit()
            except Exception:
                pass

        try:
            if Theme.get_by_id(self.theme.id):
                self.theme.delete()
                self.theme.commit()
        except Exception:
            pass

        self.client.post('/logout', headers=self.auth_header)

        if self.user:
            if Users.find_by_id(self.user.id):
                try:
                    self.user.delete()
                    self.user.commit()
                except Exception:
                    pass

        self.app_context.pop()
Пример #45
0
def test_body(db_conn, units_table):
    """
    Expect a unit to require a body.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
    })
    assert len(errors) == 1
    unit['body'] = 'Learn how to do this'
    unit, errors = unit.save()
    assert len(errors) == 0
def test_match_unit_dependents(db_conn, units_table):
    """
    Expect to order units by the number of depending units.
    """

    add_test_set(db_conn, units_table=units_table)
    units = Unit.list_by_entity_ids(db_conn, ["add", "subtract", "multiply", "divide"])
    deps = match_unit_dependents(units)
    assert len(deps["add"]) == 3
    assert len(deps["multiply"]) == 1
    assert len(deps["subtract"]) == 1
    assert len(deps["divide"]) == 0
Пример #47
0
        def _():
            # *** First, we need to break down
            #     the set into a list of known units. ***

            unit_ids = set()
            sets = [self]

            while sets:
                set_ids = set()
                for set_ in sets:
                    unit_ids.update({member['id']
                                     for member in set_.data.get('members')
                                     if member['kind'] == 'unit'})
                    set_ids.update({member['id']
                                    for member in set_.data.get('members')
                                    if member['kind'] == 'set'})
                sets = Set.list_by_entity_ids(set_ids)

            # *** Second, we need to find all
            #     the required connecting units. ***

            next_grab, units, unit_requires = unit_ids, [], {}

            while next_grab:
                tier_units = Unit.list_by_entity_ids(next_grab)
                units += tier_units
                next_grab = set()

                for unit in tier_units:
                    if 'require_ids' not in unit:
                        continue
                    unit_id = unit['entity_id']
                    require_ids = unit_requires[unit_id] = \
                        set(unit['require_ids'])
                    for require_id in require_ids:
                        if require_id in unit_ids:
                            ids = {unit_id}
                            while ids:
                                unit_ids.update(ids)
                                ids = {unit_id
                                       for unit_id, require_ids
                                       in unit_requires.items()
                                       if unit_id not in unit_ids
                                       and require_ids & ids}
                        elif require_id not in unit_requires:
                            next_grab.add(require_id)

            units = [unit.data
                     for unit in units
                     if unit['entity_id'] in unit_ids]

            return units
Пример #48
0
def choose_unit_route(request, set_id, unit_id):
    """
    Updates the learner's information based on the unit they have chosen.

    NEXT STATE
    POST Chosen Unit
        -> GET Learn Card
    """

    # TODO-3 simplify this method. should it be broken up or moved to model?
    db_conn = request['db_conn']

    current_user = get_current_user(request)
    if not current_user:
        return abort(401)

    unit = Unit.get_latest_accepted(db_conn, unit_id)
    if not unit:
        return abort(404)

    # If the unit isn't in the set...
    context = get_learning_context(current_user)
    set_ids = [set_['entity_id']
               for set_ in Set.list_by_unit_id(db_conn, unit_id)]
    if context.get('set', {}).get('entity_id') not in set_ids:
        return abort(400)

    status = judge(db_conn, unit, current_user)
    # Or, the unit doesn't need to be learned...
    if status == "done":
        return abort(400)

    # Choose a card for the learner to learn
    card = choose_card(db_conn, current_user, unit)

    if card:
        next_ = {
            'method': 'GET',
            'path': '/s/cards/{card_id}/learn'
                    .format(card_id=card['entity_id']),
        }
    else:
        next_ = {}

    set_learning_context(
        current_user,
        unit=unit.data,
        card=card.data if card else None,
        next=next_
    )

    return 200, {'next': next_}
Пример #49
0
def test_tags(db_conn, units_table):
    """
    Expect a unit to allow tags.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
        'body': 'Learn how to do this',
    })
    assert len(errors) == 0
    unit['tags'] = ['A', 'B']
    unit, errors = unit.save()
    assert len(errors) == 0
Пример #50
0
def get_latest_accepted(db_conn, kind, entity_id):
    """
    Given a kind and an entity_id, pull the latest accepted
    version out of the database.
    """

    if kind == 'card':
        card = Card.get_latest_accepted(db_conn, entity_id)
        return flip_card_into_kind(card)
    elif kind == 'unit':
        return Unit.get_latest_accepted(db_conn, entity_id)
    elif kind == 'set':
        return Set.get_latest_accepted(db_conn, entity_id)
Пример #51
0
def test_entity_id(db_conn, units_table):
    """
    Expect a unit to require an entity_id.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
        'body': 'Learn how to do this',
    })
    assert len(errors) == 0
    unit['entity_id'] = 'JFKLD1234'
    unit, errors = unit.save()
    assert len(errors) == 0
Пример #52
0
def test_previous(db_conn, units_table):
    """
    Expect a version previous_id to be a string or None.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
        'body': 'Learn how to do this',
    })
    assert len(errors) == 0
    unit['previous_id'] = 'AFJkl345'
    unit, errors = unit.save()
    assert len(errors) == 0
Пример #53
0
def get_latest_accepted(kind, entity_id):
    """
    Given a kind and an entity_id, pull the latest accepted
    version out of the database.
    """

    if kind == 'card':
        return Card.get_latest_accepted(entity_id)
        # TODO-1 This needs to also get the right card kind...
    elif kind == 'unit':
        return Unit.get_latest_accepted(entity_id)
    elif kind == 'set':
        return Set.get_latest_accepted(entity_id)
def test_order(db_conn, units_table):
    """
    Expect to order units by the number of depending units.
    """

    add_test_set(db_conn, units_table=units_table)
    units = Unit.list_by_entity_ids(db_conn, ["add", "subtract", "multiply", "divide"])
    units = order_units_by_need(units)
    entity_ids = [unit["entity_id"] for unit in units]
    assert entity_ids[0] == "add"
    assert entity_ids[1] in ("subtract", "multiply")
    assert entity_ids[2] in ("subtract", "multiply")
    assert entity_ids[3] == "divide"
Пример #55
0
def test_status(db_conn, units_table):
    """
    Expect a unit status to be a string.
    """

    unit, errors = Unit.insert({
        'name': 'Learn this',
        'body': 'Learn how to do this',
    })
    assert len(errors) == 0
    assert unit['status'] == 'pending'
    unit['status'] = 'accepted'
    unit, errors = unit.save()
    assert len(errors) == 0
def test_match_unit_dependents(db_conn, units_table):
    """
    Expect to order units by the number of depending units.
    """

    add_test_set(db_conn, units_table=units_table)
    units = Unit.list_by_entity_ids([
        'add', 'subtract', 'multiply', 'divide',
    ])
    deps = match_unit_dependents(units)
    assert len(deps['add']) == 3
    assert len(deps['multiply']) == 1
    assert len(deps['subtract']) == 1
    assert len(deps['divide']) == 0
def test_order(db_conn, units_table):
    """
    Expect to order units by the number of depending units.
    """

    add_test_set(db_conn, units_table=units_table)
    units = Unit.list_by_entity_ids([
        'add', 'subtract', 'multiply', 'divide',
    ])
    units = order_units_by_need(units)
    entity_ids = [unit['entity_id'] for unit in units]
    assert entity_ids[0] == 'add'
    assert entity_ids[1] in ('subtract', 'multiply')
    assert entity_ids[2] in ('subtract', 'multiply')
    assert entity_ids[3] == 'divide'