コード例 #1
0
ファイル: testmodels.py プロジェクト: xiaobaozi34/wordseer
    def test_model_unit(self):
        """Test to make sure that Unit is working properly.
        """

        unit_type = Property(name="unit_type", value="section")
        number = 1

        unit = Unit()

        unit.properties = [unit_type]
        unit.number = number

        assert unit.number == number

        sentence = Sentence()
        sentence.words = [Word(word="hello"), Word(word="world")]
        prop = Property(name="title", value="Hello World")

        unit.sentences.append(sentence)
        unit.properties.append(prop)

        assert unit.sentences == [sentence]
        assert unit.properties.all() == [unit_type, prop]

        unit.save()
        prop.save()

        retrieved_prop = Property.query.filter(Property.name=="title").\
            filter(Property.value == "Hello World").first()

        assert retrieved_prop.unit.type == "unit"
        assert retrieved_prop.unit.number == unit.number
コード例 #2
0
ファイル: routes.py プロジェクト: porcej/afd-dashboard-server
def _unit_new():
    """
    Creates a unit:
    params:
        name: Unit name
        home (optional): Unit's home station
        alert (optional): Station to alert for
    """
    if request.form:
        data = request.form
    else:
        data = request.args

    unit_name = data.get('name', '', type=str).upper()
    unit_home = data.get('home', '', type=str).upper()
    unit_alert = data.get('alert', '', type=str).upper()
    data = ''

    unit = Unit(name=unit_name)
    if unit_home != '':
        unit.home = Station.query.filter_by(name=unit_home).first()
    if unit_alert != '':
        unit.alert = Station.query.filter_by(name=unit_alert).first()
    try:
        db.session.add(unit)
        db.session.commit()
        socketio.emit('unit_update', namespace='/afd')
        return jsonify(result='success', \
            message='Unit ' + unit.name + ' added.')
    except exc.IntegrityError:
        db.session.rollback()
        return jsonify(result='error',\
         message='Unable to add ' + unit.name + '.')
コード例 #3
0
ファイル: manage.py プロジェクト: CodeLexis/briceicle-test
def pump_units_table():
    print('units')

    units = ['Integrations', 'UI/UX', 'Mobile', 'Network', 'Systems']

    for unit in units:
        Unit(name=unit).save()
コード例 #4
0
    def test_model_document(self):
        """Test to make sure that Document is working properly.
        """

        d1 = Document(title="test")
        d1.save()

        assert d1.type == "document"

        u1 = Unit()
        u1.save()

        d1.children.append(u1)
        d1.save()

        assert d1.children == [u1]
        assert u1.parent == d1
コード例 #5
0
ファイル: testmodels.py プロジェクト: xiaobaozi34/wordseer
    def test_model_document(self):
        """Test to make sure that Document is working properly.
        """

        d1 = Document(title="test")
        d1.save()

        assert d1.type == "document"

        u1 = Unit()
        u1.save()

        d1.children.append(u1)
        d1.save()

        assert d1.children == [u1]
        assert u1.parent == d1
コード例 #6
0
ファイル: routes.py プロジェクト: itsDrac/twin-book
def home():
    form = UnitForm()
    unites = Unit.query.filter_by(company_id=current_user.id)
    if form.validate_on_submit():
        unit = Unit(name=form.name.data, company_id=current_user.id)
        db.session.add(unit)
        db.session.commit()
        return redirect(url_for('unit.home'))
    return render_template('unit.html', unites=unites, form=form)
コード例 #7
0
def deploy():
    """Run deployment tasks."""
    from flask_migrate import upgrade

    # migrate database to latest revision
    upgrade()
    # create all tables
    db.create_all()

    # insert default values
    ShopDetails.insert_shop_details()
    Admin.insert_default_admin()
    StatusCatalog.insert_order_status()
    PaymentMethod.insert_payment_method()
    PaymentStatus.insert_payment_status()

    Unit.insert_units()
    DeliveryCharge.insert_default_charge()
    WeightDeliveryCharge.insert_default_charge()
    ProductType.insert_categories()
