def description(self): ''' We have to ensure that the description text is formatted correctly, it gets dumped into a <pre> tag which will honor whitespace this will split all of the text and insert newlines every 70 chars +2 whitespace at be beginning of each line, so the indents line up nicely. ''' if self.autoformat: index, step = 0, 70 ls = [' '] if 0 < len(self._description): text = self._description.replace('\n', '') while index < len(text): ls.append(" " + text[index:index + step]) index += step if len(ls) == 1: if self.category_id: ls.append(" Category: %s\n" % Category.by_id(self.category_id).category) else: ls.append(" No information on file.") else: if self.category_id: ls.append("\n Category: %s\n" % Category.by_id(self.category_id).category) if self.operating_system != "none": ls.append("\n Operating System: %s\n" % self.operating_system) if self.difficulty != "Unknown": ls.append(" Reported Difficulty: %s\n" % self.difficulty) if not str(ls[-1]).endswith("\n"): ls[-1] = ls[-1] + "\n" return unicode("\n".join(ls)) else: return self._description
def __extractCategories(self, stringList, cursor, prodId): categoryList = [] for string in stringList: if '[' in string and ']' in string: try: # print(string) idInitPos = string.find('[') # print(idInitPos) idEndPos = string.find(']') # print(idEndPos) id = string[idInitPos + 1:idEndPos] title = string[0:idInitPos] if str(id).isnumeric(): currentCategory = Category(int(id), title) currentCategoryByProd = CategoryByProduct( int(id), prodId) categoryList.append( currentCategoryByProd.getValuesString()) # if currentCategoryByProd.executeInsertStatement(cursor): # pass # else: # print("insertion failed:", currentCategoryByProd.toString()) # categoryList.append(currentCategory) self.mapCategorioes[id] = currentCategory else: # tratando um caso chato em que a string vem assim "title [guitar][213213]" string = string.replace("[", "(", 1) string = string.replace("]", ")", 1) idInitPos = string.find('[') idEndPos = string.find(']') id = string[idInitPos + 1:idEndPos] title = string[0:idInitPos] if str(id).isnumeric(): currentCategory = Category(int(id), title) currentCategoryByProd = CategoryByProduct( int(id), prodId) categoryList.append( currentCategoryByProd.getValuesString()) # if currentCategoryByProd.executeInsertStatement(cursor): # pass # else: # print("insertion failed:", currentCategoryByProd.toString()) # categoryList.append(currentCategory) self.mapCategorioes[id] = currentCategory else: print("inconsistent category: ", string) except Exception as e: print(e) return ",".join(categoryList)
def post(self): parser.add_argument('name', type=str) args = parser.parse_args() name = args['name'] try: category = Category(name=name) category.save() return category.json() except: return abort(400, message="Name cannot be null!")
def _get_categories(self, names_list: list): categories = [] if names_list: for category_name in names_list: existing_category = Category.query.filter_by( name=category_name).first() if not existing_category: existing_category = Category(name=category_name) existing_category.save() categories.append(existing_category) return categories
def create_category(self): ''' Add a new category to the database ''' try: category = self.get_argument('category', '') if Category.by_category(category) is not None: raise ValidationError("Category already exists") else: new_category = Category() new_category.category = category self.dbsession.add(new_category) self.dbsession.commit() self.redirect('/admin/view/categories') except ValidationError as error: self.render("admin/create/category.html", errors=[str(error), ])
def create_category(self): """ Add a new category to the database """ try: category = self.get_argument("category", "") if Category.by_category(category) is not None: raise ValidationError("Category already exists") else: new_category = Category() new_category.category = category self.dbsession.add(new_category) self.dbsession.commit() self.redirect("/admin/view/categories") except ValidationError as error: self.render("admin/create/category.html", errors=[str(error)])
def get(self): default_size = 10 summary_length = 200 cate_id = self.get_query_argument('cate', None) size = self.get_query_argument('size', default_size) categories = Category.list(self.current_user.id) user_id = self.current_user.id if cate_id: drafts = Post.drafts_by_category(user_id, int(cate_id), 0, int(size)) count = Post.count_drafts_by_category(user_id, cate_id) else: drafts = Post.drafts(user_id, 0, int(size)) count = Post.count_drafts(user_id) for draft in drafts: draft['author'] = self.current_user _html = markdown.markdown(draft.content) soup = BeautifulSoup(_html, 'html.parser') img = soup.find('img') if img: img['class'] = 'inner-img-limit' _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' draft['cover'] = img draft['summary'] = _text self.render('drafts.html', cate_id=cate_id, categories=categories, drafts=drafts)
def get(self): default_size = 10 summary_length = 200 need_pagination = False cate_id = self.get_query_argument('cate', None) size = self.get_query_argument('size', default_size) categories = Category.list(self.current_user.id) user_id = self.current_user.id if cate_id: posts = Post.list_by_category(user_id, int(cate_id), 0, int(size)) count = Post.count_posts_by_category(user_id, cate_id) else: count = Post.count_posts(user_id) posts = Post.list(user_id, 0, int(size)) if posts: need_pagination = count > len(posts) for post in posts: _html = markdown.markdown(post.content) soup = BeautifulSoup(_html, 'html.parser') img = soup.find('img') last_modified = post.last_modified if img: img['class'] = 'inner-img-limit' _text = soup.get_text() if _text and len(_text) > summary_length: _text = _text[0:summary_length] + '...' post['cover'] = img post['summary'] = _text post['author'] = self.current_user self.render('posts.html', cate_id=cate_id, categories=categories, posts=posts, page_size=size, need_pagination=int(need_pagination))
def add(self, msg: str) -> Expense: parsed_expense = self._parse_expense_msg(msg) category = Category.get_category_by_text(parsed_expense.category_text) return Expense.create( amount=parsed_expense.amount, category=category )
def add_category(type_flow_str: str, category_name: str): type_flow = calc_flow(type_flow_str) # сохранение категории в базу session = Database.get_instance().session() session.add(Category(category_name, type_flow)) session.commit() return f'Категория {category_name} добавлена!'
def category_posts(id): posts = Post().view_by_category(id) # return json.dumps(post) category = Category().view_single_category(id) return render_template('category_posts.html', posts=posts, category=category)
def test_add_flow_1000_bad_category_transport_in_base(self): self.session.add(Category('работа', TypeFlow.PROFIT)) self.session.commit() text_answer('Wallet добавь 1000 в работа') flow = self.session.query(Flow).all()[0] self.assertEqual(1000, flow.money) self.assertEqual('работа', flow.category.name)
def to_xml(self, parent): ''' Convert object to XML ''' box_elem = ET.SubElement(parent, "box") box_elem.set("gamelevel", str(self.game_level.number)) ET.SubElement(box_elem, "name").text = self.name ET.SubElement( box_elem, "operatingsystem").text = self._operating_system ET.SubElement(box_elem, "description").text = self._description ET.SubElement(box_elem, "flag_submission_type").text = FlagsSubmissionType(self.flag_submission_type).name ET.SubElement(box_elem, "difficulty").text = self._difficulty ET.SubElement(box_elem, "garbage").text = self.garbage if self.category_id: ET.SubElement(box_elem, "category").text = Category.by_id(self.category_id).category flags_elem = ET.SubElement(box_elem, "flags") flags_elem.set("count", str(len(self.flags))) for flag in self.flags: flag.to_xml(flags_elem) hints_elem = ET.SubElement(box_elem, "hints") count = 0 for hint in self.hints: if hint.flag_id is None: hint.to_xml(hints_elem) count += 1 hints_elem.set("count", str(count)) ips_elem = ET.SubElement(box_elem, "ipaddresses") ips_elem.set("count", str(len(self.ip_addresses))) for ip in self.ip_addresses: ip.to_xml(ips_elem) avatarfile = os.path.join(options.avatar_dir, self.avatar) if self.avatar and os.path.isfile(avatarfile): with open(avatarfile, mode='rb') as _avatar: data = _avatar.read() ET.SubElement(box_elem, "avatar").text = data.encode('base64') else: ET.SubElement(box_elem, "avatar").text = "none"
def to_xml(self, parent): ''' Convert object to XML ''' box_elem = ET.SubElement(parent, "box") box_elem.set("gamelevel", str(self.game_level.number)) ET.SubElement(box_elem, "name").text = self.name ET.SubElement( box_elem, "operatingsystem").text = self._operating_system ET.SubElement(box_elem, "description").text = self._description ET.SubElement(box_elem, "flag_submission_type").text = FlagsSubmissionType(self.flag_submission_type).name ET.SubElement(box_elem, "difficulty").text = self._difficulty ET.SubElement(box_elem, "garbage").text = self.garbage if self.category_id: ET.SubElement(box_elem, "category").text = Category.by_id(self.category_id).category flags_elem = ET.SubElement(box_elem, "flags") flags_elem.set("count", str(len(self.flags))) for flag in self.flags: flag.to_xml(flags_elem) hints_elem = ET.SubElement(box_elem, "hints") count = 0 for hint in self.hints: if hint.flag_id is None: hint.to_xml(hints_elem) count += 1 hints_elem.set("count", str(count)) ips_elem = ET.SubElement(box_elem, "ipaddresses") ips_elem.set("count", str(len(self.ip_addresses))) for ip in self.ip_addresses: ip.to_xml(ips_elem) with open(options.avatar_dir + '/' + self.avatar, mode='rb') as _avatar: data = _avatar.read() ET.SubElement(box_elem, "avatar").text = data.encode('base64')
def team_skills(self): ''' Returns team details in JSON form ''' uuid = self.get_argument('uuid', '') if uuid == '': user = self.get_current_user() if user: team = user.team else: team = Team.by_uuid(uuid) if team is not None: categories = Category.all() catlist = {} for cat in categories: catbox = Box.by_category(cat.id) if (len(catbox) > 0): catlist[int(cat.id)] = 0 for flag in team.flags: box = flag.box if box and box.category_id is not None: catlist[int(box.category_id)] += 1 skillvalues = [] for val in catlist: skillvalues.append(catlist[val]) self.write(str(skillvalues)) else: self.write({'error': 'Team does not exist'}) self.finish()
def category(): if request.method == "POST": category_name = request.form['category_name'] add_category = Category([category_name]).create_category() return redirect(url_for('index')) return render_template('category.html')
def export_game_objects(self, root): """ Exports the game objects to an XML doc. For the record, I hate XML with a passion. """ levels_elem = ET.SubElement(root, "gamelevels") levels_elem.set("count", "%s" % str(GameLevel.count())) for level in GameLevel.all()[1:]: level.to_xml(levels_elem) category_elem = ET.SubElement(root, "categories") category_elem.set("count", "%s" % str(Category.count())) for category in Category.all(): category.to_xml(category_elem) corps_elem = ET.SubElement(root, "corporations") corps_elem.set("count", "%s" % str(Corporation.count())) for corp in Corporation.all(): corp.to_xml(corps_elem)
def load_categories(self, data): data['categories'] = [ Category.get(id=category_id) for category_id in data['category_ids'] ] del data['category_ids'] return data
def show(category_id): schema = CategorySchema() category = Category.get(id=category_id) if not category: abort(404) return schema.dumps(category)
def create_category(self): text = self.window.ed_category.text() if text: category = Category(name=text) db.session.add(category) db.session.commit() self.window.ed_category.setText('') self.get_all_categories()
def find_dish(data): field = data['field'] search = data['search'] if field == 'category': category = Category.get(Category.title == search) search = category.id query_dish = Dish.select().where(get_model_field(Dish, field) == search) return transform_query_to_array(query_dish)
def load_from_sheet(a_sheet): AssetColl = [] for rowidx in range(a_sheet.nrows): if a_sheet.cell(rowidx, 1).value == 'Class & Category' or \ a_sheet.cell(rowidx, 1).value == 'Class Code' or \ a_sheet.cell(rowidx, 1).value == 'nvarchar' or \ a_sheet.cell(rowidx, 1).value == '' or \ a_sheet.cell(rowidx, 1).value == 20.0: continue iterAsset = Category() iterAsset.class_code = a_sheet.cell(rowidx, 1).value iterAsset.description = a_sheet.cell(rowidx, 2).value iterAsset.category_code = a_sheet.cell(rowidx, 3).value iterAsset.category_description = a_sheet.cell(rowidx, 4).value AssetColl.append(iterAsset) return AssetColl
def delete(category_id): category = Category.get(id=category_id) if not category: abort(404) category.delete() db.commit() return '', 204
def findOneById(id_cat): conn = ConnectionDB().getConnection() cursor = conn.cursor() try: cursor.execute('SELECT * FROM categories WHERE id = ?', (id_cat, )) row = cursor.fetchone() category = Category(id_cat, row[1]) return category except sqlite3.Error as error: print(error.with_traceback())
def findOneByName(name): conn = ConnectionDB().getConnection() cursor = conn.cursor() try: cursor.execute('SELECT * FROM categories WHERE name = ?', (name, )) row = cursor.fetchone() category = Category(row[0], name) return category except sqlite3.Error as error: print(error.with_traceback())
def del_category(self): ''' Delete a category ''' cat = Category.by_uuid(self.get_argument('uuid', '')) if cat is not None: logging.info("Delete category: %s" % cat.category) self.dbsession.delete(cat) self.dbsession.commit() self.redirect('/admin/view/categories') else: self.render('admin/view/categories.html', errors=["Category does not exist in database."])
def findAll(): conn = ConnectionDB().getConnection() cursor = conn.cursor() try: categories = [] for row in cursor.execute("SELECT * FROM categories"): categories.append(Category(row[0], row[1])) return categories except sqlite3.Error as error: print(error.with_traceback())
def put_new_category(): session = get_session() content = g.data locale = get_post_locale(session) category = Category() name_id = str(uuid4()) locale_string = LocaleString(id=name_id, locale=locale, text=content['name']) category.name_id = name_id category.name.set(locale_string) category.label = content['label'] session.add(category) session.commit() session.close() return 'ok'
def del_category(self): ''' Delete a category ''' cat = Category.by_uuid(self.get_argument('uuid', '')) if cat is not None: logging.info("Delete category: %s" % cat.category) self.dbsession.delete(cat) self.dbsession.commit() self.redirect('/admin/view/categories') else: self.render('admin/view/categories.html', errors=["Category does not exist in database."] )
def create(): schema = CategorySchema() try: data = schema.load(request.get_json()) category = Category(**data) db.commit() except ValidationError as err: return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(category), 201
def del_category(self): """ Delete a category """ cat = Category.by_uuid(self.get_argument("uuid", "")) if cat is not None: logging.info("Delete category: %s" % cat.category) self.dbsession.delete(cat) self.dbsession.commit() self.redirect("/admin/view/categories") else: self.render( "admin/view/categories.html", errors=["Category does not exist in database."], )
def load_data_into_models(data): categories = [] for item in data['category_data']: c = Category(**item) categories.append(c) players = [] for player in data['player_data']: p = Player(**player) players.append(p) populated_models = {'players': players, 'categories': categories} return populated_models
def add_category() -> Category: category_name = input("The name of the new category: ") parent_id = int(input("To which parent category does it belong (parent_id): ")) new_budgeted_amount = float(input("Write budgeted amount: ")) category = Category(name=category_name, parent_id=parent_id) session.add(category) session.commit() # TODO: If more than one person creates a new category at the same time we might get incorrect data here new_category = session.query(Category).order_by(Category.id.desc()).first() category_budget = CategoryBudget(budgeted_amount=new_budgeted_amount, category_id=new_category.id, datetime=datetime.now()) session.add(category_budget) session.commit() return new_category
def findByRecipe(id_recipe): conn = ConnectionDB().getConnection() cursor = conn.cursor() try: categories = [] for row in cursor.execute( '''SELECT categories.id, categories.name FROM map_recipe_category JOIN categories on categories.id=map_recipe_category.id_category WHERE id_recipe = ?''', (id_recipe, )): categories.append(Category(row[0], row[1])) return categories except sqlite3.Error as error: print(error.with_traceback())
def edit_category(self): ''' Updates category object in the database ''' try: cat = Category.by_uuid(self.get_argument('uuid', '')) if cat is None: raise ValidationError("Category does not exist") category = self.get_argument('category', '') if category != cat.category: logging.info("Updated category name %s -> %s" % ( cat.category, category )) cat.category = category self.dbsession.add(cat) self.dbsession.commit() self.redirect('/admin/view/categories') except ValidationError as error: self.render("admin/view/categories.html", errors=[str(error), ])
def to_dict(self): ''' Returns editable data as a dictionary ''' corp = Corporation.by_id(self.corporation_id) game_level = GameLevel.by_id(self.game_level_id) cat = Category.by_id(self.category_id) if cat: category = cat.uuid else: category = "" return { 'name': self.name, 'uuid': self.uuid, 'corporation': corp.uuid, 'category': category, 'operating_system': self.operating_system, 'description': self._description, 'difficulty': self.difficulty, 'game_level': game_level.uuid, 'flag_submission_type': self.flag_submission_type, 'flaglist': self.flaglist(self.id) }
def create_box(self): ''' Create a box object ''' try: game_level = self.get_argument('game_level', '') corp_uuid = self.get_argument('corporation_uuid', '') if Box.by_name(self.get_argument('name', '')) is not None: raise ValidationError("Box name already exists") elif Corporation.by_uuid(corp_uuid) is None: raise ValidationError("Corporation does not exist") elif GameLevel.by_number(game_level) is None: raise ValidationError("Game level does not exist") else: corp = Corporation.by_uuid(corp_uuid) level = GameLevel.by_number(game_level) box = Box(corporation_id=corp.id, game_level_id=level.id) box.name = self.get_argument('name', '') box.description = self.get_argument('description', '') box.flag_submission_type = FlagsSubmissionType[self.get_argument('flag_submission_type','')] box.difficulty = self.get_argument('difficulty', '') box.operating_system = self.get_argument('operating_system', '?') cat = Category.by_uuid(self.get_argument('category_uuid', '')) if cat is not None: box.category_id = cat.id else: box.category_id = None # Avatar avatar_select = self.get_argument('box_avatar_select', '') if avatar_select and len(avatar_select) > 0: box._avatar = avatar_select elif hasattr(self.request, 'files') and 'avatar' in self.request.files: box.avatar = self.request.files['avatar'][0]['body'] self.dbsession.add(box) self.dbsession.commit() self.redirect("/admin/view/game_objects#%s" % box.uuid) except ValidationError as error: self.render('admin/create/box.html', errors=[str(error), ])
def edit_boxes(self): ''' Edit existing boxes in the database, and log the changes ''' try: box = Box.by_uuid(self.get_argument('uuid', '')) if box is None: raise ValidationError("Box does not exist") # Name name = self.get_argument('name', '') if name != box.name: if Box.by_name(name) is None: logging.info("Updated box name %s -> %s" % ( box.name, name, )) box.name = name else: raise ValidationError("Box name already exists") # Corporation corp = Corporation.by_uuid(self.get_argument('corporation_uuid')) if corp is not None and corp.id != box.corporation_id: logging.info("Updated %s's corporation %s -> %s" % ( box.name, box.corporation_id, corp.id, )) box.corporation_id = corp.id elif corp is None: raise ValidationError("Corporation does not exist") # Category cat = Category.by_uuid(self.get_argument('category_uuid')) if cat is not None and cat.id != box.category_id: logging.info("Updated %s's category %s -> %s" % ( box.name, box.category_id, cat.id, )) box.category_id = cat.id elif cat is None and cat != box.category_id: logging.info("Updated %s's category %s -> None" % ( box.name, box.category_id, )) box.category_id = None # System Type ostype = self.get_argument('operating_system') if ostype is not None and ostype != box.operating_system: logging.info("Updated %s's system type %s -> %s" % ( box.name, box.operating_system, ostype, )) box.operating_system = ostype # Description description = self.get_argument('description', '') if description != box._description: logging.info("Updated %s's description %s -> %s" % ( box.name, box.description, description, )) box.description = description # Difficulty difficulty = self.get_argument('difficulty', '') if difficulty != box.difficulty: logging.info("Updated %s's difficulty %s -> %s" % ( box.name, box.difficulty, difficulty, )) box.difficulty = difficulty # Flag submission type flag_submission_type = self.get_argument('flag_submission_type', '') if flag_submission_type is not None and flag_submission_type != box.flag_submission_type: logging.info("Updated %s's flag submission type %s -> %s" % ( box.name, box.flag_submission_type, flag_submission_type )) box.flag_submission_type = flag_submission_type # Avatar avatar_select = self.get_argument('box_avatar_select', '') if avatar_select and len(avatar_select) > 0: box._avatar = avatar_select elif 'avatar' in self.request.files: box.avatar = self.request.files['avatar'][0]['body'] self.dbsession.add(box) self.dbsession.commit() self.redirect("/admin/view/game_objects#%s" % box.uuid) except ValidationError as error: self.render("admin/view/game_objects.html", errors=[str(error), ])