def delete_production(prod_id): try: production = Production.get_by_id(prod_id) production.delete_instance() return Response('{}', status=200) except: return Response('{}', status=503)
async def update_production(slug: str, data: Dict): try: production = await Production.find_one({"slug": slug}) except ValidationError as e: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=e.errors()) if not production: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Production not found", ) try: updated = Production(**production.copy(update=data).dict()) await updated.save() except ValidationError as e: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=e.errors()) except DuplicateKeyError as e: raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) return updated
def remove_expansion(limit, lhs, rhs, parent=None, lmk=None, rel=None): return Production.delete_productions(limit, lhs=lhs, rhs=rhs, parent=parent, lmk=lmk_id(lmk), rel=rel_type(rel))
def get_production(prod_id): try: production = Production.get_by_id(prod_id) jsonprod = json.dumps(production.get_dict()) return jsonprod except: return Response('{}', status=404)
def genearate_states(self): initial = self.grammar.productions.get_augmented()[0] dotted_initial = self.add_dot(initial) state = [dotted_initial] for e in self.generate_additional_state_elements(production=dotted_initial): state.append(e) self.states.append(state) index = 0 # generate states while index < len(self.states): if index not in self.table.entries: self.table.entries[index] = self.prepare_table_entry() toadd = [] transitions = [] for pr in self.states[index]: goto = self.goto(pr) if len(goto) > 0: element_to_add = self.get_element_before_dot(goto[0]) transitions.append((element_to_add, goto)) if goto not in toadd: if goto not in self.states: toadd.append(goto) for gt in toadd: self.states.append(gt) for t in transitions: idx = self.states.index(t[1]) if idx not in self.table.entries: self.table.entries[idx] = self.prepare_table_entry() if t[1][0].rhs[-1].is_dot: p = Production(lhs=t[1][0].lhs, rhs=t[1][0].rhs[:-1]) if p == initial: self.table.entries[idx].action['$'] = Action(action='accept', number=None) else: for y in self.table.entries[idx].action: self.table.entries[idx].action[y] = Action(action='reduce', number=str(self.grammar.productions.productions.index(p) + 1)) if t[0].terminal: self.table.entries[index].action[t[0].name] = Action(action='shift', number=str(self.states.index(t[1]))) else: self.table.entries[index].goto[t[0].name] = Action(action='goto', number=str(self.states.index(t[1]))) index += 1 for i, state in enumerate(self.states): print(str(i) + ": " + ",".join(map(str, state))) for k, v in self.table.entries.items(): print(str(k) + ": " + str(v))
def get_expansion(lhs, parent=None, lmk=None, rel=None): p_db = Production.get_productions(lhs=lhs, parent=parent, lmk=lmk_id(lmk), rel=rel_type(rel)) counter = collections.Counter(p_db) keys, counts = zip(*counter.items()) counts = np.array(counts) counts /= counts.sum() prod, prod_prob, prod_entropy = categorical_sample(keys, counts) print 'expanding:', prod, prod_prob, prod_entropy return prod.rhs, prod_prob, prod_entropy
def edit_production(production_id): try: rcv = request.get_json() if 'name' in rcv: query = Production.update(name=rcv['name']).where( Production.id == production_id) query.execute() if 'client': query = Production.update(client=rcv['client']).where( Production.id == production_id) query.execute() if 'shrimpClass' in rcv: query = Production.update(shrimpClass=rcv['shrimpClass']).where( Production.id == production_id) query.execute() if 'requestedAmount' in rcv: query = Production.update( requestedAmount=rcv['requestedAmount']).where( Production.id == production_id) query.execute() if 'estimatedAmount' in rcv: query = Production.update( estimatedAmount=rcv['estimatedAmount']).where( Production.id == production_id) query.execute() if 'endDate' in rcv: newEndDate = datetime.strptime(rcv['endDate'], '%Y-%m-%d') query = Production.update(endDate=newEndDate).where( Production.id == production_id) query.execute() return Response('{}', status=200) except: return Response('{}', status=503)
async def productions(type: ProductionType = None): query = {} if type: query["type"] = type try: productions = [p async for p in Production.find(query)] except ValidationError as e: raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=e.errors()) for production in productions: print(production) return productions
def read_grammar(self): self.grammar_lines = [line.rstrip('\n') for line in open(self.grammar_filename)] starting_symbol = Element(name=self.grammar_lines[0], terminal=False) elements = [] productions = [] for terminal in self.grammar_lines[1].split(' '): elements.append(Element(name=terminal, terminal=True)) for nonterminal in self.grammar_lines[2].split(' '): elements.append(Element(name=nonterminal, terminal=False)) for production in self.grammar_lines[3:]: elems = production.split(' ') lhs = [lhselem for lhselem in elements if lhselem.name == elems[0]] rhs = [] for rhsinput in elems[1:]: rhselem = [rhsele for rhsele in elements if rhsele.name == rhsinput] rhs.append(rhselem[0]) prod = Production(lhs=lhs[0], rhs=rhs) productions.append(prod) return Grammar(starting_symbol=starting_symbol, productions=productions, elements=elements)
def save_tree(tree, loc, rel, lmk, parent=None): if len(tree.productions()) == 1: # if this tree only has one production # it means that its child is a terminal (word) word = Word() word.word = tree[0] word.pos = tree.node word.parent = parent word.location = loc else: prod = Production() prod.lhs = tree.node prod.rhs = " ".join(n.node for n in tree) prod.parent = parent prod.location = loc # some productions are related to semantic representation if prod.lhs == "RELATION": prod.relation = rel_type(rel) if hasattr(rel, "measurement"): prod.relation_distance_class = rel.measurement.best_distance_class prod.relation_degree_class = rel.measurement.best_degree_class elif prod.lhs == "LANDMARK-PHRASE": prod.landmark = lmk_id(lmk) prod.landmark_class = lmk.object_class # next landmark phrase will need the parent landmark lmk = parent_landmark(lmk) elif prod.lhs == "LANDMARK": # LANDMARK has the same landmark as its parent LANDMARK-PHRASE prod.landmark = parent.landmark prod.landmark_class = parent.landmark_class # save subtrees, keeping track of parent for subtree in tree: save_tree(subtree, loc, rel, lmk, prod)
def edit_tank(tank_id): # falta checagem de boia rcv = request.get_json() if 'capacity' in rcv: query = WaterTank.update(capacity=rcv['capacity']).where( WaterTank.id == tank_id) query.execute() if 'waterLevel' in rcv: query = WaterTank.update(waterLevel=rcv['waterLevel']).where( WaterTank.id == tank_id) query.execute() if 'temperature' in rcv: query = WaterTank.update(temperature=rcv['temperature']).where( WaterTank.id == tank_id) query.execute() if 'salinity' in rcv: query = WaterTank.update(salinity=rcv['salinity']).where( WaterTank.id == tank_id) query.execute() if 'turbidity' in rcv: query = WaterTank.update(turbidity=rcv['turbidity']).where( WaterTank.id == tank_id) query.execute() if 'buoy' in rcv: buoy = Buoy.select().where(Buoy.id == rcv['buoy']) if buoy.exists(): query = WaterTank.update(buoy=rcv['buoy']).where( WaterTank.id == tank_id) query.execute() else: if rcv['buoy'] == 0: query = WaterTank.update(buoy=None).where( WaterTank.id == tank_id) query.execute() if 'production' in rcv: production = Production.select().where( Production.id == rcv['production']) if production.exists(): if production[0].startDate == None: data_start = datetime.datetime.now().strftime("%Y-%m-%d") query = Production.update(startDate=data_start).where( Production.id == rcv['production']) query.execute() query = WaterTank.update(production=rcv['production']).where( WaterTank.id == tank_id) query.execute() else: if rcv['production'] == 0: query = WaterTank.update(production=None).where( WaterTank.id == tank_id) query.execute() if 'feedingschedule' in rcv: feedingschedule = FeedingSchedule.select().where( FeedingSchedule.id == rcv['feedingschedule']) if feedingschedule.exists(): query = WaterTank.update( feedingschedule=rcv['feedingschedule']).where( WaterTank.id == tank_id) query.execute() if 'qtyShrimps' in rcv: query = WaterTank.update(qtyShrimps=rcv['qtyShrimps']).where( WaterTank.id == tank_id) query.execute() tank_now = WaterTank.select().where(WaterTank.id == tank_id) prod_id = tank_now[0].production tanks = json.loads(get_tanks_associated_with_production(prod_id)) qty_total = 0 for tank in tanks: qty_tank = tank['qtyShrimps'] qty_total = qty_total + qty_tank query = Production.update(estimatedAmount=qty_total).where( Production.id == prod_id) query.execute() return Response('{}', status=200)
from models import Production, Customer, Seller, Administrator, Orders, Sale # print (Production.order_production_data(2)) # print(Production.edit(26,"图书","喜为你疾,药石无医","31.4","20","wei.png","This is i like book","新品上架")) # print(Production.basket_production_data(2)) # print(Seller.add_new_production(1,28,"0.9","200-20")) # print(Seller.delete_production(2,25)) # print(Seller.query_seller_product(2)) # print(Production.all_query()) # print(Orders.add_from_basket(14)) # print(Production.query_by_type_type1("图书", "新品上架")) # print(Seller.search_id_by_name('john')) # print(Seller.change_production(2,25,'0.9','0')) # print(Production.basket_production_data(2)) print(Sale.get_price_full_sub(Production.basket_production_data(2)))
def update(self): """ Sync the local DB with IMDB :return: None """ self.download() self.decompress() ids = self.get_ids() new_ids = self.get_new_movies(ids) # For each new movie id get it's data and store in the DB for id in new_ids: movie_data = self.get_movie_info(id) if movie_data: print(movie_data) # distribute this info to respective tables movie = Movie(db) movie.insert([movie_data['id'], movie_data['title'], movie_data['year'], movie_data['runtime'][0] if movie_data['runtime'] else None, movie_data['budget'], movie_data['rating'], movie_data['link'], movie_data['director'][0]['name'] if movie_data['director'] else None]) # Add actor to actor table actors = movie_data['actors'] # Add actor to movie actor relation table ma = MovieActor(db) if actors: for actor in actors: try: fname, lname = actor['name'].split(' ', 2) except ValueError: fname = actor['name'] lname = None id = actor.getID() a = Actor(db) try: if not a.select_one(id): a.insert([id, fname, lname]) except Exception: pass try: # for each actor in the movie add relation movieid -> actorid ma.insert([movie_data['id'], id]) except Exception: pass # Add production company to table companies = movie_data['production company'] if companies: for company in companies: id = company.getID() name = company['name'] c = Production(db) try: if not c.select_one(id): c.insert([id, name]) except Exception: pass # Add this movie to production movie relation table pm = ProductionMovie(db) try: pm.insert([id, movie_data['id']]) except Exception: pass # Add genre to table genres = movie_data['genre'] if genres: g = Genre(db) for genre in genres: try: if not g.select_one(genre): g.insert([genre]) except Exception: pass # Add movie to genre movie relation table gm = GenreMovie(db) try: gm.insert([g.select_one(genre)['GN_ID'], movie_data['id']]) except Exception: pass
def get_all_productions(): productions = Production.select() resposta = [p.get_dict() for p in productions] return json.dumps(resposta)
def save_tree(tree, loc, rel, lmk, parent=None): if len(tree.productions()) == 1: # if this tree only has one production # it means that its child is a terminal (word) word = Word() word.word = tree[0] word.pos = tree.node word.parent = parent word.location = loc else: prod = Production() prod.lhs = tree.node prod.rhs = ' '.join(n.node for n in tree) prod.parent = parent prod.location = loc # some productions are related to semantic representation if prod.lhs == 'RELATION': prod.relation = rel_type(rel) if hasattr(rel, 'measurement'): prod.relation_distance_class = rel.measurement.best_distance_class prod.relation_degree_class = rel.measurement.best_degree_class elif prod.lhs == 'LANDMARK-PHRASE': prod.landmark = lmk_id(lmk) prod.landmark_class = lmk.object_class prod.landmark_orientation_relations = get_lmk_ori_rels_str(lmk) prod.landmark_color = lmk.color # next landmark phrase will need the parent landmark lmk = parent_landmark(lmk) elif prod.lhs == 'LANDMARK': # LANDMARK has the same landmark as its parent LANDMARK-PHRASE prod.landmark = parent.landmark prod.landmark_class = parent.landmark_class prod.landmark_orientation_relations = parent.landmark_orientation_relations prod.landmark_color = parent.landmark_color # save subtrees, keeping track of parent for subtree in tree: save_tree(subtree, loc, rel, lmk, prod)