コード例 #8
0
    def test_model_unit(self):
        """Test to make sure that Unit is working properly.
        """

        unit_type = Property(name="unit_type", value="section")
        number = 1

        unit = Unit()

        unit.properties = [unit_type]
        unit.number = number

        assert unit.number == number

        sentence = Sentence()
        sentence.words = [Word(lemma="hello"), Word(lemma="world")]
        prop = Property(name="title", value="Hello World")

        unit.sentences.append(sentence)
        unit.properties.append(prop)

        assert unit.sentences == [sentence]
        assert unit.properties.all() == [unit_type, prop]

        unit.save()
        prop.save()

        retrieved_prop = Property.query.filter(Property.name=="title").\
            filter(Property.value == "Hello World").first()

        assert retrieved_prop.unit.type == "unit"
        assert retrieved_prop.unit.number == unit.number
コード例 #9
0
def create_module_for_config_tree(type='', id=0):
    flash('New Node Created ****** type: '+type+' id: '+str(id))

    if type == 'semester':
        semester = Semester.query.get_or_404(id)
        # create new unit
        rand = str( random.randint(1,999) )
        unit = Unit(
            semester_id=id, 
            name='name-'+rand, 
            display_name='display_name-'+rand,
            order=1)
        db.session.add(unit)
        db.session.commit()
        return redirect( url_for('conf_semester', semester_id=semester.id) )

    if type == 'unit':
        unit = Unit.query.get_or_404(id)
        semester = unit.semester
        # create new module
        rand = str( random.randint(1,999) )
        module = Module(
            unit_id=id, 
            code='code-'+rand, 
            name='name-'+rand, 
            display_name='display_name-'+rand,
            order=1)
        db.session.add(module)
        db.session.commit()
        return redirect( url_for('conf_semester', semester_id=semester.id) )

    if type == 'module':
        module = Module.query.get_or_404(id)
        semester = module.unit.semester

        # create new percentage
        rand = str( random.randint(1,999) )
        percentage = Percentage(
            module_id=id, 
            # name='name-'+rand, 
            # percentage= ,
            order=1)
        db.session.add(percentage)
        db.session.commit()

        return redirect( url_for('conf_semester', semester_id=semester.id) )

    return 'type not catched'
コード例 #10
0
def store_units(unit_list, type_name):
    type_record = get_unit_type(type_name)

    if type_record is None:
        print("Error: Unit type " + type_name + " is not found.\n")
    else:
        for unit in unit_list:
            unit_record = Unit.query.filter(Unit.name == unit).first()

            if unit_record is None:
                unit_record = Unit(type_record.id, unit)
                db.session.add(unit_record)
                db.session.commit()
            else:
                print("Unit " + unit + " of " + type_name +
                      " measurement has already been added. Skipping\n")
コード例 #11
0
def duplicate_unit(unit, new_semester):
    new_unit = Unit(
        name = unit.name,
        display_name = unit.display_name,
        unit_coefficient = unit.unit_coefficient,
        is_fondamental = unit.is_fondamental,
        semester_id = new_semester.id,
        order = unit.order
    )
    db.session.add(new_unit)
    db.session.commit()

    # add children
    msg_modules = ''
    for module in unit.modules:
        msg_modules = msg_modules +  duplicate_module(module, new_unit) + ' - '

    return ' U: ' + str(new_unit.id) + ' [' + msg_modules + ']'
コード例 #12
0
ファイル: routes.py プロジェクト: cgmbaer/myapp
def add_unit():
    if request.json['id'] > 0:
        u = Unit.query.get(request.json['id'])
        u.name = request.json['name']
        u.group = request.json['group']
        u.factor = request.json['factor']
    else:
        u = Unit(name=request.json['name'],
                 group=request.json['group'],
                 factor=request.json['factor'])
        db.session.add(u)
    try:
        db.session.commit()
        return jsonify({'id': u.id})

    except IntegrityError as err:
        db.session.rollback()
        return jsonify({'error': 'Exisitert bereits!'})
コード例 #13
0
ファイル: questions.py プロジェクト: CodeLexis/briceicle-test
    def post(self):
        data = request.form

        unit = Unit.get(name=data.get('unit'))

        yes_count = 0

        for question, answer in data.items():
            question = Question.get(body=question)

            if question:
                Answer(body=answer, question=question, unit=unit).save()

                if answer == 'YES':
                    yes_count += 1

        session['taken'] = True
        session['score'] = yes_count

        return redirect(url_for('blueprints.web.results', score=yes_count))
