def add(title, content, c_name, c_id, tags): summary = content[0:80] + '...' html = markdown.markdown(content) diary = { "_id": Kid.kid(), "title": title, "category": c_name, "category_id": int(c_id), "tags": tags, "content": content, "html": html, "summary": markdown.markdown(summary), "publish_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") } db.diaries.save(diary) # save category Category.update_diary(c_id, diary.get('_id'), title, diary.get('publish_time')) if tags is not None: # save tags for tag in tags: Tag.add(tag, diary) return
def update(_id, title, content, c_name, c_id, tags): summary = content[0:80] + '...' html = markdown.markdown(content) diary = { "title": title, "content": content, "category": c_name, "category_id": int(c_id), "tags": tags, "summary": markdown.markdown(summary), "html": html, "update_time": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") } publish_time = Diary.get_detail(_id).get('publish_time') last_cid = Diary.get_detail(_id).get('category_id') last_tags = Diary.get_detail(_id).get('tags') db.diaries.update({'_id': int(_id)}, {'$set': diary}) #Save for category Category.update_diary(c_id, _id, title, publish_time, last_cid) if last_tags is not None: # delete it from old tags Tag.del_diary(_id) if tags is not None: diary = Diary.get_detail(_id) # save tags for tag in tags: Tag.add(tag, diary) return
def prediction(self, file, file_to_save_path): ## main here: ## #time_now = time.mktime((2016, 4, 26, 14, 45,45,4,120,-1)) # time_now = 01_May_2015 time_now = time.mktime(time.localtime()) # By Bowen Huang 04-27-2016 # Instant of class Category categories = Category() # Run categorize to obtain categories and internal results categories.categorize(file, file_to_save_path) # Assume last_visit_elapsed_variable is a global variable global last_visit_elapsed_variable last_visit_elapsed_variable = last_visit_elapsed(categories.inp_dataset,categories.inter_arrivals,categories.inter_arrival_cnt,categories.user_id,time_now) print #print "last visit elapsed:", last_visit_elapsed KDEs = KDE_plt(categories.categories,categories.inter_arrivals) MLE_plt(categories.categories,categories.inter_arrivals,categories.inter_arrival_means) ###recommendations#### recoms = [] for i in range(0,len(categories.categories)): num_of_recom = int(math.floor(0.01*len(categories.categories[i][0])))+1 #top 1% customers for recommendation temp_recom = [-1]*num_of_recom temp_cat = categories.categories[i][0] for n in range(0,num_of_recom): current_index=0 #print "temp_cat_prob",temp_cat_prob for j in range(0,len(temp_cat)): if last_visit_elapsed_variable[temp_cat[j]]>last_visit_elapsed_variable[temp_cat[current_index]]: # print "here for j= ",j current_index=j temp_recom[n]=temp_cat[current_index] temp_cat.pop(current_index) recoms.append(temp_recom) print "The top 1 percent customers to recommend for target marketing:" print fh = open("./uploads/target_selection.txt", "w") for i in range(0,len(recoms)): for j in range(0,len(recoms[i])):#format in each line: (acc_id,category,priority) fh.writelines(str(categories.acc_id[recoms[i][j]])+","+str(i)+","+str(j+1)) fh.write("\n") print "Account ID",categories.acc_id[recoms[i][j]],"has priority", j+1," in customer category", i print # store the number of categories self.category_num = len(categories.categories)
def get_averages_per_question(self): category = Category(Category.BASE_URL) views = [] votes = [] for page_num in count(1): soup = self.make_soup(category.url+'?page='+str(page_num)+'&sort=votes') string_results = self.parse_for_title(soup.findAll('div', {'class': 'views supernova'})) view_results = self.parse_results_for_digits(string_results) vote_results = self.parse_results_for_digits( [span.text for span in soup.findAll("span", {'class': 'vote-count-post'})]) views += view_results votes += vote_results if page_num == self.max_pages: break category.views = views category.votes = votes category.samples = len(views) return category
async def show_user_categories(message: types.Message): """Отправляет список всех категорий адресов пользователя""" all_categories = Category(message.from_user.id).get_all_categories() if not all_categories: await message.answer( "Список категорий пуст.\n\n" "*Для добавления категории введите* /addcat\n\n" "Мои адреса: /addresses\n\n" "Начальный экран: /start", parse_mode='Markdown') return categories_rows = [ f"*{category_one.name}* ({category_one.addr_counter})\n" f"/showcataddr{category_one.id} - просмотреть адреса категории\n" f"{show_delcat_title(category_one.id, category_one.addr_counter)}" for category_one in all_categories ] answer_message = "Список категорий:\n\n" + "\n\n" \ .join(categories_rows) + \ "\n\nДобавить категорию: /addcat" + \ "\n\nМои адреса: /addresses" + \ "\n\nНачальный экран: /start" await message.answer(answer_message, parse_mode='Markdown')
async def add_address(message: types.Message): """Добавляет новый адрес""" global input_mode answer_message = '' try: # Добавляем адрес if input_mode == 0: yandex_map = YandexMap(YANDEX_API_KEY) address = str(message.text).replace('*', '') yandex_answer = yandex_map.get_geocode(address) link_to_yamaps = 'Ничего не найдено, попробуйте повторить попытку позже' is_shown = 0 # Если пришел нормальный ответ от API (два числа через пробел) if yandex_answer != -1: arr = str(yandex_answer).split() if len(arr) == 2: long = arr[0] wide = arr[1] link_to_yamaps = yandex_map.form_href_to_yamap(long, wide) is_shown = 1 Address().add_address(address, link_to_yamaps, message.from_user.id, is_shown) answer_message = (f"Ссылка на Яндекс.Карты: {link_to_yamaps}.\n\n") # Добавляем категорию elif input_mode == 1: input_mode = 0 cat_name = str(message.text).replace('*', '') Category(message.from_user.id).add_category(cat_name) answer_message = ( f"Новая категория успешно добавлена: *{cat_name}*\n\n") except exceptions.NotCorrectMessage as e: await message.answer(str(e)) return answer_message += (f"Мои адреса: /addresses\n\n" f"Мои категории: /categories\n\n" f"Главное меню: /start\n\n") await message.answer(answer_message, parse_mode='Markdown')
def del_diary(_id): db.diaries.remove({'_id': int(_id)}) Category.del_diary(_id) return
def add_category(self, cat_name: str) -> None: if cat_name not in self.categories.keys(): self.categories[cat_name] = Category(cat_name)