Esempio n. 1
0
def implementation_new(fraction_id, year_of_growth, product_id):
    """formular to enter a new vegetables growing action """
    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)
    diversity = DiversityModel(product_id, fraction_id)
    cultivation = CultivationModel()
    growkind = GrowKindModel()
    seed = SeedModel()
    contacts = ContactsModel()

    #productlist = fraction.get_productlist()
    productlist = fraction.cheata_menue()  #implement list2nested!!!

    the_product = product.get_data()
    the_diversity = diversity.get()

    form = VegetablesImplementationForm(request.form)

    #before validating choices must be given
    form.diversity_id.choices = diversity.get_wtform_choices()
    form.area_id.choices = fraction.area.get_wtform_choices()
    form.grow_kind_id.choices = growkind.get_wtform_choices()
    form.unit_of_seed.choices = seed.get_wtform_unit_choices()
    form.art_of_cultivation.choices = cultivation.get_wtform_choices()
    form.company_id.choices = contacts.get_wtform_choices()

    if form.validate_on_submit():

        new_id = implementation_model.insert(form)
        print(">>>>>>>>> new_id: " + str(new_id))
        if new_id:
            flash(u'Erfolgreich angelegt:#' + str(new_id), 'success')

            return redirect(
                url_for('.implementation_by_product_id',
                        fraction_id=fraction.fraction_id,
                        year_of_growth=year_of_growth,
                        product_id=product.product_id,
                        pivot=new_id))
        else:
            abort(500)

    #manualy poke initial form.values with the_product specs
    form.name.data = the_product['item_name']
    form.fraction_id.data = fraction.fraction_id
    form.year_of_growth.data = year_of_growth
    form.product_id.data = the_product['product_id']

    form.grow_kind_id.data = (the_product['grow_kind_id'])

    form.planting_interval.data = the_product['planting_interval']

    return render_template('vegetables/implementation_input_form.html',
                           form=form,
                           fraction=fraction,
                           productlist=productlist,
                           the_product=the_product,
                           the_diversity=the_diversity,
                           year_of_growth=year_of_growth,
                           flag='new')
Esempio n. 2
0
  def post(self):
    try:
      
      self.response.headers['Content-Type'] = 'text/json'

      try:
        jdata = json.loads(self.request.body)
      except ValueError, e:
        log.debug(e)
        self.response.set_status(404)
        msg = {'success': False, 'message': "Failed to read JSON body"}
        self.response.write(json.dumps(msg))
        return
    
      new_product = ProductModel(
        product_id=jdata['product_id'],
        manufacturer_id=jdata['manufacturer_id'],
        name=jdata['name'],
        price=jdata['price'],
        qty=jdata['qty'] or 0
      )
      
      result = new_product.put()
      
      if result:
        entity = result.get().to_dict()
        entity['success'] = True
        self.response.set_status(201)
        self.response.write(json.dumps(entity))
Esempio n. 3
0
def implementation_edit(implementation_id):
    """update"""
    data = implementation_model.get_by_id(implementation_id)

    fraction_id = data['fraction_id']
    product_id = data['product_id']
    year_of_growth = data['year_of_growth']

    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)
    diversity = DiversityModel(product_id, fraction_id)
    cultivation = CultivationModel()
    growkind = GrowKindModel()
    seed = SeedModel()
    contacts = ContactsModel()

    the_product = product.get_data()
    #productlist = fraction.get_first_product_list()
    productlist = fraction.cheata_menue()  #implement list2nested!!!

    the_diversity = diversity.get()
    form = VegetablesImplementationForm(request.form, data=data)  #obj=data
    #before validating choices must be given
    form.diversity_id.choices = diversity.get_wtform_choices()
    form.area_id.choices = fraction.area.get_wtform_choices()
    form.art_of_cultivation.choices = cultivation.get_wtform_choices()
    form.grow_kind_id.choices = growkind.get_wtform_choices()
    form.unit_of_seed.choices = seed.get_wtform_unit_choices()
    form.company_id.choices = contacts.get_wtform_choices()

    if form.validate_on_submit():

        check = implementation_model.update(form, implementation_id)

        if check == 1:
            flash(u'Erfolgreich geändert', 'success')
        if check == 0:
            flash(u'nichts verändert', 'primary')
        return redirect(
            url_for('.implementation_by_product_id',
                    fraction_id=fraction.fraction_id,
                    year_of_growth=year_of_growth,
                    product_id=product.product_id,
                    pivot=implementation_id))
    return render_template('vegetables/implementation_input_form.html',
                           form=form,
                           fraction=fraction,
                           productlist=productlist,
                           the_product=the_product,
                           the_diversity=the_diversity,
                           year_of_growth=year_of_growth,
                           data=data,
                           flag='edit')