コード例 #14
0
    def test_insert_product(self):
        pt = ProductType(type_name="Pulses")

        unit = Unit(unit_name="Kilogram", unit_short="kg")

        db.session.add(pt)
        db.session.add(unit)
        db.session.commit()

        unit = Unit.query.filter_by(unit_name="Kilogram").first()
        producttype = ProductType.query.filter_by(type_name="Pulses").first()
        p = Product(
            product_name="rice",
            product_description="basmatic rice",
            price_per_unit=123,
            product_items=producttype,
            unit_items=unit,
        )
        db.session.add(p)
        db.session.commit()
        self.assertTrue(
            Product.query.filter_by(product_name="rice").first() == p)
コード例 #15
0
def demand(id: int):
    if request.method == "GET":
        return jsonify(Demand.query.get_or_404(id).to_dict())
    if request.method == "PUT":

        demand: Demand = Demand.query.get_or_404(id)
        if not request.is_json:
            raise errors.InvalidUsage(
                "Incorrect request format! Request data must be JSON"
            )
        data: Union[dict, None] = request.get_json(silent=True)
        if not data:
            raise errors.InvalidUsage(
                "Invalid JSON received! Request data must be JSON"
            )

        if "demand" in data:
            new_demand: dict = data["demand"]
        else:
            raise errors.InvalidUsage("'demand' missing in request data")

        # Validate demand
        check_demand(new_demand)

        # Update values in DB
        unit = Unit.query.filter_by(name=new_demand["unit"]).first()
        if unit is None:
            unit = Unit(name=new_demand["unit"])
            logging.debug(f"Created unit {unit}")

        demand.latitude = new_demand["latitude"]
        demand.longitude = new_demand["longitude"]
        demand.quantity = new_demand["quantity"]
        demand.cluster_id = new_demand["cluster_id"]
        demand.unit = unit

        db.session.commit()

        return make_response(jsonify(demand.to_dict()), 200)
コード例 #16
0
ファイル: routes.py プロジェクト: Littlebus/compNet
def unit_add():
    form = UnitForm()
    if form.validate_on_submit():
        unit = Unit(name=form.name.data,
                    comment=form.comment.data,
                    gender=form.gender.data,
                    height=form.height.data,
                    weight=form.weight.data,
                    age=form.age.data,
                    owner=current_user)
        db.session.add(unit)
        db.session.commit()
        flash('新病人已经被添加', category='info')
        return redirect_back()
    page = request.args.get('page', 1, type=int)
    pagination = Unit.query.order_by(Unit.timestamp.desc()).paginate(
        page, app.config['UNITS_PER_PAGE_ADD'], False)
    units = pagination.items
    return render_template('add_unit.html',
                           title='Add Unit',
                           form=form,
                           units=units,
                           pagination=pagination)
コード例 #17
0
def init_units():
    sample_units = ["miles", "pallets", "kilometres", "grams"]
    for unit in sample_units:
        db.session.add(Unit(name=unit))
    db.session.commit()
コード例 #18
0
def unitManager():

    message = ""
    user = User.query.filter_by(email=current_user.email).first_or_404()
    if (user.isTeacher == False):
        return redirect(url_for('dashboard'))
    else:
        form = CreateUnitForm()
        formReset = ResetDatabaseForm()
        if form.validate_on_submit():
            unit = Unit(name=form.name.data,
                        description=form.description.data,
                        mark1Criteria=form.mark1Criteria.data,
                        mark2Criteria=form.mark2Criteria.data,
                        mark3Criteria=form.mark3Criteria.data,
                        mark4Criteria=form.mark4Criteria.data)
            db.session.add(unit)
            db.session.commit()
            return redirect(url_for('unitManager'))
        if formReset.validate_on_submit():
            folder = 'app/static/music/'
            for filename in os.listdir(folder):
                dirToFile = folder + filename
                os.remove(dirToFile)
            if (formReset.passwordResetter.data == "SUPERHARDPASSWORD"):
                users = User.query.filter_by(isTeacher=False).all()
                for user in users:
                    db.session.delete(user)
                units = Unit.query.all()
                for unit in units:
                    db.session.delete(unit)
                tests = Test.query.all()
                for test in tests:
                    db.session.delete(test)

                questions = Question.query.all()
                for question in questions:
                    db.session.delete(question)

                answers = Answer.query.all()
                for answer in answers:
                    db.session.delete(answer)

                feedbacks = Feedback.query.all()
                for feedback in feedbacks:
                    db.session.delete(feedback)

                testmarks = TestMark.query.all()
                for testmark in testmarks:
                    db.session.delete(testmark)

                db.session.commit()
                flash("Database Successfully cleaned")
                return redirect(url_for('unitManager'))
            else:
                flash("Password is incorrect")
                return redirect(url_for('unitManager'))
        units = Unit.query.all()
        return render_template('unitManager.html',
                               title='Unit Manager',
                               units=units,
                               form=form,
                               formReset=formReset)
