def reco(): property_name = request.form.get('property_name') property_code = request.form.get('property_code') flag_name = request.form.get('flag_name') num_of_rooms = request.form.get('num_of_rooms', type=int) location_type = request.form.get('location_type') state = request.form.get('state') revenue = request.form.get('revenue', type=float) profit_margin = request.form.get('profit_margin', type=float) occupancy_rate = request.form.get('occupancy_rate', type=float) store = Store(property_name, property_code, flag_name, num_of_rooms, revenue, profit_margin, occupancy_rate, location_type, state) cluster = model.predict(store) spor = model.predict_spor(store) profit_margin = model.predict_profit_margin(store) stores = model.predict_comparable_stores(store, 5) store_hat = store.upgrade_to(spor=spor, profit_margin=profit_margin) return render_template("reco.html", store=store, cluster=cluster, store_hat=store_hat, stores=stores.tolist())
def _getDefaultStore(self): query = Store.gql('where name = :name', name='default') store = query.get() if store == None: store = Store(name='default', merchantid='0', useSandbox='true') store.put() return store
class GenFE(object): ''' generate fixed number entity ''' def __init__(self, ent, ent_size, db): self.ent = ent self.ent_size = ent_size self.db = db self.start_idx = 0 self.db_handler = Store(self.db) self.db_handler.connect() def set_start_idx(self, n): self.start_idx = n def start(self, max_id): # max_id: the max id should be generated count = max_id - start_idx + 1 if count < 1: return data = gen_data(self.ent, self.ent_size, self.start_idx, count) self.start_idx += count # dump data to db name = self.ent['alias'] sql = 'insert into %s values (?' % (name) if 'tag' in self.ent: sql = sql + ', ?' if 'attr' in self.ent: sql = sql + ', ?' * len(self.ent['attr']) sql = sql + ')' try: self.db_handler.insert_many(sql, data) except Exception as e: raise e print('[Node Generation]: Name %s, Max ID %s' % (name, max_id))
def __init__(self, ent, ent_size, db): self.ent = ent self.ent_size = ent_size self.db = db self.start_idx = 0 self.db_handler = Store(self.db) self.db_handler.connect()
def __init__(self, db, dic, parent_conn, src_dic, ent_size, tgt_dic=None, mode='local'): ''' db : db name dic : the relation dict of the config parent_conn: server conn 1, rel data 2, src nodes: n 3, tgt nodes: m src_dic : src node config dict ent_size: the number of nodes of each entity tgt_dic : tgt node config dict if is None, then tgt_dic == src_dic, e.g. user -> user mode : local (default), dump edge locally : u-level, dump edge and node in parent process ''' self.parent_conn = parent_conn self.rel_dict = dic self.db_name = db self.src_dic = src_dic self.tgt_dic = tgt_dic self.mode = mode self.ent_size = ent_size self.db_handler = Store(db) self.db_handler.connect() # parameters of in/out distributions # TODO: other type of distribution if dic['in']['type'] == 'power_law': mind, maxd, midd = 0, -1, -1 if 'min_degree' in dic['in']: mind = dic['in']['min_degree'] if 'max_degree' in dic['in']: maxd = dic['in']['max_degree'] if 'mid_degree' in dic['in']: midd = dic['in']['mid_degree'] if isinstance(dic['in']['lambd'], list): self.indistr_ins = PWL(0, dic['in']['lambd'][0], dic['in']['lambd'][1], mind, maxd, midd) else: self.indistr_ins = PWL(0, dic['in']['lambd'], min_degree=mind, max_degree=maxd, mid_degree=midd) elif dic['in']['type'] == 'uniform': self.indistr_ins = Uniform(0, dic['in']['min'], dic['in']['max']) if dic['out']['type'] == 'power_law': mind, maxd, midd = 0, -1, -1 if 'min_degree' in dic['out']: mind = dic['out']['min_degree'] if 'max_degree' in dic['out']: maxd = dic['out']['max_degree'] if 'mid_degree' in dic['out']: midd = dic['out']['mid_degree'] if isinstance(dic['out']['lambd'], list): self.outdistr_ins = PWL(0, dic['out']['lambd'][0], dic['out']['lambd'][1], mind, maxd, midd) else: self.outdistr_ins = PWL(0, dic['out']['lambd'], min_degree=mind, max_degree=maxd, mid_degree=midd) elif dic['out']['type'] = 'uniform': self.outdistr_ins = Uniform(0, dic['out']['min'], dic['out']['max'])
def __init__(self, dic, db, in_, out, cutoff=6): ''' dic: the dict info of one type edge db : db file name, store the generated graph data ''' self.rel_dict = dic self.db_name = db self.db_handler = Store(db) self.db_handler.connect() self.cutoff = cutoff self.in_cnt = in_ self.out_cnt = out
def make_stores(): """ Make fake stores and load into database. """ print 'Making Stores...' # Since I like to run this file over and over again: Store.query.delete() for row in open('misc/seed_stores.txt'): row = row.rstrip() store_id, name, address, city, state, zipcode, phone = row.split('\t') store_id = "{:0>3}".format(store_id) zipcode = "{:0>5}".format(zipcode) district_id = get_random_district() # Instantiate a store using Store class in model.py! Woohoo! store = Store(store_id=store_id, name=name, address=address, phone=phone, city=city, state=state, zipcode=zipcode, district_id=district_id) # Add to db db.session.add(store) db.session.commit()
def check_order_store_quantity(store_id, oid): result = 0 items = OrderItem.select().where(OrderItem.order == oid) r = 0 if store_id: for i in items: if i.product.is_store == 1: # and i.product.store.id == int(store_id) r += 1 else: r += check_store_product_quantity(store_id, i.product_standard.id) if r == items.count(): result = 1 else: list = [] order = Order.get(Order.id == oid) store = Store.select().where(Store.status == 1) sid = 0 for s in store: ss = getDistanceAS(order.take_address.replace(' ', ''), s.id) if ss['flag'] == 1: list.append(float(ss['data'])) if float(ss['data']) < setting.PeiSongDistance: sid = s.id for i in items: if i.product.is_store == 1 and i.product.store.id == sid: r += 1 else: r += check_store_product_quantity(sid, i.product_standard.id) if r == items.count(): result = 1 return result
def fill_product(self, dictcat): """Fill the table products and store.""" if self.session.query(Products.id).count() == 0: for key in dictcat.keys(): select_product.extract(key, dictcat[key]) for prod in select_product.product_list: print(f"Downloading products: {prod}") if prod[0] and prod[1] != 'NULL' or '': newstore = Store(name_store=prod[3]) self.session.add(newstore) self.session.commit() store = self.session.query(Store.id).count() newproduct = Products(name=prod[0], name_nut=prod[1], name_url=prod[2], store_name=prod[3], categorie_id=prod[4], store_id=store) self.session.add(newproduct) self.session.commit() select_product.product_list.remove(prod) else: pass else: pass
def post(self): username = self.get_argument("username", None) password = self.get_argument("password", None) if username and password: try: user = AdminUser.get(AdminUser.username == username) if user.check_password(password): if user.isactive == 1: if not user.store: storeid = 0 else: storeid = user.store if not user.front_user: frontuserid = 0 else: frontuserid = user.front_user qstore = Store.select().where(Store.id == storeid) qfront_user = User.select().where( User.id == frontuserid) if qstore.count() > 0 and qfront_user.count() > 0: user.updatesignin() self.session['store'] = user self.session.save() self.redirect("/store/index") return else: self.flash("此帐户未关联经销商或经销商未绑定前台用户。") else: self.flash("此账户被禁止登录,请联系管理员。") else: self.flash("密码错误") except Exception, e: print e self.flash("此用户不存在")
def create(): try: store=Store( code= request.json['code'] or None, name=request.json['name'], online=request.json['online'] or False, website=request.json['website'] or None, longitude=request.json['longitude'] or None, latitude=request.json['latitude'] or None, source='OWN', source_id=request.json['source_id'] or None ) database.session.add(store) database.session.commit() return jsonify({ 'status': 'OK', 'store': store.serialize() }), 201 except Exception as e: return jsonify({ 'status': 'ERROR', 'error': str(e) }), 500
def delete(self, name): store = Store.find_by_name(name) if store: try: store.delete() except Exception: return {'message': 'Unable to delete store at this time.'}, 500 else: return {'message': 'Store deleted'}
def render(self): client_store = self.handler.get_secure_cookie('store', None) if client_store: sid = simplejson.loads(client_store) s = Store.get(Store.id == sid) name = s.name else: name = u'实体店' return name
def setUp(self): super(TestCRUDController, self).setUp() self.store = Store() self.app = self.parent = cimarron.skin.Application() self.widget = CRUDController.fromXmlFile('test/testCrud.xml') self.widget.parent = self.parent self.window = self.widget.window self.widget.store = self.store person = Person.__values__[0] self.setUpControl(target=person, attr=None)
def post(self): result = {"flag": 0, "msg": "", "data": ""} try: args = simplejson.loads(self.request.body) username = args["username"] password = args["password"] if username and password: quser = AdminUser.select().where( AdminUser.username == username) if quser.count() > 0 and quser[0].check_password(password): user = quser[0] if user.isactive == 1: if self.vrole("J", user.roles): if not user.store: storeid = 0 else: storeid = user.store if not user.front_user: frontuserid = 0 else: frontuserid = user.front_user qstore = Store.select().where(Store.id == storeid) qfront_user = User.select().where( User.id == frontuserid) if qstore.count() > 0 and qfront_user.count() > 0: user.updatesignin() result["flag"] = 1 result["data"] = { 'adminid': user.id, 'storeid': qstore[0].id, 'front_user': user.front_user, 'storename': qstore[0].name, } else: result["flag"] = 0 result["msg"] = "此帐户未关联经销商或经销商未绑定前台用户。" else: result["flag"] = 0 result["msg"] = "此账户没有经销商的登录权限。" else: result["flag"] = 0 result["msg"] = "此账户被禁止登录,请联系管理员。" else: if quser.count() > 0: result["flag"] = 0 result["msg"] = "密码错误。" else: result["flag"] = 0 result["msg"] = "此用户不存在" else: result["flag"] = 0 result["msg"] = "请输入用户名或者密码" except Exception, e: result["flag"] = 0 result["msg"] = e
def estimateR_weighted(S, W, D, R0): ''' estimates the update of the rotation matrix for the second part of the iterations :param S : shape :param W : heatmap :param D : weight of the heatmap :param R0 : rotation matrix :return: R the new rotation matrix ''' A = np.transpose(S) B = np.transpose(W) X0 = R0[0:2, :] store_E = Store() [m, n] = A.shape p = B.shape[1] At = np.zeros([n, m]) At = np.transpose(A) # we use the optimization on a Stiefel manifold because R is constrained to be othogonal manifold = Stiefel(n, p, 1) #################################################################################################################### def cost(X): ''' cost function of the manifold, the cost is trace(E'*D*E)/2 with E = A*X - B or store_E :param X : vector :return f : the cost ''' if store_E.stored is None: store_E.stored = np.dot(A, np.transpose(X)) - B E = store_E.stored f = np.trace(np.dot(np.transpose(E), np.dot(D, E))) / 2 return f #################################################################################################################### # setup the problem structure with manifold M and cost problem = Problem(manifold=manifold, cost=cost, verbosity=0) # setup the trust region algorithm to solve the problem TR = TrustRegions(maxiter=10) # solve the problem X = TR.solve(problem, X0) #print('X : ',X) return np.transpose(X) # return R = X'
def setUp(self): super(TestEditor, self).setUp() self.store = Store() self.parent = self.window = cimarron.skin.Window() # self.widget = cimarron.skin.Editor(store=self.store, # attributes=['name', 'surname']) self.widget = Editor.fromXmlFile('test/editor.xml') self.widget.parent = self.parent self.widget.store = self.store self.entry = self.widget.entries.children[0] self.setUpControl(target=Person('Marcos', 'Dione'), attr=None)
class Main(object): ''' main procedure Input : scheme Output: social network data, saved to sqlite ''' def __init__(self, scheme): self.scheme = scheme self.db_name = scheme['alias'] + '.db' self.db_handler = Store(self.db_name) self.db_handler.connect() def create_db(self): try: crt_db_sql = tbl_sql(self.scheme) # with open('ddl.sql', 'w') as f: # f.write(crt_db_sql) self.db_handler.execute_script(crt_db_sql) print('Create db %s done' % self.db_name) except Exception as e: raise e def clear_db(self): try: dlt_sql = delete_sql(self.scheme) self.db_handler.execute_script(dlt_sql) print('clear db %s done' % (self.db_name)) except Exception as e: raise e def process(self): pass
def __init__(self, config, lowtran, hightran, device): self.config = config self.device = device self.lownet = lowPolicy(config.get('feature_dim'), config.get('action_dim'), config.get('num_options'), config.get('hidden_dim')).double().to( self.device) self.highnet = OptionNet(config.get('num_options'), config.get('feature_dim'), config.get('hidden_dim')).double().to( self.device) self.lowmemory = Store(lowtran, config.get('buffer_cap'), config.get('batch_size')) self.highmemory = Store(hightran, config.get('buffer_cap'), config.get('batch_size')) self.lowoptimizition = torch.optim.Adam(self.lownet.parameters(), lr=config.get('low_lr')) self.highoptimizition = torch.optim.Adam(self.highnet.parameters(), lr=config.get('high_lr')) self.start_list = config.get('start_list') self.end_list = config.get('end_list')
def create_store(store_name, address_id, store_website, web_only_indicator): """Create and return a store.""" store = Store(store_name=store_name, address_id = address_id, store_website = store_website, web_only_indicator = web_only_indicator ) db.session.add(store) db.session.commit() return store
def store_add(): if request.method == 'POST': if request.form.get('store_id'): store = get_object_or_404(Store, Store.id == request.form['store_id']) store.name = request.form['name'] store.save() flash('Store #%d updated successfully.' % (store.id,), 'success') else: name = request.form['name'] if name == "": flash('Store needs to have a name', 'danger') else: store = Store.create(name=name) flash('Store %s created successfully.' % (name,), 'success') return jsonify(success=True) return render_template('store.html')
def post(self, name): if Item.find_by_name(name): return {'message': 'item already exists'} data = ItemResource.parser.parse_args() if Store.find_by_id(data['store_id']) is None: return {'message': 'invalid store_id'} item = Item(name, data['price'], data['store_id']) try: item.persist() except Exception: return {'message': 'error occurred while creating item'}, 500 else: return item.json(), 201
def post(self, name): if Store.find_by_name(name): return {'message': 'Store already exists.'}, 400 store = Store(name) try: store.persist() except Exception: return {'message': 'error occurred while creating store'}, 500 else: return store.json(), 201
def add_nancy(): """ Adds me & corp to the employee & store tables """ corp_store = Store(store_id='999', name='Corporate Headquarters', address='400 Valley Drive', city='Brisbane', state='CA', zipcode='94005', phone='(415) 555-1234', district_id='D99') nancy = Employee(emp_id='09332', fname='Nancy', lname='Reyes', ssn='123-45-6789', password='******', store_id='999', pos_id='99-HQ') db.session.add_all([nancy, corp_store]) db.session.commit()
def optimizer_R_v1(W, D, S, R0): """ :param W: heatmap constant :param D: weight of the keypoints :param S: shape of the object :param R0: initial R :return : the optimal R with fixed T and s the cost is ||(W-(RS))*sqrt(D)|| but in fact is the scale factor is already taken into account in S and T is taken into account in W """ # this store object is needed because the manifold optimizer do not works if it is not implemented like that store = Store() # -------------------------------------COST FUNCTION------------------------------------- def cost(R): """ :param R: rotation matrix variable :return : ||(W-(RS))*D^1/2||^2 = tr((W-(RS))*D*(W-(RS))') """ if store.stored is None: store.stored = W - np.dot(R, S) X = store.stored f = np.trace(np.dot(X, np.dot(D, np.transpose(X)))) / 2 return f # ---------------------------------------------------------------------------------------- # we use the optimization on a Stiefel manifold because R is constrained to be othogonal manifold = Stiefel(3, 2, 1) # setup the problem structure with manifold M and cost problem = Problem(manifold=manifold, cost=cost, verbosity=0) # setup the trust region algorithm to solve the problem TR = TrustRegions(maxiter=15) # solve the problem R_opt = TR.solve(problem, R0) return np.transpose(R_opt)
def virtual_creation(): with dm.session_scope() as db: stores = [] for i in range(STORES_NUM): store = Store(name="Tienda {}".format(i), latitude=0.0, longitude=0.0) offers = [] for j in range(PRODUCTS_PER_STORE): pr = Product( store=store, name="Product {},{}".format(i, j), img_url= "http://www.lavozlibre.com/userfiles/2a_decada/image/FOTOS%202013/04%20ABRIL%202013/02%20ABRIL%202013/yogures.jpg", price="3€") offers.append(Offer(product=pr, offer_price="2€", store=store)) store.products.append(pr) db.add_all(offers) stores.append(store) db.add_all(stores)
def getMinDistanceStore(address): result = {"flag": 0, "msg": "", "data": ""} try: if address: if address.count('枫林绿洲') > 0: address = address.replace('小区', '') qstore = Store.select().where((Store.status == 1) & (Store.storetype == 0)) point = getPointByAddress(address) minDistance = 10000 minStore = None for store in qstore: minD = getDistance(point["lng"], point["lat"], float(store.x), float(store.y)) if minD < minDistance: minDistance = minD minStore = store if minDistance > 0 and minStore and minDistance < minStore.psdistance: result["flag"] = 1 result["data"] = { "id": minStore.id, "name": minStore.name, "distance": minDistance, "byprice": minStore.byprice, "freight": minStore.freight, } else: result["flag"] = 0 result["msg"] = "在该地址附近未找到可以配送的经销商!" result["data"] = "" else: result["flag"] = 0 result["msg"] = "地址不能为空!" except Exception, ex: result["flag"] = 0 result["msg"] = "地址或者经销商信息错误!"
def getDistanceAS(address, store_id): result = {"flag": 0, "msg": "", "data": ""} try: if address: if store_id > 0: store = Store.get(Store.id == store_id) result["flag"] = 1 point = getPointByAddress(address) result["data"] = str( getDistance(point["lng"], point["lat"], float(store.x), float(store.y))) else: result["flag"] = 0 result["msg"] = "经销商ID不正确!" else: result["flag"] = 0 result["msg"] = "地址不能为空!" except: result["flag"] = 0 result["msg"] = "地址或者经销商信息错误!" return result
class GenDDR(object): ''' src is dynamic, and tag is dynamic ''' def __init__(self, db, dic, parent_conn, src_dic, ent_size, tgt_dic=None, mode='local'): ''' db : db name dic : the relation dict of the config parent_conn: server conn 1, rel data 2, src nodes: n 3, tgt nodes: m src_dic : src node config dict ent_size: the number of nodes of each entity tgt_dic : tgt node config dict if is None, then tgt_dic == src_dic, e.g. user -> user mode : local (default), dump edge locally : u-level, dump edge and node in parent process ''' self.parent_conn = parent_conn self.rel_dict = dic self.db_name = db self.src_dic = src_dic self.tgt_dic = tgt_dic self.mode = mode self.ent_size = ent_size self.db_handler = Store(db) self.db_handler.connect() # parameters of in/out distributions # TODO: other type of distribution if dic['in']['type'] == 'power_law': mind, maxd, midd = 0, -1, -1 if 'min_degree' in dic['in']: mind = dic['in']['min_degree'] if 'max_degree' in dic['in']: maxd = dic['in']['max_degree'] if 'mid_degree' in dic['in']: midd = dic['in']['mid_degree'] if isinstance(dic['in']['lambd'], list): self.indistr_ins = PWL(0, dic['in']['lambd'][0], dic['in']['lambd'][1], mind, maxd, midd) else: self.indistr_ins = PWL(0, dic['in']['lambd'], min_degree=mind, max_degree=maxd, mid_degree=midd) elif dic['in']['type'] == 'uniform': self.indistr_ins = Uniform(0, dic['in']['min'], dic['in']['max']) if dic['out']['type'] == 'power_law': mind, maxd, midd = 0, -1, -1 if 'min_degree' in dic['out']: mind = dic['out']['min_degree'] if 'max_degree' in dic['out']: maxd = dic['out']['max_degree'] if 'mid_degree' in dic['out']: midd = dic['out']['mid_degree'] if isinstance(dic['out']['lambd'], list): self.outdistr_ins = PWL(0, dic['out']['lambd'][0], dic['out']['lambd'][1], mind, maxd, midd) else: self.outdistr_ins = PWL(0, dic['out']['lambd'], min_degree=mind, max_degree=maxd, mid_degree=midd) elif dic['out']['type'] = 'uniform': self.outdistr_ins = Uniform(0, dic['out']['min'], dic['out']['max']) # some statistical info self.in_degree_nums = [] # [i] : the number of nodes with in degree i self.out_degree_nums = [] # [i] : the number of nodes with out degree i self.node_in_degree = [] # [i] : the in degree of node i self.node_out_degree = [] # [i] : the out degree of node i self.in_degree_nodes = [] # [i] : the nodes with in degree i, from degree 1 self.out_degree_nodes = [] # [i] : the nodes with out degree i,from degree 1 self.src_remain_nodes = [] # : source nodes (out) list with degree 0 self.tgt_remain_nodes = [] # : target nodes (in) list with degree 0 # generate index and nums info self.src_l_index = 0 self.src_r_index = 1 self.tgt_l_index = 0 self.tgt_r_index = 1 self.src_fake_cnt = 0 self.tgt_fake_cnt = 0 # for community self.mu_parameter = 0.4 # used to determine community belongs self.ncomunty = 10 # community id: 0, 1, ... self.comunty_nodes = [] # community: set of nodes # node id: start from 1 self.node_comunty_n_indegree = [[]] # [d1, ..., dn] self.node_comunty_n_outdegree = [[]] # [d1, ..., dn] self.node_comunty_ident = [set()] # the communities node i belongs to
def get(self): result = [] q = Store.select().where(Store.status == 1) for n in q: result.append({'ID': n.id, 'Name': n.name}) self.write(simplejson.dumps(result))
def store_list(): stores = Store.listWithStats() return render_template('store.html', stores=stores)