Esempio n. 4
0
    def mutate(root, info, name, price):
        product = ProductModel(name=name, price=price)
        db_session.add(product)
        db_session.commit()

        ok = True
        return CreateProduct(product=product, ok=ok)
Esempio n. 5
0
def conception_by_product_id(fraction_id, year_of_growth, product_id):
    """render all sets (Sätze) of one product"""
    start = time.time()  #performence time start
    if request.args.get('pivot'):
        pivot = int(request.args.get('pivot'))  #or_test (trinity operator)
    else:
        pivot = 0

    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)
    transact = TransactionModel(fraction_id)

    #productlist = fraction.get_product_list()
    productlist = fraction.cheata_menue()  #implement list2nested!!!
    the_product = product.get_data()  #:one dict

    area_info = conception_model.get_involved_areas(fraction_id,
                                                    year_of_growth)

    #t=transact.get_transactions(product_id)
    #print('Transactions:'+str(t))

    #and the_product[0]['has_data'] == fraction_id

    if the_product['has_data'] == fraction_id:

        entries = conception_model.get_product_by_id(fraction_id,
                                                     year_of_growth,
                                                     product_id)
        summary = conception_model.get_summary_by_id(fraction_id,
                                                     year_of_growth,
                                                     product_id)
        end = time.time()  #performence time end
        print('Performence conception.by_product_id:' + str(end - start) +
              'sec.')
        return render_template('vegetables/conception_one.html',
                               entries=entries,
                               summary=summary,
                               productlist=productlist,
                               fraction=fraction,
                               the_product=the_product,
                               area_info=area_info,
                               year_of_growth=year_of_growth,
                               pivot=pivot)

    elif the_product['tree_diff'] != 1 or the_product['has_data'] < 0:
        return str(the_product)
Esempio n. 6
0
 def mutate(cls, _, args, context, info):
     product = ProductModel(name=args.get('name'),
                            description=args.get('description'),
                            author_id=args.get('author_id'),
                            category_id=args.get('category_id'))
     db_session.add(product)
     db_session.commit()
     ok = True
     return createProduct(product=product, ok=ok)
Esempio n. 7
0
 def create(self, product: ProductModel):
     db_tuple = product.toDB()
     try:
         self.c.execute("INSERT INTO products VALUES (?,?,?,?)", db_tuple)
         self.db.commit()
     except sqlite3.IntegrityError:
         self.db.rollback()
         raise sqlite3.IntegrityError(
             f'product.sku: {product.sku} already exists in db!')
Esempio n. 8
0
class ProductHandler():
    def __init__(self):
        self._model = ProductModel()
        self._view = ProductView()

    def getProductPage(self, path, alias=None, product_id=None):
        product = self._model.getProduct(alias, product_id)
        self._view.setParam('product', product)
        self._view.setLayout('beta/layout/layout.html')
        page = self._view.render()
        return page
Esempio n. 9
0
def implementation_by_product_id(fraction_id, year_of_growth, product_id):
    """render all sets (Sätze) of one procuct that were realised
    by one fraction in a year
    """
    #is one element of entries pivot?
    if request.args.get('pivot'):
        pivot = int(request.args.get('pivot'))
    else:
        pivot = 0

    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)

    productlist = fraction.cheata_menue()  #implement list2nested!!!
    #productlist = fraction.get_product_list()

    the_product = product.get_data()  #one dict

    #if the_product['tree_diff'] == 1: # is leaf node
    if the_product['has_data'] == fraction_id:

        imp_entries = implementation_model.get_product_by_id(
            fraction_id, year_of_growth, product_id)
        con_entries = conception_model.get_product_by_id(
            fraction_id, year_of_growth, product_id)
        imp_summary = implementation_model.get_summary_by_id(
            fraction_id, year_of_growth, product_id)
        con_summary = conception_model.get_summary_by_id(
            fraction_id, year_of_growth, product_id)
        return render_template('vegetables/implementation_one.html',
                               con_entries=con_entries,
                               imp_entries=imp_entries,
                               con_summary=con_summary,
                               imp_summary=imp_summary,
                               productlist=productlist,
                               fraction=fraction,
                               the_product=the_product,
                               year_of_growth=year_of_growth,
                               pivot=pivot)
    elif the_product['tree_diff'] != 1 or the_product['has_data'] < 0:
        return str(the_product)