コード例 #19
0
def iterate_units(data: dict):
    for unit in data['units'][:get_count()]:
        yield Unit(unit=unit)
コード例 #20
0
 def test_insert_Units(self):
     unit = Unit(unit_name="Kilogram", unit_short="kg")
     db.session.add(unit)
     db.session.commit()
     self.assertTrue(
         Unit.query.filter_by(unit_name="Kilogram").first() == unit)
コード例 #21
0
ファイル: db_populate.py プロジェクト: sredmond/apc
with open('app/static/json/carousel.json') as f:
    carousel = json.loads(f.read())

with open('app/static/json/references.json') as f:
    references = json.loads(f.read())

# Seconds since epoch at which a new PST day w/ physics begins
epoch_day_offsets = [timegm(time.strptime(date, "%m/%d/%y")) for date in dates]

# Used to iterate through our potential times
time_iter = iter(epoch_day_offsets)

# Populate the lessons into their respective units, including dates
for unit in content:
    unit_model = Unit()
    unit_model.title = unit.get('title')
    unit_model.description = unit.get('description')
    for lesson in unit['lessons']:
        lesson_model = Lesson()
        for item in lesson['items']:
            lesson_model.addItem(item)
        lesson_model.homework=lesson.get('homework')
        lesson_model.additional = lesson.get('additional')

        # Add time values
        t = time_iter.next() # Seconds since epoch of a new UTC day - could throw an error
        pst_dt = datetime.utcfromtimestamp(t) # Datetime representing the local date and time
        lesson_model.epoch_time = t + pst_offset # Seconds since epoch of a new PST day
        lesson_model.pst_datetime = pst_dt
        lesson_model.day_of_week = int(pst_dt.strftime("%w")) # 1 = Monday, 2 = Tuesday, ..., 5 = Friday
コード例 #22
0
def demands():

    if request.method == "GET":
        return jsonify([demand.to_dict() for demand in Demand.query.all()])
        # return jsonify(Demand.query.all())

    if request.method == "POST":
        if not request.is_json:
            raise errors.InvalidUsage(
                "Incorrect request format! Request data must be JSON"
            )

        data = request.get_json(silent=True)
        if not data:
            raise errors.InvalidUsage(
                "Invalid JSON received! Request data must be JSON"
            )

        if "demands" in data:
            demands = data["demands"]
        else:
            raise errors.InvalidUsage("'demands' missing in request data")

        if not demands:
            raise errors.InvalidUsage("'demands' is empty")

        params = ["latitude", "longitude", "cluster_id", "unit", "quantity"]

        # Checking if each element is valid
        for demand in demands:

            error = check_demand(demand)
            if error:
                return error

            # Filtering the dict for safety
            demand = {param: demand[param] for param in params}

        demand_entries = []

        # Adding demands to database
        for demand in demands:
            unit = Unit.query.filter_by(name=demand["unit"]).first()
            if unit is None:
                unit = Unit(name=demand["unit"])
                logging.debug(f"Created unit {unit}")
            demand_entry = Demand(
                latitude=demand["latitude"],
                longitude=demand["longitude"],
                quantity=demand["quantity"],
                cluster_id=demand["cluster_id"],
                unit=unit,
            )
            db.session.add(demand_entry)
            demand_entries.append(demand_entry)

        db.session.commit()

        for demand, demand_entry in zip(demands, demand_entries):
            demand["id"] = demand_entry.id

        # for unit in data['add_units']:
        #     print(f"Adding unit '{unit}'")
        #     un = Unit(name=unit)
        #     db.session.add(un)
        #     db.session.commit()

        return make_response(jsonify(demands), 201)