Пример #1
0
async def search(poisk: str, response: Response):
    users_collection = db.categories_items
    list_of_index = []
    list_of_cat = users_collection.find({"name": poisk}).distinct("id_name")
    if list_of_cat:
        for post in list_of_cat:
            list_of_index.append(post)
    else:
        list_of_cat = users_collection.find({
            "subtype": poisk
        }).distinct("id_subtype")
        if list_of_cat:
            for post in list_of_cat:
                list_of_index.append(post)
        else:
            list_of_cat = users_collection.find({
                "lasttype": poisk
            }).distinct("id_subtype")
            if list_of_cat:
                for post in list_of_cat:
                    list_of_index.append(post)
    list_of_items = []
    users_collection = db.items
    for post in list_of_index:
        current_items = users_collection.find({"categories": str(post)})
        for p in current_items:
            list_of_items.append(
                models.items(id=p['_id'],
                             name=p['name'],
                             description=p['description'],
                             size=p['size'],
                             color=p['color'],
                             image=p['image'],
                             price=p['price'],
                             discount=p['discount'],
                             hit_sales=p['hit_sales'],
                             special_offer=p['special_offer'],
                             categories=p['categories'],
                             link_color=p['link_color']))
    if not list_of_items:
        items = users_collection.find({"name": {'$regex': poisk}})
        for p in items:
            list_of_items.append(
                models.items(id=p['_id'],
                             name=p['name'],
                             description=p['description'],
                             size=p['size'],
                             color=p['color'],
                             image=p['image'],
                             price=p['price'],
                             discount=p['discount'],
                             hit_sales=p['hit_sales'],
                             special_offer=p['special_offer'],
                             categories=p['categories'],
                             link_color=p['link_color']))
    return list_of_items
Пример #2
0
def add_item():
	error = None
	form = itemform()
	if form.validate_on_submit():
		try:
			i = items(name=form.name.data, description=form.description.data)
			db.session.add(i)
			db.session.commit()
			flash('Item added')
		except Exception as e:
			error = e
	return render_template('add.html', form=form, error=error)
Пример #3
0
def sell(request, curr_user):
	"Sell Page"
	if request.method == 'POST':
		form = SellForm(request.POST, instance=items(user=curr_user.user_obj))
		if form.is_valid():
			new_item = form.save()
			# Redirect to the new item page
			return HttpResponseRedirect('/item/?id=%d' % new_item.id)
		else:
			return render(request, 'sell.html', {'form': form})
	else:
		# Display the Form
		return render(request, 'sell.html', {'form': SellForm()})
Пример #4
0
def add_to_cart(id):
    already_in = items.query.filter_by(post_id=id).all()
    if already_in:
        return redirect(url_for('index'))
    db_entry = items(post_id=id, email=current_user.email)
    print(db_entry)
    try:
        db.session.add(db_entry)
        db.session.commit()
        return redirect(url_for('index'))

    except SQLAlchemyError as e:
        error = str(e.__dict__['orig'])
        return error
Пример #5
0
def load_models(models,load_dir,prefix='best'):
    '''
    :param models: Either a single pytorch model, or a dict in {'model_name':model} format
    :param load_dir: Directory to load from
    :return: None
    '''
    if type(models) is not type(None):
        for name,model in models.items():
            load_file = os.path.join(load_dir, '{}_{}.pth'.fotmat(prefix,name))
            model.load_state_dict(torch.load(load_file))
    else:
        load_file = os.path.join(load_dir,'{}_model.pth'.fotmat(prefix))
        models.load_state_dict(torch.load(load_file))
    return None
Пример #6
0
def save_models(models,save_dir,prefix='best'):
    '''

    :param models: Either a single pytorch model, or a dict in {'model_name':model} format
    :param save_dir: Directory to save
    :return: None
    '''
    if type(models) == dict:
        for name,model in models.items():
            save_file = os.path.join(save_dir, '{}_{}.pth'.fotmat(prefix,name))
            torch.save(model.state_dict(), save_file)
    else:
        save_file = os.path.join(save_dir,'{}_model.pth'.fotmat(prefix))
        torch.save(models.state_dict(),save_file)
    return