Esempio n. 10
0
def save_product_to_account(product, account_id, token):
    # type: (Product, str) -> None
    ProductModel(key=ndb.Key(ProductModel,
                             product.product_id,
                             parent=ndb.Key(AccountModel, account_id)),
                 product_name=product.product_name,
                 product_id=product.product_id,
                 photo_url='https://{}.joinposter.com'.format(account_id) +
                 product.photo_url,
                 category_name=product.category_name).put()
    for spot in product.spots:
        spots.sync_spot(spot, account_id, product.product_id, token)
class NonlinearBikeShareModel:
  def __init__(self, train):
    self.terms = [Amplitude, Quantity]
    self.model = ProductModel(train, self.terms)

  def __call__(self, beta):
    """
    Return error and gradient of error rather than prediction for
    optimization.
    """
    f, grad_f = self.model.fit(beta, grad=True)
    e, grad_e = self.error(f, grad_f)

    if numpy.isnan(e):
      grad_e[:] = 0.0
      return 1.0e6, grad_e

    return e, grad_e

  def show(self, beta):
    return self.model.show(beta)

  def predict(self, test, beta):
    return self.model(test, beta, grad=False)

  def count(self, beta):
    return self.model.fit(beta, grad=False)

  def error(self, count, grad=None):
    actual = self._train['count'].values
    n = len(count)
    evec = numpy.log(1.0 + actual) - numpy.log(1.0 + count)
    e = numpy.sqrt(numpy.dot(evec, evec) / float(n))

    if grad is not None:
      grad_e = -numpy.dot(evec / (1.0 + count), grad) / (e * float(n))
      return e, grad_e

    return e
Esempio n. 12
0
  def get(self):
    try:

      self.response.headers['Content-Type'] = 'text/json'

      entities = ProductModel().list()
      
      response = {"success": True, "entities":{}}

      for entity in entities.fetch():
        key_id = entity.key.id()
        response['entities'][key_id] = (entity.to_dict())

      self.response.write(json.dumps(response))

    except Exception, e: 
      # Should Log to console - exception message
      log.debug(e)
      self.response.write(
        json.dumps({
          "success": False, 
          "message": "ProductsViewHandler Exception: " + e.message
      }))
Esempio n. 13
0
def product_view(request):
    user = check_validation(request)
    if user:
        if request.method == 'POST':
            form = ProductForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('image')
                caption = form.cleaned_data.get('caption')
                review = ProductModel(user=user, image=image, caption=caption)
                review.save()

                path = str(BASE_DIR + '/' + product.image.url)

                client = ImgurClient(CLIENT_ID, CLIENT_SECRET)
                product.image_url = client.upload_from_path(path, anon=True)['link']
                product.save()

                return redirect('/products/')

            else:
                return render(request, 'feed.html', {'form': form})
        else:
            return redirect('/post/')
Esempio n. 14
0
def setupDB():
    # This function sets up the database. After processing the input file function and getting each dictionary
    # the dataframes need to be put into the SQL database for the information to be used later and throughout
    # each simulation

    num_rows, num_columns, num_drones, max_time, max_cargo, products, wh_list, order_list, order_product, warehouse_products = read_file(
        './assets/busy_day.in')
    dbms = hash_database.HashDataBase(
        hash_database.SQLITE,
        dbname='hash.sqlite')  # Creating database session to call on
    dbms.create_db_tables()
    Session = sessionmaker(bind=dbms.db_engine)
    session = Session()

    # add each product, order, order products, warehouse, and warehouse products to database
    for product in products:
        session.add(
            ProductModel(**product))  # append database with product types
    for order in order_list:
        session.add(OrderModel(**order))  # append database with order ids
    for order in order_product:
        # session.add(order_product_model.OrderModel(**order))
        order_id = order["order_id"]
        for key in dict(order["items"]).keys(
        ):  # for each product of the orders, add with an id, qty, weight, etc
            order["items"][key]
            session.add(
                OrderProductModel(      # order product model file arguments
                    **{
                        "order_id":order_id,
                        "product_id": key,
                        "qty": order["items"][key]
                    }
                )
            )
    for warehouse in wh_list:
        session.add(
            WarehouseModel(**warehouse))  # append database with warehouse ids

    for wh_product in warehouse_products:  # append database with warehouse product ids and quantities
        for wh_pr in wh_product:
            session.add(WarehouseProductModel(**wh_pr))
    session.commit()
Esempio n. 15
0
def createProduct(pr):
    try:
        pricing = pr["pricing"]
        price = pricing["price"]
        if not price:
            print("no price found for:" + pr["productIdAsString"])
            return

        inkl = price["amountIncl"]
        insteadOfPrice = findInseadOfPrice(pricing)
        model = ProductModel(pr["id"], pr["productIdAsString"], pr["name"],
                             pr["fullName"], pr["simpleName"], inkl,
                             insteadOfPrice)

        return model

    except (Exception) as error:
        print("unmarshal" + str(error))
        print(pr)
        logger.error('error' + str(error))
