def __init__(self, path): global netCdfReady Product.__init__(self, path) print " init class netCDF_Product" self.netCdfReady=netCDFloaded self.type=Product.TYPE_NETCDF self.dataset=None
def manage_beverages_add(): if request.method == 'POST': p = Product() error = None logging.info(request) p.name = request.form['name'] #if request.form['price'].isnumeric(): p.price = float(request.form['price']) #else: # error = "Preis muss eine Nummer sein." if 'isshown' in request.form: p.isshown = True else: p.isshown = False pic = request.files['file'] logging.info(pic.filename) if pic: extension = pic.filename.rsplit('.', 1)[1].lower() logging.info(extension) if extension == "png" or extension == "jpg": pic.seek(0) # Move cursor back to beginning so we can write to disk fpath = os.path.join("./app/static/", "product_%s.png" % p.name) pic.save(fpath) if error is None: add_product(p) return render_template('manage_beverages_add.html', success="Konsumat hinzugefuegt.", user=get_user_by_name(session.get('name'))) return render_template('manage_beverages_add.html', error=error, user=get_user_by_name(session.get('name'))) return render_template('manage_beverages_add.html', user=get_user_by_name(session.get('name')))
def get_product_by_name(name): row = query_db("SELECT * FROM PRODUCTS WHERE NAME = ?", [str(name)], one=True) p = Product() p.id = row[0] p.name = row[1] p.price = row[2] p.isshown = row[3] return p
def get_product_by_id(id): row = query_db("SELECT * FROM PRODUCTS WHERE ID = ?", [str(id)], one=True) # print row p = Product() p.id = row[0] p.name = row[1] p.price = row[2] p.isshown = row[3] return p
def addNewProduct(): form = AddNewProductForm() if request.method == "POST" and form.validate(): # Add the new product. newProduct = Product(form.name.data, float(form.price.data), int(form.stock.data)) newProduct.category = form.category.data newProduct.description = form.description.data db.session.add(newProduct) db.session.commit() # We should, also, add the product specifications. # Specifications are sent as a json string. We do this because it # is really hard to generate dynamic for fields on the client with wtforms. # The solution is to have a single string field generated with wtforms and # to simulate the rest of the string fields on the client, when the client # will submit the form, the values of that fields will be collected and saved # in that master field. We use a javascript object on the client to track # the fields an their values, so at the submission the master field will # contain the json representation of that object. specifications = json.loads(form.specifications.data) for spec_name, spec_value in specifications.iteritems(): db.session.add(ProductSpecifications(newProduct.id, spec_name, spec_value)) db.session.commit() # Now add the images. pictures = json.loads(form.pictures.data) for pictureLink in pictures: db.session.add(ProductPictures(pictureLink, newProduct.id)) db.session.commit() # Now that the product has an id we can add the rest of the components. # First, if the product's category is not already in the database we should add it. category = Categories.query.filter_by(name=newProduct.category).first() if category is None: newCategory = Categories(newProduct.category) db.session.add(newCategory) db.session.commit() else: # The product category may exist, but is unavailable, because there # are no products available left in it. We should make it available. if not category.available: category.available = True db.session.add(category) db.session.commit() return redirect(url_for('productAddedSuccessfully', name=newProduct.name)) flashErrors(form.errors, flash) return render_template('add_new_product.html', form=form)
def get_products(): rows = query_db("SELECT * FROM PRODUCTS") products = [] for row in rows: p = Product() p.id = row[0] p.name = row[1] p.price = row[2] p.isshown = row[3] products.append(p) return products
class Main(Controler): def __init__(self): Controler.__init__(self) self.__sql = core.Sql() self._brand = Brand() self._product = Product() def main(self): self._product.menu()
def next_turn(self): "Reset the city for the next turn" if self.current_progress >= Product.cost [self.current_product]: self.current_progress -= Product.cost [self.current_product] if Product.isUnit(self.current_product): print ("{:s} has produced product id {:s}".format (self.name, self.current_product)) return Unit (self.x, self.y, self.current_product) elif Product.isBuilding(self.current_product): self.city_improvements.append (self.current_product) self.current_product = Product.NONE self.current_progress += self.productivity return None
def test_readAndSum(self): sold=SalesProductList() sold.addProductsCSV("./csvs/stock-sales_TEST.csv") eA = Product() eA.setAddStyle(SalesAddBehavior()) eA=eA.addStyle.addItem(eA, -4, 5, 10) #calculated manually assert sold['602'].totalCost == eA.totalCost assert sold['602'].count == eA.count assert sold['602'].retail == eA.retail
def __init__(self): Controler.__init__(self) self.__sql = core.Sql() self._brand = Brand() self._product = Product()
def __add_data_to_dict(self): print("Collecting data to dictionary:") data = ReturnData() for pdf in self.pdf_list: notes = Notes() try: pdf_without_notes, notes = notes.extract_notes(pdf) except: continue #check impact else: if notes is None: data.files_skipped += 1 print("NOT PREPPED: ", pdf_without_notes[:7]) else: product = Product.factory(pdf_without_notes, notes) row = product.merge_notes_without_csv() key = notes["stock"] if notes["type"] == "FLAT": data.rows_flat.setdefault(key,[]).append(row) elif notes["type"] == "BOUND": data.rows_bound.setdefault(key, []).append(row) print("ADDED!!: ", pdf[:7]) data.files_added_to_csv += 1 print("All data in dictionary!") return data
def get_cost(self, connection, run_size=1): ''' Get the total project BOM cost and unit price for a given production run size. Returns a pair (unit_price, total_cost).''' self.set_prod_counts(connection) project_prod_counts = self.prod_counts.copy() unit_price = 0 total_cost = 0 if 'NULL' in project_prod_counts.keys(): raise NullProductInProjectException(self.get_cost.__name__, 'Warning: Cost calculation does not account for parts with no product assigned!') for x in project_prod_counts.keys(): project_prod_counts[x] = self.prod_counts[x] * run_size for x in project_prod_counts.items(): # Find x[0] (the dict key) in the product DB # x is [manufacturer_pn, qty] if x[0] == 'NULL': pass else: prod = Product.select_by_pn(x[0], connection)[0] listing = prod.best_listing(project_prod_counts[x[0]]) price_break = listing.get_price_break(x[1]) unit_price += (price_break[1] * self.prod_counts[x[0]]) + listing.reel_fee total_cost += (price_break[1] * project_prod_counts[x[0]]) + listing.reel_fee return (unit_price, total_cost)
def test_totalSalesBySKU(self): sold = SalesProductList() sold.addProductsCSV("./csvs/stock-sales_TEST.csv") eA = Product() eA.setAddStyle(behavior_accumulate_retail()) eA = eA.addStyle.addItem(eA, -6, 5, 10) # calculated manually assert sold['602'].totalCost == eA.totalCost assert sold['602'].count == eA.count assert sold['602'].retail == eA.retail assert sold['602'].totalCost == -30 assert sold['602'].count == -6 assert sold['602'].retail == -60
def test_search_sanity(self): our_products = [] products = self.seach.search(self.product_group, self.keyword) our_products_item = self.api.item_search(self.product_group, Keywords=self.keyword) for index, item in enumerate(our_products_item): if index == self.MAX_RESULTS: break browse_nodes = self.api.item_lookup(ItemId=item.ASIN, ResponseGroup='OfferListings,\ BrowseNodes,\ OfferSummary,\ Offers,\ Images') product = Product(item, browse_nodes) if (product.get_img_url('SmallImage') == 'null') or \ (product.get_img_url('MediumImage') == 'null' and product.get_img_url('LargeImage') == 'null'): index -= 1 continue if product.get_rating() == 'null' or \ product.get_review() == 'null' or product.get_price() == 'null': index -= 1 continue our_products.append(product) products_ASIN = [product.ASIN for product in products] our_products_ASIN = [product.ASIN for product in our_products] self.assertItemsEqual(products_ASIN,our_products_ASIN)
def getID( ): while True: id = input("Enter ID (dd-dddd): ") if id == WILDCARD or Product.isIDValid(id): return id else: print("Error: Invalid input. Try again.")
def write(user_id, password, model, odoo_id, vals): _check_user(user_id, password) if model not in ["customer", "product"]: raise Fault("unknown_model", "Reference model does not exist!") if model == "customer": try: customer = Customer.get(Customer.odoo_id == odoo_id) except Customer.DoesNotExist: raise Fault("unknown_registry", "Customer not found!") q = Customer.update(**vals).where(Customer.odoo_id == odoo_id) else: try: product = Product.get(Product.odoo_id == odoo_id) except Product.DoesNotExist: raise Fault("unknown_registry", "Product not found!") q = Product.update(**vals).where(Product.odoo_id == odoo_id) q.execute() return True
def test_get_products_since(self): prod = Product("a", "b", "des", 34.0, "F", "['h','ht']", "name", "color", 0.0, "sourc_url", "{u'L': 1, u'M': 1, u'S': 3, u'XS': 3}", datetime.datetime(2013, 7, 12, 20, 1, 1, 1), "A") db.session.add(prod) db.session.commit() res = self.app.get("/rest/products/?since=2010-1-1", environ_base={"REMOTE_ADDR": "127.0.0.1"}) result = json.loads(res.data) json_prod = result["result"][0] json_prod["__type__"] = "Product" assert res.status_code == 200 assert Product.json_to_product(json_prod) == prod
def create(user_id, password, model, vals): _check_user(user_id, password) odoo_id = vals["odoo_id"] if model not in ["customer", "product"]: raise Fault("unknown_model", "Reference model does not exist!") if model == "customer": try: customer = Customer.get(Customer.odoo_id == odoo_id) except Customer.DoesNotExist: q = Customer.insert(**vals) else: q = Customer.update(**vals).where(Customer.odoo_id == odoo_id) else: try: product = Product.get(Product.odoo_id == odoo_id) except Product.DoesNotExist: q = Product.insert(**vals) else: q = Product.update(**vals).where(Product.odoo_id == odoo_id) q.execute() return True
def parse_products(self): '''get the products in the lists ''' for prod in self.products: p = Product(prod) # prod is a dictionary p.dump() if p.get_type() in Globals.VLEES_TYPES and p.get_include() and p.get_qty() > 0: self.prodlists[p.get_type()].append(p) for x in self.prodlists.keys(): print x, len(self.prodlists[x])
class Director: def __init__(self): self.__data_loader = None self.__builder = None self.__product = Product() def register(self, factory): """ 注册工厂 通过给定的工厂获得DataLoader和Builder子类, 准备更新结果数据到Product """ self.__data_loader = factory.get_data() self.__builder = factory.get_builder() def build(self): data_generator = self.__data_loader.retrieve() for partition_key, deal_source_attrs, deal_target_attrs in data_generator: self.__builder.reset(partition_key, deal_source_attrs) self.__product.reset(deal_target_attrs) self.__builder.build(self.__product) self.__product.persist()
def manage_beverages_edit(name=None): if request.method == 'GET': error = None p = get_product_by_name(name) if p is None: error = "Product existiert nicht" return render_template('manage_beverages_edit.html', product_to_edit=p, error=error, user=get_user_by_name(session.get('name'))) if request.method == 'POST': p = Product() #print request.form p.id = request.form['id'] p.name = request.form['name'] p.price = float(request.form['price']) if 'isshown' in request.form: p.isshown = True else: p.isshown = False pic = request.files['file'] if pic: extension = pic.filename.rsplit('.', 1)[1].lower() if extension == "png" or extension == "jpg": pic.seek(0) # Move cursor back to beginning so we can write to disk fpath = os.path.join("./app/static/", "product_%s.png" % p.name) pic.save(fpath) update_product(p) # update_user(u) return redirect('/manage_beverages')
class ConcreteBuilder(AbstractBuilder): """ Concrete implementation for AbstractBuilder. Please notice that this class also offers a method for returning the whole, newly-created product """ _product = None def __init__(self): self._product = Product() def build_part_A(self): print("Building part A of complex object") self._product.add_part_A("I am a complex object") def build_part_B(self): print("Building part B of complex object") self._product.add_part_B("I am a complex object") def get_product(self): print("Created: new Product instance") return self._product
def unlink(user_id, password, model, odoo_id): _check_user(user_id, password) if model not in ["customer", "product"]: raise Fault("unknown_model", "Reference model does not exist!") q = False if model == "customer": try: customer = Customer.get(Customer.odoo_id == odoo_id) except Customer.DoesNotExist: pass else: q = Customer.delete().where(Customer.odoo_id == odoo_id) else: try: product = Product.get(Product.odoo_id == odoo_id) except Product.DoesNotExist: pass else: q = Product.delete().where(Product.odoo_id == odoo_id) if q: q.execute() return True
def fetch(self, handle, id): from product import Product from artist import Artist jtrack = qobuz.api.get_track(id) if not jtrack: print "Cannot fetch data" return False print pprint.pformat(jtrack) where = {} if 'album' in jtrack: P = Product() album = P.get(handle, jtrack['album']['id']) if not album: P.insert_json(handle, jtrack['album']) for field in self.fields_name.keys(): f = self.fields_name[field] if not f['jsonmap']: continue value = self.get_property(jtrack, f['jsonmap']) if not value: continue where[field] = value if 'interpreter' in jtrack: I = Artist() interpreter = I.get(handle, jtrack['interpreter']) if not interpreter: I.insert(handle, jtrack['interpreter']) if 'performer' in jtrack: I = Artist() interpreter = I.get(handle, jtrack['performer']) if not interpreter: I.insert(handle, jtrack['performer']) artist = None artist_type = ('artist', 'interpreter', 'composer', 'performer') for a in artist_type: if a in jtrack and jtrack[a]['name'] and jtrack[a]['name'] != 'None': artist = jtrack[a] break self.insert(handle, where) return False
def insert_json(self, handle, json): print "JSON: " + pprint.pformat(json) from product import Product from artist import Artist where = {} subtype = ['album', 'interpreter', 'composer', 'performer'] for type in subtype: if type in json: db = None if type == 'album': db = Product() elif type in ['interpreter', 'composer', 'performer']: db = Artist() if not 'id' in json[type] or not json[type]['id']: continue if not db.get(handle, int(json[type]['id'])): db.insert_json(handle, json[type]) for field in self.fields_name.keys(): f = self.fields_name[field] if not f['jsonmap']: continue value = self.get_property(json, f['jsonmap']) if not value: continue where[field] = value print "Where %s" % (pprint.pformat(where)) return self.insert(handle, where)
def find_matching_products(self, proj_parts, wspace_parts, connection): ''' Takes in the output of self.find_similar_parts. Returns a list of Product objects.''' # TODO : Find more results by searching the product_attributes table products = set() part_nums = set() for part in proj_parts: if part.product is not None: db_prods = Product.select_by_pn(part.product.manufacturer_pn, connection) for prod in db_prods: if prod.manufacturer_pn not in part_nums: part_nums.add(prod.manufacturer_pn) products.add(prod) for part in wspace_parts: if part.product is not None: db_prods = Product.select_by_pn(part.product.manufacturer_pn, connection) for prod in db_prods: if prod.manufacturer_pn not in part_nums: part_nums.add(prod.manufacturer_pn) products.add(prod) return list(products)
def setUp(self): unittest.TestCase.setUp(self) from product import * from part import Part from bom import BOM self.wspace = Workspace('DB Tests', os.path.join(os.getcwd(), 'testfixtures', 'dbtests.sqlite')) self.test_product = Product('TDK Corporation', 'C1608X5R1E105K', 'general_B11.pdf', 'CAP CER 1UF 25V 10% X5R 0603', '0603 (1608 Metric)') self.prices_ct = dict({10 : 0.09000, 100 : 0.04280, 250 : 0.03600, 500 : 0.03016, 1000 : 0.02475}) self.prices_tr = dict({4000 : 0.01935, 8000 : 0.01800, 12000 : 0.01710, 280000 : 0.01620, 100000 : 0.01227}) self.prices_dr = dict({10 : 0.09000, 100 : 0.04280, 250 : 0.03600, 500 : 0.03016, 1000 : 0.02475}) self.test_listing_ct = Listing(VENDOR_DK, '445-5146-1-ND', 'C1608X5R1E105K', self.prices_ct, 566342, 'Cut Tape (CT)', 0, 'Capacitors', 'Ceramic', 'C') self.test_listing_tr = Listing(VENDOR_DK, '445-5146-2-ND', 'C1608X5R1E105K', self.prices_tr, 552000, 'Tape & Reel (TR)', 0, 'Capacitors', 'Ceramic', 'C') self.test_listing_dr = Listing(VENDOR_DK, '445-5146-6-ND', 'C1608X5R1E105K', self.prices_dr, 566342, 'Digi-Reel', 7, 'Capacitors', 'Ceramic', 'C') self.test_product.listings[self.test_listing_ct.key()] = self.test_listing_ct self.test_product.listings[self.test_listing_tr.key()] = self.test_listing_tr self.test_product.listings[self.test_listing_dr.key()] = self.test_listing_dr self.part_attribs = dict({'TOL' : '10%', 'VOLT' : '25V', 'TC' : 'X5R'})
def add_products(product): prod = Product.json_to_product(product) prod_ent = Product.query.get(prod.code) if prod_ent: prod_ent.description = prod.description prod_ent.designer = prod.designer prod_ent.price = prod.price prod_ent.gender = prod.gender prod_ent.image_urls = prod.image_urls prod_ent.name = prod.name prod_ent.raw_color = prod.raw_color prod_ent.sale_discount = prod.sale_discount prod_ent.source_url = prod.source_url prod_ent.stock_status = prod.stock_status prod_ent.last_updated = prod.last_updated prod_ent.type = prod.type db.session.commit() return '{"result": "updated"}' else: db.session.add(prod) db.session.commit() return '{"result": "added"}'
def search(self, product_group, keyword, browse_node=None): """ :param product_group: search_index(string) :param keyword: free keyword (string) :return: list of Products instance """ product_items = self.api.item_search(product_group, Keywords=keyword, BrowseNode=browse_node) products = [] index = -1 for item in product_items: index += 1 if index == self.MAX_RESULTS: break browse_nodes = self.api.item_lookup(ItemId=item.ASIN, ResponseGroup='OfferListings,\ BrowseNodes,\ OfferSummary,\ Offers,\ Images') product = Product(item, browse_nodes) if (product.get_img_url('SmallImage') == 'null') or \ (product.get_img_url('MediumImage') == 'null' and product.get_img_url('LargeImage') == 'null'): index -= 1 continue if product.get_rating() == 'null' or product.get_review() == 'null' or product.get_price() == 'null': index -= 1 continue if float(product.get_rating()) < 4.0: index -= 1 continue products.append(product) return products
def new_from_row(row, connection, known_project=None): ''' Given a part row from the DB, returns a Part object. ''' from bom import BOM #print 'new_from_row: row param: ', row if row[6] is None or row[6] == 'NULL' or row[6] == '': product = None #print 'new_from_row: setting no product' else: product = Product.select_by_pn(row[6], connection)[0] #print 'new_from_row: product results: ', product if row[1] is None or row[1] == 'NULL': project = None # TODO: Raise an exception here? This is a PK violation print 'row[1] is None/NULL!' else: if known_project is None: projects = BOM.read_from_db(row[1], connection) if len(projects) > 0: project = projects[0] else: project = known_project part = Part(row[0], project, row[2], row[3], row[4], row[5], product) part.fetch_attributes(connection) return part
def test_is_expired_2(): P1 = Product(1, "Orange", 0.23, "2020-01-01", "2021-01-02", "2020-01-01", 1.20) print(P1.isExpired("2020-01-01")) assert P1.isExpired("2021-01-03") == True
def filter_products(self, query_dict, page_info, fill_options=None): db_models = mall_models.Product.select().dj_where(is_deleted=False) if query_dict.get('status') == 'verified': product_pool_ids = [ p.product_id for p in mall_models.ProductPool.select().dj_where( woid=query_dict['corp'].id, status__not=mall_models.PP_STATUS_DELETE) ] db_models = db_models.dj_where( id__in=product_pool_ids, is_accepted=True, status__not=mall_models.PRODUCT_STATUS['SUBMIT']) elif query_dict.get('status') == 'unverified': db_models = db_models.dj_where(is_accepted=False) elif query_dict.get('status') == 'updated': db_models = db_models.dj_where( is_accepted=True, status=mall_models.PRODUCT_STATUS['SUBMIT'], is_updated=True) if self.corp.is_weizoom_corp(): if query_dict.get('status') != 'verified': db_models = db_models.dj_where(status__in=[ mall_models.PRODUCT_STATUS['SUBMIT'], mall_models.PRODUCT_STATUS['REFUSED'] ]) else: db_models = db_models.dj_where(owner_id=query_dict['corp'].id) #筛选 filter = self.__get_filter_params(query_dict) product_name = filter.get('name') classification_name = filter.get('classification') status = filter.get('status') owner_name = filter.get('owner_name') if product_name: db_models = db_models.dj_where(name__icontains=product_name) if classification_name: classification_models = list( mall_models.Classification.select().dj_where( name__icontains=classification_name)) #能够查询出子分类的数据(默认二级) classification_models += list( mall_models.Classification.select().dj_where( father_id__in=[c.id for c in classification_models])) relation_models = mall_models.ClassificationHasProduct.select( ).dj_where( classification_id__in=[c.id for c in classification_models]) db_models = db_models.dj_where( id__in=[r.product_id for r in relation_models]) if not status == None: status = int(status) if status == self.FILTER_CONST['ALL']: pass if status in [ self.FILTER_CONST['NOT_YET'], self.FILTER_CONST['SUBMIT'] ]: db_models = db_models.dj_where(status=status, is_accepted=False) elif status == self.FILTER_CONST['POOL_REFUSED']: db_models = db_models.dj_where( status=mall_models.PRODUCT_STATUS['REFUSED'], is_accepted=False) elif status == self.FILTER_CONST['UPDATE_REFUSED']: db_models = db_models.dj_where( status=mall_models.PRODUCT_STATUS['REFUSED'], is_accepted=True, is_updated=True) elif status == self.FILTER_CONST['PASSED']: db_models = db_models.dj_where( status=mall_models.PRODUCT_STATUS['NOT_YET'], is_accepted=True) products = [] if owner_name: products = [Product(model) for model in db_models] self.__fill_product_details(products, {'with_supplier_info': True}) fill_options['with_supplier_info'] = False tmp_products = [] for product in products: if product.supplier_info and owner_name in product.supplier_info[ 'company_name']: tmp_products.append(product) if page_info: pageinfo, products = paginator.paginate( tmp_products, page_info.cur_page, page_info.count_per_page) else: pageinfo = None else: db_models = db_models.order_by(-mall_models.Product.id) if page_info: pageinfo, db_models = paginator.paginate( db_models, page_info.cur_page, page_info.count_per_page) else: pageinfo = None for model in db_models: pre_product = Product(model) products.append(pre_product) fill_options = fill_options if fill_options else {} self.__fill_product_details(products, fill_options) return pageinfo, products
# x.send_keys('415') break except NoSuchElementException: print('looking') sleep(.5) self.driver._switch_to.default_content() save = self.driver.find_elements_by_xpath( "//button[@data-qa = 'save-button']") for i in range(0, len(save)): try: save[i].click() except NoSuchElementException: continue except ElementNotInteractableException: continue def buy(self): self.find_click("//button[text()='Submit Order']") # buy_now_x = "//button[text()='Submit Order']" # self.driver.find_element_by_xpath(buy_now_x).click() # size = input("Size: ") # email = input('Account: ') blk_jrdn = Product( size=4, launch_time=LaunchTime(20, 8), link='https://www.nike.com/launch/t/space-hippie-01-wheat-white?size=11') Bot(blk_jrdn)
def test_transform_color_for_sku(self): small_black_shoes = Product('shoes', 'S', 'black') assert small_black_shoes.transform_color_for_sku() == 'BLACK'
def test_transform_name_for_sku(self): small_black_shoes = Product('shoes', 'S', 'black') self.assertEqual( 'SHOES', small_black_shoes.transform_name_for_sku(), )
def test_generate_sku(self): small_black_shoes = Product('shoes', 'S', 'black') self.assertEqual( 'SHOES-S-BLACK', small_black_shoes.generate_sku(), )
def rece(self): while 1: data, addr = pu.recembase(self.udp_socket) action = json.loads(data) if action['type'] == 'newpeer': self.peers[action['data']]= addr print(self.peers) pu.sendJS(self.udp_socket, addr,{ "type":'peers', "data":self.peers }) if action['type'] == 'newProduct': #print('Someone post a new product') newProduct = Product(action) newProduct.printInfo() if newProduct.name in self.product_lst: self.product_lst[newProduct.name].append(newProduct) else: self.product_lst[newProduct.name] = [newProduct] #end if print('debug: sync value is:', action['sync']) if not action['sync']: self.version+=1 #end rec newProduct if action['type'] == 'remove': name = action['Name'] uid = action['UID'] # Assume the product in list if name in self.product_lst: p_lst = self.product_lst[name] for p in p_lst: if p.uid == uid: p_lst.remove(p) #print('debug: remove signal, ack') break #end if #end for else: pass #print('debug: there is no such a product') #end if #end if action if action['type'] == 'update': name = action['Name'] uid = action['UID'] attr = action['Attribute'] value = action['Value'] # Assume the product in list if name in self.product_lst: p_lst = self.product_lst[name] for p in p_lst: if p.uid == uid: p.setAttr(attr,value) #print('debug: update signal, ack') break #end if #end for else: pass #print('debug: there is no such a product') #end if #end if action if action['type'] == 'peers': self.peers.update(action['data']) pu.broadcastJS(self.udp_socket, { "type":"introduce", "data": self.myid, },self.peers) # syncchronize dictionary for peer in self.peers: dist = self.peers[peer] pu.sendJS(self.udp_socket, dist, { "type": "sync", "version": self.version }) break #end for #end rec peers if action['type'] == 'sync': print('debug: in sync') pversion = action['version'] if pversion > self.version: pu.sendJS(self.udp_socket, addr, { "type": 'broadcast', }) else: pu.sendJS(self.udp_socket, addr, {'type': 'reset'}) time.sleep(1) for pn in self.product_lst: p_lst = self.product_lst[pn] for p in p_lst: smsg = p.jsonFile() smsg.update({'type': 'newProduct', 'sync': True}) pu.sendJS(self.udp_socket, addr, smsg) #end for #end for pu.sendJS(self.udp_socket, addr, {'type': 'syncVersion', 'version': self.version}) #end if #end rec sync if action['type'] == 'syncVersion': self.version == action['version'] #end rec syncVersion if action['type'] == 'broadcast': pu.broadcastJS(self.udp_socket, {'type': 'reset'}, self.peers) time.sleep(1) for pn in self.product_lst: p_lst = self.product_lst[pn] for p in p_lst: smsg = p.jsonFile() smsg.update({'type': 'newProduct', 'sync': True}) pu.broadcastJS(self.udp_socket, smsg, self.peers) #end for #end for pu.broadcastJS(self.udp_socket, {'type': 'syncVersion', 'version': self.version}, self.peers) #end rec broadcast if action['type'] == 'reset': self.product_lst.clear() #end rec reset if action['type'] == 'introduce': self.peers[action['data']]= addr #end rec introduce if action['type'] == 'input': print(action['data']) if action['type'] == 'exit': if(self.myid == action['data']): #cannot be closed too fast. time.sleep(0.5) break # self.udp_socket.close() value, key = self.peers.pop(action['data']) print( action['data'] + " is left.")
from product import Product from store import Store # walMart.inflation(0.05) potato = Product(1, "Potato", 2, "Vegetable") # potato.update_price(0.05, True).print_info() carrot = Product(2, "Carrot", 1.5, "Vegetable") onion = Product(3, "Onion", 1, "Vegetable") coke = Product(4, "Coke", 3, "Drink") pepsi = Product(5, "Pepsi", 2.8, "Drink") chips = Product(6, "Chips", 3, "Snack") cake = Product(7, "Cake", 3, "Snack") candy = Product(8, "Candy", 3, "Snack") walMart = Store('Wal Mart') walMart.add_product(potato) walMart.add_product(carrot) walMart.add_product(onion) walMart.add_product(coke) walMart.add_product(pepsi) walMart.add_product(chips) walMart.add_product(cake) walMart.add_product(candy) walMart.sell_product(6) # print(walMart.products) # walMart.set_clearance("Vegetable", 0.05) # class Store: # def __init__(self, name): # self.name = name # self.products = []
self.products.append(product) return self def remove_product(self, product_name): for i in range(0, len(self.products)): if self.products[i].item_name == product_name: del self.products[i] break return self def inventory(self): print("Current inventory: ") for product in self.products: product.display_all() if __name__ == "__main__": Product1 = Product(20, "Toddler shoes", 1, "Carter's", "for sale") Product2 = Product(10, "Toddler socks", 1, "Carter's", "for sale") Product1.sell() Product2.sell() Product2.return_product("used") Store1 = Store([Product1, Product2], "Redmond", "Stephanie Artati") Product3 = Product(25, "Toddler sleepsack", 2, "Gymboree", "for sale") Store1.add_product(Product3) Store1.inventory() Store1.remove_product("Toddler socks") Store1.inventory()
from product import Product from server import ListServer new_prod = Product('3adf', 333.3) new_prod.name = '33rt' test_list_server = ListServer() p1 = Product('abc33', 444.4) test_list_server.catalog.append(p1) test_list_server.remove_product('abc33') test_server_2 = ListServer()
def createProduct(self): p = Product() pass
# teste com um cliente que possui filiação # cliente com afiliação tem 10% de desconto no total da compra cliente = { "name": "alynne", "cpf": "487845", "zipcode": "04574", "membership": { "membership_type": 1 } } #Instanciando um cliente que possui filiação print('Teste Cliente filiado 10\%\ de desconto') foolano = Customer(cliente) # criando um novo produto produto = Product('Game of Trones', 50, 'comum_book') # criando um novo pedido order = Order(foolano, '08012') # adicionando um produto order.add_product(produto) produto2 = Product('bela e a fera', 30, 'midia_digital') order.add_product(produto2) print('Valor total do pedido:', order.total_amount()) # cria um pagamento attributes = dict( order=order, payment_method=CreditCard.fetch_by_hashed('43567890-987654367')) # endereço de cobrança shipping_address = Address('90233') payment = Payment(attributes=attributes)
def create_products(self, product_array): """ Takes an array, then returns a list of products. :param product_array: An array of product info :return: List of products """ products = [] for product_data in product_array: product = Product() # set product attributes product.set_uniq_id(product_data[self._UNIQ_ID]) product.set_item_name(product_data[self._PRODUCT_NAME]) num_reviews = product_data[self._NUMBER_OF_REVIEWS].replace( ',', '') if num_reviews: product.set_number_of_reviews(int(num_reviews)) else: product.set_number_of_reviews(0) avg_reviews = product_data[self._AVERAGE_REVIEW_RATING][:3] if avg_reviews: product.set_average_review_rating( float(product_data[self._AVERAGE_REVIEW_RATING][:3])) else: product.set_average_review_rating(0) product.set_amazon_category_and_sub_category( product_data[self._AMAZON_CATEGORY_AND_SUB_CATEGORY]) product.set_item_type("toys") products.append(product) return products
break for element in soup.find_all('div', class_="_9c44d_2H7Kt"): name = '' price = '' link = '' main_link = '' try: name = element.find('h2', class_="_9c44d_LUA1k").findChild().text price_wrapper = element.find('span', class_="_9c44d_1zemI").text link = element.find('h2', class_="_9c44d_LUA1k").findChild().get("href") main_link = r_url except: print("Exception") product = Product(name, price_wrapper, link, main_link) products.append(product) # print("Name: " + name) # print("Price: " + price_wrapper) # print("Link: " + link) #print() print("Page: " + str(page)) page = page - 1 if page == 0: break #print("Link do strony allegro: "+r.url) run = 0 # browser.quit()
def getUserPreference(buyer_id): search_product = Product() print("Enter the following details: ") manufacturer = input('Make: ') search_product.setMake(manufacturer) modelName = input('Model: ') search_product.setModel(modelName) modelYear = input('Year: ') search_product.setModelYear(modelYear) color = input('Color: ') search_product.setColor(color) products = func.searchBestMatch(search_product.getMake(), search_product.getModel(), search_product.getModelYear(), search_product.getColor()) if products is not None: productMap = printListgetMapForBuyer(products) print(productMap) key = int(input("Enter item no. that you wish to buy: ")) if (key > 0): chooseItemToBuy(productMap[key], buyer_id) else: print("Please enter a valid number! \n") else: print( "Sorry! We cannot find a product that matches your preference!\n") getProductOptionsToBuy(buyer_id)
def send(self): while 1: msg_input = input("$:") msg_input = msg_input.strip() if msg_input == "exit": pu.broadcastJS(self.udp_socket, { "type":"exit", "data":self.myid },self.peers) self.save() break if msg_input == "friends": print(self.peers) continue if msg_input == 'product': # implement create Product later #newProduct = self.createProduct() newProduct = Product() newProduct.name = input('Your product name: ') newProduct.description = input('Please descript your product status:') newProduct.price = input('what is the price of the product:') newProduct.owner = self.myid newProduct.uid = self.getUID() newProduct.printInfo() smsg = newProduct.jsonFile() smsg.update({'type': 'newProduct', 'sync': False}) print('Product added') pu.broadcastJS(self.udp_socket, smsg, self.peers) continue if msg_input == 'save': self.save() continue if msg_input == 'products info': # print format here, todo later self.printProductInfo() continue if msg_input == 'update': p, attr, value = self.update() if p != None: #print('debug: send a update command to peers') pu.broadcastJS(self.udp_socket, { "type": "update", "Name": p.name, "UID": p.uid, "Attribute": attr, "Value": value}, self.peers) else: pass #print('debug: update canceled, nothing happend') #end if continue if msg_input == 'remove': p = self.remove() if p != None: #print('debug: send a remove command to peers') pu.broadcastJS(self.udp_socket, { "type": "remove", "Name": p.name, "UID": p.uid}, self.peers) else: pass #print('debug: Remove canceled, nothing happened') continue if msg_input == 'search': self.search() continue if msg_input == 'guide': self.printGuide() continue l = msg_input.split() if l[-1] in self.peers.keys(): toA = self.peers[l[-1]] s = ' '.join(l[:-1]) pu.sendJS(self.udp_socket, toA,{ "type":"input", "data":s }) else : pu.broadcastJS(self.udp_socket, { "type":"input", "data":msg_input },self.peers) continue #end while if self.myid == 'helper': dist = self.udp_socket.getsockname() pu.sendJS(self.udp_socket, dist, {'type': 'exit', 'data': self.myid})
def test_transform_color_for_sku(self): small_black_shoes = Product('shoes', 'S', 'black') self.assertEqual( 'BLACK', small_black_shoes.transform_color_for_sku(), )
for product in self.products: total_after_tax += product.total_price() return '%.2f' % total_after_tax def find_expensive(self): most_expensive_price = 0 most_expensive_product = "" for product in self.products: if product.total_price() > most_expensive_price: most_expensive_price = product.total_price() most_expensive_product = product.name return most_expensive_product table = Product("table", 13.50, "standard", 1) # 15.25 chair = Product("chair", 5.75, "tax-exempt", 4) # 23 whiteboard = Product("whiteboard", 22.25, "tax-exempt", 3) # 66.75 list_of_products = [table, chair, whiteboard] shopping_cart = ShoppingCart(list_of_products) print(shopping_cart) # Add product eraser = Product("eraser", 1.05, "imported", 10) # 13.13 shopping_cart.add_product(eraser) print(shopping_cart) # Remove product
def test_generate_sku(self): small_black_shoes = Product('shoes', 'S', 'black') assert small_black_shoes.generate_sku() == 'SHOES-S-BLACK'
from product import Product, Build, Parameter from typing import List, Tuple from docker.errors import DockerException code_validations = [ check_copyright, check_spacing, check_tabs, check_doc, check_framework, check_pycodestyle, ] products = [ Product('host', toolchains=[Parameter('GNU')]), Product('juno'), Product('morello'), Product('n1sdp'), Product('rdv1'), Product('rdv1mc'), Product('rdn1e1'), Product('sgi575'), Product('sgm775'), Product('sgm776'), Product('synquacer'), Product('tc0'), Product('tc1'), Product('rcar', toolchains=[Parameter('GNU')]), Product('rdn2', variants=[Parameter('0')]), ]
def test_transform_name_for_sku(self): small_black_shoes = Product('shoes', 'S', 'black') assert small_black_shoes.transform_name_for_sku() == 'SHOES' # <2>
from product import Product from utils import convert_price_toNumber from web_driver_conf import get_web_driver_options from web_driver_conf import get_chrome_web_driver from web_driver_conf import set_ignore_certificate_error from web_driver_conf import set_browser_as_incognito from web_driver_conf import set_automation_as_head_less URL = "http://www.amazon.com/" NUMBER_OF_PAGES_TO_SEARCH = 5 QUESTION_PRODUCT = "What are you looking for?\n:" search_term = str(input(QUESTION_PRODUCT)) biggest_discount = 0.0 lowest_price = 0.0 chepest_product = Product("", "", "", "") best_deal_product = Product("", "", "", "") search_terms = search_term.split(" ") options = get_web_driver_options() set_automation_as_head_less(options) set_ignore_certificate_error(options) set_browser_as_incognito(options) driver = get_chrome_web_driver(options) driver.get(URL) element = driver.find_element_by_xpath('//*[@id="twotabsearchtextbox"]') element.send_keys(search_term) element.send_keys(Keys.ENTER) products = []
def products_to_dict(products): data = [] for product in products: data.append(Product.to_dict(product)) return data
def extract_product(html_content, url): #String Buffer string_buffer = "" errs = list() #Read page and read to extract product infomation parser = BeautifulSoup(html_content, "html.parser") #Check if the page is a product, if not skip page. truth, asin = check_page(parser) if not truth: errs.append("Not product") return (False, errs) #New Product as a object product = Product() #Find URL product.SetUrl(url) #Find Brand: Note: Some products have an image for the brand #truth, string_buffer = search_table(parser, {"id": "productDetails_techSpec_section_1"}, "Brand Name") #if truth: # product.SetBrand(string_buffer) #else: # string_buffer = parser.find("a", attrs={"id": "brand"}) # if string_buffer != None: # product.SetBrand(string_buffer.get_text().strip()) # else: # errs.append("Could not find Brand") #Find Title string_buffer = parser.find("span", attrs={"id": "productTitle"}) string_buffer_2 = parser.find("span", attrs={"id": "btAsinTitle"}) if string_buffer != None: product.SetTitle(string_buffer.get_text().strip()) elif string_buffer_2 != None: product.SetTitle(string_buffer_2.get_text().strip()) elif url != None: product.SetTitle(url.strip("https://www.amazon.com/").split("/dp")[0]) print("Title: ", product.title) else: errs.append("Could not find Title") #return (False, errs) #Find Image #string_buffer = parser.find("img", attrs={"id": "landingImage"}) #if string_buffer != None: # string_buffer = string_buffer.get("data-old-hires") # if len(string_buffer) < 2: # string_buffer = parser.find("img", attrs={"id": "landingImage"}).get("data-a-dynamic-image") # m = re.search('https://(.+?).jpg', string_buffer) # if m: # string_buffer = m.group(1) # string_buffer = "https://{}.jpg".format(string_buffer) # #print ("Img Url: "+string_buffer) # product.SetImage(string_buffer) #else: # errs.append("Could not find Image") #Find ASIN product.SetSourceID(asin) #print("Product after setting ASIN: ",product) #Find price string_buffer = parser.find("span", attrs={"id": "priceblock_saleprice"}) string_buffer_2 = parser.find("span", attrs={"id": "priceblock_ourprice"}) if string_buffer != None: product.SetPrice(string_buffer.get_text()) elif string_buffer_2 != None: product.SetPrice(string_buffer_2.get_text()) else: errs.append("Could not find Price") #return (False, errs) #Find rating string_buffer = parser.find("span", attrs={"id": "acrCustomerReviewText"}) if string_buffer != None: product.SetRating(string_buffer.get_text().split()[0]) #print("Product after setting rating: ",product) #Append the product to large list of products if product.FormCompleted(): return (product, errs) else: return (False, errs)
def get_product(self, product_id, fill_options=None): db_model = mall_models.Product.select().dj_where( id=product_id, is_deleted=False).get() product = Product(db_model) self.__fill_product_details([product], fill_options) return product
total += item.calc_price() return(total) def add_to_cart(self, newitem): self.products.append(newitem) def remove_from_cart(self,rm_item_index): self.products.pop(rm_item_index) def display_cart(self): print("Your Cart:") for item in self.products: print(item) newcart = Cart() # bear = Product("bear", 10, 0.05) # print(bear.base_price) # print(bear.calc_price()) newcart.add_to_cart(Product("bear", 10, 0.05)) newcart.add_to_cart(Product("ball", 5, 0.14)) newcart.add_to_cart(Product("bike", 150, 0.13)) newcart.display_cart() print(newcart.cost_before_tax()) print(newcart.cost_after_tax()) newcart.remove_from_cart(1) newcart.display_cart() print(newcart.cost_before_tax()) print(newcart.cost_after_tax())
def update_inventories(product_id, seller_id): conn = c.returnConnection() cursor = conn.cursor(buffered=True) # fetch data to update based on user that is logged in - show user products that belongs to that seller ESPECIALLY for Update! cursor.execute( f"SELECT make, model, model_quantity, model_year, color, price FROM products WHERE product_id = '{product_id}' AND user_id = '{seller_id}'" ) data = cursor.fetchone() manufacturer, model_name, model_quantity, model_year, color, price = data update_fields = [ 'Manufacturer', 'Model name', 'Quantity', 'Model Year', 'Color', 'Cost', 'Previous Menu' ] while (True): print(f'Please select the operation you would like to perform: ') cnt = 1 for field in update_fields: print(f'{cnt}. {field}') cnt += 1 selection = int(input('Select one above: ')) product = Product() if (selection == 1): manufacturer = input('New Manufacturer: ') if manufacturer is not None: product.setMake(manufacturer) elif (selection == 2): model_name = input('New Model Name: ') if model_name is not None: product.setModel(model_name) elif (selection == 3): model_quantity = int(input('New Quantity: ')) if model_quantity is not None: product.setModelQuantity(model_quantity) elif (selection == 4): model_year = input('New Model Year: ') if model_year is not None: product.setModel(model_year) elif (selection == 5): color = input('New Model Color: ') if color is not None: product.setModel(color) elif (selection == 6): price = float(input('New Model Cost: ')) if price is not None: product.setModel(price) elif (selection == 7): break else: print('invalid selection') func.updateProduct(product_id, manufacturer, model_name, model_quantity, model_year, color, price)
def add_inventories(user_id): product = Product() manufacturer = input('Enter manufacturer name: ') product.setMake(manufacturer) model_name = input('Enter your Model name: ') product.setModel(model_name) model_qty = int(input('Quantity available: ')) product.setModelQuantity(model_qty) model_yr = input('Enter Model year: ') product.setModelYear(model_yr) color = input('Enter color available: ') product.setColor(color) cost = input('Enter cost of the Model: ') product.setPrice(cost) func.insertProductInfo(user_id, product.getMake(), product.getModel(), product.getModelQuantity(), product.getModelYear(), product.getColor(), product.getPrice())
def prodAddBtnClicked(self): name = self.work.nameLine.text() price = self.work.priceLine.text() producer = self.work.producerLine.text() measurment = self.work.measurmentLine.text() Product(name, price, producer, measurment).changeData(self.index)
def buildProduct(self, food_item): food_dict = json.loads(food_item) product = Product(food_dict) return product