Пример #7
0
    def do_create(self, line):
        """Creates a new instance of BaseModel and saves it to a JSON file,
        then prints the id of the newly created instance. """
        if line == "":
            print("** class name missing **")
            return
        if line not in models:
            print("** class doesn't exist **")
            return

        for k, v in models.items():
            if k == line:
                value = v
        new = value()
        new.save()
        print("{}".format(new.id))
Пример #8
0
async def get_items(id: int, response: Response):
    users_collection = db.items
    items = users_collection.find_one({"_id": id})
    link_collection = db.link_color
    if not items:
        raise HTTPException(status_code=403)
    response.status_code = status.HTTP_200_OK
    return models.items(id=items['_id'],
                        name=items['name'],
                        description=items['description'],
                        size=items['size'],
                        color=items['color'],
                        image=items['image'],
                        price=items['price'],
                        discount=items['discount'],
                        hit_sales=items['hit_sales'],
                        special_offer=items['special_offer'],
                        categories=items['categories'],
                        link_color=link_collection.find_one(
                            {"_id": items['link_color']})['color_link'])
Пример #9
0
async def get_items(response: Response):
    users_collection = db.items
    link_collection = db.link_color
    all_items = users_collection.find()
    a_i = []
    for post in all_items:
        a_i.append(
            models.items(id=post['_id'],
                         name=post['name'],
                         description=post['description'],
                         size=post['size'],
                         color=post['color'],
                         image=post['image'],
                         price=post['price'],
                         discount=post['discount'],
                         hit_sales=post['hit_sales'],
                         special_offer=post['special_offer'],
                         categories=post['categories'],
                         link_color=link_collection.find_one(
                             {"_id": post['link_color']})['color_link']))
    response.status_code = status.HTTP_200_OK
    return a_i
Пример #10
0
async def items_ind(index: list, response: Response):
    items_collection = db.items
    link_collection = db.link_color
    list_of_items = []
    for post in index:
        items = items_collection.find_one({"_id": int(post)})
        if items:
            list_of_items.append(
                models.items(id=items['_id'],
                             name=items['name'],
                             description=items['description'],
                             size=items['size'],
                             color=items['color'],
                             image=items['image'],
                             price=items['price'],
                             discount=items['discount'],
                             hit_sales=items['hit_sales'],
                             special_offer=items['special_offer'],
                             categories=items['categories'],
                             link_color=link_collection.find_one(
                                 {"_id": items['link_color']})['color_link']))
    return list_of_items
Пример #11
0
async def items_cat(id: str, response: Response):
    list_of_items = []
    items_collection = db.items
    link_collection = db.link_color
    items = items_collection.find({"categories": id}).sort("name", 1)
    for post in items:
        list_of_items.append(
            models.items(id=post['_id'],
                         name=post['name'],
                         description=post['description'],
                         size=post['size'],
                         color=post['color'],
                         image=post['image'],
                         price=post['price'],
                         discount=post['discount'],
                         hit_sales=post['hit_sales'],
                         special_offer=post['special_offer'],
                         categories=post['categories'],
                         link_color=link_collection.find_one(
                             {"_id": post['link_color']})['color_link']))

    return list_of_items
Пример #12
0
async def patch_items(patch_item: models.patch_items, response: Response):
    users_collection = db.items
    link_collection = db.link_color
    items = users_collection.find_one({"_id": patch_item.id})
    if not items:
        raise HTTPException(status_code=403)
    cat_collection = db.categories_items
    cur_cat = cat_collection.find_one({
        "name": patch_item.categories[0],
        "subtype": patch_item.categories[1],
        "lasttype": patch_item.categories[2]
    })

    if not cur_cat:
        raise HTTPException(status_code=403)
    current_item = users_collection.update_one({'_id': patch_item.id}, {
        "$set": {
            "name":
            patch_item.name,
            "description":
            patch_item.description,
            "size":
            patch_item.size,
            "color":
            patch_item.color,
            "image":
            patch_item.image,
            "price":
            patch_item.price,
            "discount":
            patch_item.discount,
            "hit_sales":
            patch_item.hit_sales,
            "special_offer":
            patch_item.special_offer,
            "categories": [
                str(cur_cat['id_name']),
                str(cur_cat['id_subtype']),
                str(cur_cat['id_lasttype'])
            ],
            "link_color":
            patch_item.link_color
        }
    })
    if not current_item:
        raise HTTPException(status_code=403)
    return models.items(id=patch_item.id,
                        name=patch_item.name,
                        description=patch_item.description,
                        size=patch_item.size,
                        color=patch_item.color,
                        image=patch_item.image,
                        price=patch_item.price,
                        discount=patch_item.discount,
                        hit_sales=patch_item.hit_sales,
                        special_offer=patch_item.special_offer,
                        categories=[
                            str(cur_cat['id_name']),
                            str(cur_cat['id_subtype']),
                            str(cur_cat['id_lasttype'])
                        ],
                        link_color=patch_item.link_color)