Esempio n. 16
0
    def post(self):
        print("Post request received")
        print(self)
        print(dir(self))
        print(dir(request))
        print("------------------------")
        print(request.url)
        print(request.headers)
        print(request.get_data())
        print(request.json)
        print(request.content_type)
        print(request.content_length)
        request_dict = request.get_json()
        print(request_dict)
        parser = reqparse.RequestParser()
        parser.add_argument('name',
                            type=str,
                            required=True,
                            help='Name cannot be blank!')
        parser.add_argument('durability',
                            type=int,
                            required=True,
                            help='Durability cannot be blank!')
        parser.add_argument('category',
                            type=str,
                            required=True,
                            help='Product category cannot be blank!')
        print("parser arguments added")
        args = parser.parse_args()
        print(args)
        product = ProductModel(name=args['name'],
                               durability=args['durability'],
                               manufacture_date=datetime.now(utc),
                               category=args['category'])

        product_manager.insert_message(product)
        return product, status.HTTP_201_CREATED
Esempio n. 17
0
  def put(self, id):
    try:

      self.response.headers['Content-Type'] = 'text/json'

      if not id:
        self.response.set_status(204)
        self.response.write("{\"id value missing from url. aborted update.\"}")
        return

      try:
        jdata = json.loads(self.request.body)
      except ValueError, e:
        log.debug(e)
        self.response.set_status(404)
        msg = {'success': False, 'message': "Failed to read JSON body"}
        self.response.write(json.dumps(msg))
        return
    
      entity = ProductModel(id=int(id)).get_by_id(int(id))
      
      entity.product_id           = jdata['product_id']
      entity.manufacturer_id      = jdata['manufacturer_id']
      entity.name                 = jdata['name']
      entity.qty                  = jdata['qty']
      entity.price                = jdata['price']
      result = entity.put()

      if result:
        rdata = {}
        rdata['success'] = True
        rdata['entity'] = {
          "product_id":       entity.product_id,
          "manufacturer_id":  entity.manufacturer_id,
          "name":             entity.name,
          "qty":              entity.qty
        }
        self.response.set_status(200)
        self.response.write(json.dumps(rdata))
Esempio n. 18
0
def remove_for_account(account_name):
    product_ids = ProductModel.allocate_ids(parent=ndb.Key(
        AccountModel, account_name),
                                            max=1000)  # fixme later
    ndb.delete_multi(product_ids)
Esempio n. 19
0
 def search(self, **kwargs):
     query = 'SELECT * FROM products WHERE (' + self.build_query(
         kwargs) + ')'
     print(query)
     results = self.c.execute(query)
     return [ProductModel.fromDB(r) for r in results.fetchall()]
Esempio n. 20
0
from models import SPHModel, GP3DModel, LogSpaceModel, HybridModel, ProductModel
from plot import Plot

df = data.get_data()
df = data.filter(df, 
        max_age = dt.datetime.now()-dt.timedelta(minutes=60),
        required_metrics = ['mufd', 'md', 'fof2'],
        min_confidence = 0.01
        )

mufd = df.mufd.values

model = ProductModel(
        LogSpaceModel( # fof2
            HybridModel(SPHModel(), 0.8, GP3DModel(), 0.9)
        ),
        LogSpaceModel( # md
            HybridModel(SPHModel(), 0.8, GP3DModel(), 0.9)
        )
    )

model.train(df, df.fof2.values, df.md.values)
pred = model.predict(df['station.longitude'].values, df['station.latitude'].values)

error = pred - mufd
print(mufd)
print(pred)
print(error)
print(np.sqrt(np.mean(error ** 2)))

plt = Plot('mufd', dt.datetime.now(timezone.utc))
plt.scale_mufd()
Esempio n. 21
0
def implementation_create_from_conception(conception_id):
    """provides a form with prefilled conception values"""
    conception_data = conception_model.get_by_id(conception_id)

    fraction_id = conception_data['fraction_id']
    product_id = conception_data['product_id']
    year_of_growth = conception_data['year_of_growth']

    fraction = FractionModel(fraction_id)
    the_product = ProductModel(product_id, fraction_id)
    productlist = fraction.cheata_menue()  #implement list2nested!!!

    the_diversity = DiversityModel(product_id, fraction_id)
    cultivation = CultivationModel()
    growkind = GrowKindModel()
    seed = SeedModel()
    contacts = ContactsModel()

    form = VegetablesImplementationForm(request.form)

    #before validating choices must be given
    form.diversity_id.choices = the_diversity.get_wtform_choices()
    form.area_id.choices = fraction.area.get_wtform_choices()
    form.grow_kind_id.choices = growkind.get_wtform_choices()
    form.unit_of_seed.choices = seed.get_wtform_unit_choices()
    form.art_of_cultivation.choices = cultivation.get_wtform_choices()
    form.company_id.choices = contacts.get_wtform_choices()

    if form.validate_on_submit():

        new_id = implementation_model.insert(form)
        print(">>>>>>>>> new_id: " + str(new_id))
        if new_id:
            flash(u'Durchführung erfolgreich angelegt:#' + str(new_id),
                  'success')
            upd = conception_model.lock_entrie(conception_id)
            if upd == 1:
                flash(u'Planungseintrag archiviert', 'primary')

            return redirect(
                url_for('.implementation_by_product_id',
                        fraction_id=fraction.fraction_id,
                        year_of_growth=year_of_growth,
                        product_id=the_product.product_id,
                        pivot=new_id))
        else:
            abort(500)
    #manualy poke form.field.data with conception_data
    #rule number one: NEVER map manualy
    #just data=conception_data
    form.conception_id.data = conception_data['id']
    form.fraction_id.data = conception_data['fraction_id']
    form.product_id.data = conception_data['product_id']
    form.year_of_growth.data = conception_data['year_of_growth']
    form.name.data = conception_data['name']
    form.diversity_id.data = conception_data['diversity_id']
    form.area_id.data = conception_data['area_id']
    form.grow_kind_id.data = conception_data['grow_kind_id']
    form.art_of_cultivation.data = conception_data['art_of_cultivation']
    form.amount_of_grow_kind_units.data = conception_data[
        'amount_of_grow_kind_units']
    form.hint.data = conception_data['hint']
    form.amount_of_plants.data = conception_data['amount_of_plants']
    form.planting_interval.data = conception_data['planting_interval']
    form.length_of_field.data = conception_data['length_of_field']
    form.square_of_field.data = conception_data['square_of_field']
    form.plants_per_square.data = conception_data['plants_per_square']

    return render_template('vegetables/implementation_input_form.html',
                           form=form,
                           fraction=fraction,
                           productlist=productlist,
                           the_product=the_product,
                           the_diversity=the_diversity,
                           year_of_growth=year_of_growth,
                           conception_data=conception_data,
                           flag='cfc')
Esempio n. 22
0
 def get_by_sku(self, sku):
     p = self.c.execute('SELECT * FROM products WHERE sku=?', (sku, ))
     try:
         return ProductModel.fromDB(p.fetchall()[0])
     except IndexError:
         return False
Esempio n. 23
0
 def list(self):
     p = self.c.execute('SELECT * FROM products')
     try:
         return [ProductModel.fromDB(product) for product in p.fetchall()]
     except Exception as e:
         raise e
Esempio n. 24
0
核心思想是: 分层和解耦, 提高了程序的扩展性、可重用性、可维护性和可读性

模型-视图-控制器模式是应用到面向对象编程的 SoC(关注点分离)原则

是一种非常通用的设计模式,虽然我私人会认为不算是严格的设计模式,更像是一种指导架构的架构模式。

- Model(模型) 是核心的部分, 代表着应用的信息本源, 包含和管理(业务)逻辑, 数据和状态以及应用的规则.
- View(视图) 是模型的可视化表现, 它只决定怎么展示数据, 并不处理数据, 多为前端应用
- Controller(控制器) 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。


目前我了解到的, 基本上所有流行的Web框架例如 PHP中的 Laravel和Yii, Python中的Django
都有用到MVC或者其变种, 例如Django的MVT( Model, View, Template)
    View 视图, 和MVC里的C控制器功能相同, 接收请求, 处理业务逻辑
    Template 模板, 与MVC里的V视图功能相同, 有点不同的是返回html涉及到的模板语言会不同, 基本作用都是展示数据
    而Urlconf, 更像是控制器, 根据正则url匹配不同的视图来响应请求