Пример #13
0
def additem(cod,nom,fecha,cant):
    produ = config.con.query(producto).filter_by(Nomb_producto=nom).first() 
    now = datetime.now()
    nuevo = items(cod, produ.id_producto, now, fecha, "disponible", cant)
    config.con.add(nuevo)
    config.con.commit()
    parser.add_argument('-s','--startdate',default = '2010-01-01 00:00:00',
        help = 'specify a starting time stamp for relevant new data points')
    parser.add_argument('-e','--enddate',default = '2020-01-01 00:00:00',
        help = 'specify an ending time stamp for relevant new data points')
    parser.add_argument('-c','--hydrocodes',
        help = 'specify a hydrocode for all new data points being processed')
    parser.add_argument('-d','--delimiter',default = ',',
        help = 'specify a delimiter for outputting data points\nNote: use $\'\\t\' for tab character')
    parser.add_argument('-w','--overwrite',action = 'store_true',
        help = 'discard existing data if output file already exists')
    args = parser.parse_args()

    if not args.inputfiles:print('no input files provided!');quit()
    elif not args.outputfile:print('no output file provided!');quit()
    cfg,hcfg = convert.parse_config(args.configfile)

    datapoints = collections.OrderedDict()
    ifiles = args.inputfiles.split(',')
    for ifile in ifiles:load_data(ifile,datapoints,hcfg,args)

    risks = {}
    for hydrocode in datapoints:
        risks[hydrocode] = {}
        for threat,model in models.items():
            frisk = model.model(datapoints[hydrocode])
            risks[hydrocode][threat] = frisk 

    save_data(args.outputfile,models,risks,hcfg,args)


Пример #15
0
if __name__ == '__main__':
    for z in ['REG']:
        # Construct the environment with three predictors and desirability functions
        keys = ['A1', 'A2A', 'ERG']
        A1 = utils.Predictor('output/env/RF_%s_CHEMBL226.pkg' % z, type=z)
        A2A = utils.Predictor('output/env/RF_%s_CHEMBL251.pkg' % z, type=z)
        ERG = utils.Predictor('output/env/RF_%s_CHEMBL240.pkg' % z, type=z)
        mod1 = utils.ClippedScore(lower_x=4, upper_x=6.5)
        mod2 = utils.ClippedScore(lower_x=9, upper_x=6.5)
        mod3 = utils.ClippedScore(lower_x=7.5, upper_x=5)
        objs = [A1, A2A, ERG]

        models = {
            'output/lstm_ligand.pkg':
            'benchmark/FINE-TUNE_%s_%s.tsv' % (z, case),
            'output/lstm_chembl.pkg':
            'benchmark/PRE-TRAIN_%s_%s.tsv' % (z, case)
        }
        for case in ['OBJ1', 'OBJ3']:
            if case == 'OBJ3':
                mods = [mod1, mod1, mod3]
            else:
                mods = [mod2, mod1, mod3]

            env = utils.Env(objs=objs, mods=mods, keys=keys)

            for input, output in models.items():
                df = pd.DataFrame()
                df['Smiles'] = sampling(input, output)
                scores = env(df['Smiles'], is_smiles=True)
                df.to_csv(output, index=False, sep='\t')
Пример #16
0
def fit(models, X, Y):
    result = {}
    for key, model in models.items():
        result[key] = model.fit(X, Y)
    return result