"""

from models import ProductModel
from views import ProductView
from controllers import Controller

if __name__ == '__main__':
    model = ProductModel()
    view = ProductView()
    controller = Controller(model, view)

    controller.show_item_list()
    controller.show_item_info('milk')
    controller.show_item_info('apple')
Esempio n. 25
0
 def mutate(self, info, **kwargs):
     product = ProductModel(**kwargs)
     product.save()
     return CreateProduct(product=product)
Esempio n. 26
0
def conception_edit(conception_id):
    """update an entrie by id"""
    #next = get_redirect_target()

    data = conception_model.get_by_id(conception_id)

    fraction_id = data['fraction_id']
    product_id = data['product_id']
    year_of_growth = data['year_of_growth']

    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)
    diversity = DiversityModel(product_id, fraction_id)
    cultivation = CultivationModel()
    growkind = GrowKindModel()
    seed = SeedModel()
    #area = AreaModel()
    productlist = fraction.cheata_menue()  #implement list2nested!!!
    #productlist = fraction.get_product_list()

    the_product = product.get_data()
    the_diversity = diversity.get()
    summary = conception_model.get_summary_by_id(fraction_id, year_of_growth,
                                                 product_id)
    #aside
    conceptions_micro = conception_model.get_micro_by_product_id(
        fraction_id, year_of_growth, product_id)

    form = VegetablesConceptionForm(request.form, data=data)  #obj=data
    #before validating choices must be given
    form.diversity_id.choices = diversity.get_wtform_choices()
    form.area_id.choices = fraction.area.get_wtform_choices()
    form.grow_kind_id.choices = growkind.get_wtform_choices()
    form.art_of_cultivation.choices = cultivation.get_wtform_choices()
    form.unit_of_seed.choices = seed.get_wtform_unit_choices()

    #print('>>>>>>>>>>>>>diversity_ID:'+str(form.diversity_id.data))
    if form.validate_on_submit():
        next = get_redirect_target()

        check = conception_model.update(form, conception_id)

        if check == 1:
            flash(u'Erfolgreich geändert', 'success')
        if check == 0:
            flash(u'Nichts verändert', 'primary')
        #print('ValidOnSubmit>>>>>>>>>>>>>>>'+str(next))
        #redirect to next here or default to here
        #TODO use redirect_back()

        if next:
            #redirect(next+'?pivot='+str(conception_id))
            print('NExT conc_edit##>' + str(next))
            return redirect(next)
        else:
            return redirect(
                url_for('.conception_by_product_id',
                        fraction_id=fraction.fraction_id,
                        year_of_growth=year_of_growth,
                        product_id=product.product_id,
                        pivot=conception_id))

    next = get_redirect_target()
    if next == request.base_url:
        return redirect(
            url_for('.conception_by_product_id',
                    fraction_id=fraction.fraction_id,
                    year_of_growth=year_of_growth,
                    product_id=product.product_id,
                    pivot=conception_id))

    else:
        #print('req.base_url'+str(request.base_url))
        print('NExT before render conception_input_form:' + str(next))
        return render_template('vegetables/conception_input_form.html',
                               form=form,
                               fraction=fraction,
                               summary=summary,
                               productlist=productlist,
                               the_product=the_product,
                               the_diversity=the_diversity,
                               year_of_growth=year_of_growth,
                               conceptions_micro=conceptions_micro,
                               edit=True,
                               data=data,
                               next=next)
Esempio n. 27
0
def conception_new(fraction_id, year_of_growth, product_id):
    """create one new entrie for one product (fraction,year)
       and do an insert 
    """
    fraction = FractionModel(fraction_id)
    product = ProductModel(product_id, fraction_id)
    diversity = DiversityModel(product_id, fraction_id)
    cultivation = CultivationModel()
    growkind = GrowKindModel()
    seed = SeedModel()
    productlist = fraction.cheata_menue()  #implement list2nested!!!
    #productlist = fraction.get_first_product_list()

    the_product = product.get_data()
    the_diversity = diversity.get()
    summary = conception_model.get_summary_by_id(fraction_id, year_of_growth,
                                                 product_id)
    #aside
    conceptions_micro = conception_model.get_micro_by_product_id(
        fraction_id, year_of_growth, product_id)

    form = VegetablesConceptionForm(request.form)

    #before validating wtf choices (<option>) must be given
    form.diversity_id.choices = diversity.get_wtform_choices()
    form.area_id.choices = fraction.area.get_wtform_choices()
    form.grow_kind_id.choices = growkind.get_wtform_choices()
    form.art_of_cultivation.choices = cultivation.get_wtform_choices()
    form.unit_of_seed.choices = seed.get_wtform_unit_choices()
    if form.validate_on_submit():

        new_id = conception_model.insert(form)
        #print(">>>>>>>>> new_id: "+ str(new_id))
        if new_id:
            flash(u'Erfolgreich angelegt:#' + str(new_id), 'success')

            return redirect(
                url_for('.conception_by_product_id',
                        fraction_id=fraction.fraction_id,
                        year_of_growth=year_of_growth,
                        product_id=product.product_id,
                        pivot=new_id))
        else:
            abort(500)

    #manualy poke initial form.values with the_product specs
    form.name.data = the_product['item_name']
    form.fraction_id.data = fraction.fraction_id
    form.year_of_growth.data = year_of_growth
    form.product_id.data = the_product['product_id']

    form.grow_kind_id.data = (the_product['grow_kind_id'])

    form.planting_interval.data = the_product['planting_interval']

    return render_template('vegetables/conception_input_form.html',
                           form=form,
                           fraction=fraction,
                           summary=summary,
                           productlist=productlist,
                           the_product=the_product,
                           the_diversity=the_diversity,
                           year_of_growth=year_of_growth,
                           conceptions_micro=conceptions_micro,
                           edit=False)
 def __init__(self, train):
   #terms = [HumidityEffect, SmoothedWeatherEffect, TempEffect, WindspeedEffect, CommuteDaytypeEffect, CommuteDailyPattern]
   terms = [CommuteDaytypeEffect, CommuteDailyPattern]
   ProductModel.__init__(self, train, terms)
Esempio n. 29
0
def retract_getsome(fraction_id,source_fraction_id,product_id,unit_id):
    """Hit the retraction Table
    date is handled over session-cookie
    first get the entrie in the acquire data from that retour what you want
    we could restrict boxes ID  to acquire data but the user could retour in
    boxes of another date, years ago.
    """
    fraction = FractionModel(fraction_id)
    source_fraction = FractionModel(source_fraction_id)
    product = ProductModel(product_id, source_fraction_id)
    product_entries = product.get_data()
    unit = UnitModel(product_entries['unit_set_id'])
    box = BoxModel(product_entries['boxes_set_id'])
    vehicle = VehicleModel()
    transaction_model = TransactionModel(fraction_id,source_fraction_id)
    #Do I repeat myself?
    
    if request.args.get('acquiredate'):
        session['acquiredate']= request.args.get('acquiredate')
        
    if 'acquiredate' in session:
        the_date = str(session.get('acquiredate'))
    #
    acquire_data = transaction_model.acquisitions_get_summary_by_date_product_unit(the_date,product_id,unit_id)

    form = Acquisition_Retraction_Form()
    
    form.unit_id.choices = unit.get_wtform_choices()
    form.vehicle_id.choices = vehicle.get_wtform_choices()
    form.box_id.choices = box.get_wtform_choices()
    form.alternate_unit_id.choices = unit.get_wtform_choices()
    
    #prefill formdata
    form.aq_date.data = datetime.strptime(the_date,form.aq_date.format).date()
    form.product_id.data = product_id
    form.fraction_id.data = fraction_id
    form.source_fraction_id.data = source_fraction_id
    form.unit_id.data = acquire_data['unit_id']
    form.unit_id.render_kw={"disabled":"disabled"}
    
    form.box_id.data = acquire_data['box_id']
    #form.box_id.render_kw={"disabled":"disabled"}
    
    if acquire_data['alternatesum'] and acquire_data['alternate_unit_id'] in [item[0] for item in form.alternate_unit_id.choices] :
        form.alternate_unit_id.data = acquire_data['alternate_unit_id']
    else:
        form.alternate_unit_id.data = 1 #defaults to KG (Datenmüll)
    
    if form.validate_on_submit():
        
        result = transaction_model.retraction_insert(form)
        if type(result) is str:
            flash(result, 'alert')
        elif result:
            flash(u'Übernommen!','success')
            
            return redirect(url_for('.retract_twopack', fraction_id=fraction_id,
                                    source_fraction_id=source_fraction_id))
        else:
            abort(500)
            
    if form.csrf_token.errors:
        flash(u'Zeitüberschreitung. Das Formular wird nach einer Stunde warten ungültig. Nichts gespeichert. Gleich nochmal versuchen.','warning')
        
        
    return render_template('transaction/retraction.html',
                            fraction=fraction,
                            source_fraction=source_fraction,
                            product_entries=product_entries,
                            acquire_data=acquire_data,
                            form=form
                            )
 def __init__(self, train):
   #terms = [LinearPopularity]
   terms = [HumidityEffect, SmoothedWeatherEffect, LinearPopularity, TempEffect, WindspeedEffect]
   ProductModel.__init__(self, train, terms)
Esempio n. 31
0
 def __init__(self):
     self._model = ProductModel()
     self._view = ProductView()
 def __init__(self, train):
   self.terms = [Amplitude, Quantity]
   self.model = ProductModel(train, self.terms)
Esempio n. 33
0
        print(coeff)

        irimodel = LinearModel(irimodel, coeff[0], coeff[1])
        pred = irimodel.predict(df['station.longitude'].values,
                                df['station.latitude'].values)
        error = pred - df[metric].values
        print(df[metric].values)
        print(pred)
        print(error)
        print(np.sqrt(np.sum(error**2) / np.sum(df.cs.values)),
              np.sum(error) / np.sum(df.cs.values))

    gp3dmodel = GP3DModel()
    gp3dmodel.train(df, np.log(df[metric].values) - np.log(pred))

    model = ProductModel(irimodel, LogSpaceModel(gp3dmodel))
    pred = model.predict(df['station.longitude'].values,
                         df['station.latitude'].values)
    error = pred - df[metric].values
    print(df[metric].values)
    print(pred)
    print(error)
    print(np.sqrt(np.sum(error**2) / np.sum(df.cs.values)),
          np.sum(error) / np.sum(df.cs.values))

plt = Plot(metric, nowtime)
if metric == 'mufd':
    plt.scale_mufd()
elif metric == 'fof2':
    plt.scale_fof2()
else:
Esempio n. 34
0
def acquire_getsome(fraction_id, source_fraction_id, product_id):
    """ GET ready to fire a POST to the acquisitions table
    the flow is: from source_fraction to fraction
    
    WHAT happens IF fraction_id is to drive the boxes and units,
    like DEPOT wants to have 264' boxes in Pounds of a product???
    
    """
    #init destination fractions
    fraction = FractionModel(fraction_id)
    #init source fraction
    source_fraction = FractionModel(source_fraction_id)

    product = ProductModel(product_id, source_fraction_id)
    #dict of product spec data (one db row)
    product_entries = product.get_data()
    unit = UnitModel(product_entries['unit_set_id'])
    box = BoxModel(product_entries['boxes_set_id'])
    vehicle = VehicleModel()
    transactions = TransactionModel(fraction_id, source_fraction_id)
    #the latest entries in acquisitions table
    #TODO variable count
    history_entries = transactions.acqusitions_get_last_inserts(12)    
    
    form = Acquisition_Retraction_Form()
    #print('dateFORMAT:'+str(form.aq_date.format))
    #print('Session::acquiredate:'+str(session.get('acquiredate')))
    
        
        #form.aq_date.data = session.get('acquiredate')
        
    #before validating wtf choises (<option>) must be given 
    form.unit_id.choices = unit.get_wtform_choices()
    form.vehicle_id.choices = vehicle.get_wtform_choices()
    form.box_id.choices = box.get_wtform_choices()

    #with boxes we css-style <options> in the template (render_kw?)
    boxset = box.get_set_by_id(product_entries['boxes_set_id'])

    form.alternate_unit_id.choices = unit.get_wtform_choices()
    
    if form.validate_on_submit():
        session['acquiredate'] = str(form.aq_date.data)
        
        #print('form-data:'+str(form.aq_date.data))
        #print('sessionACQUIREdate:'+str(session.get('acquiredate')))
        
        result = transactions.acqusition_insert(form)
        
        #print('>>>>>>>>>aqcuisition_insert_result: '+ str(result))
        if type(result) is str:
            flash(result, 'alert')
        elif result:
            flash(u'Die Angaben und Werte wurden erfolgreich übernommen und gespeichert.','success')
 
            return redirect(url_for('.acquire_getsome', fraction_id=fraction_id,
                     source_fraction_id=source_fraction_id,
                     product_id=product_id))
        else:
            abort(500)

    if form.csrf_token.errors:
        flash(u'Zeitüberschreitung. Das Formular wird nach einer Stunde warten ungültig. Nichts gespeichert. Gleich nochmal versuchen.','warning')
    
    #manualy set wtform.data initial_preselected
    if not form.is_submitted():
        #print("FORM SUBMIT!")
        if 'acquiredate' in session:
            set_date = datetime.strptime(session.get('acquiredate'),form.aq_date.format).date()
            form.aq_date.data = set_date
            
        form.fraction_id.data = fraction.fraction_id
        form.source_fraction_id.data = source_fraction.fraction_id
        form.product_id.data = product_entries['product_id']
        if  request.args.get('unit_id',''):
            #print('UNIT_ID!!!!'+str(request.args.get('unit_id',''))+str(type(request.args.get('unit_id',''))))
            if int(request.args.get('unit_id','')) in[item[0] for item in form.unit_id.choices]:
                form.unit_id.data=int(request.args.get('unit_id',''))
        else:
            form.unit_id.data = product_entries['unit_pivot_id']
        form.box_id.data = product_entries['box_pivot_id']
        form.box_count.data = 0
        form.vehicle_count.data = 0
    

    return render_template('transaction/acquisition.html',
                           fraction=fraction,
                           source_fraction=source_fraction,
                           product_entries=product_entries,
                           boxset=boxset,
                           history_entries=history_entries,
                           form=form)