_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q5000
MPostHist.create_post_history
train
def create_post_history(raw_data): ''' Create the history of certain post. ''' uid = tools.get_uuid() TabPostHist.create( uid=uid, title=raw_data.title, post_id=raw_data.uid, user_name=raw_data.user_name, cnt_md=raw_data.cnt_md, time_update=tools.timestamp(), logo=raw_data.logo, ) return True
python
{ "resource": "" }
q5001
ListHandler.ajax_list_catalog
train
def ajax_list_catalog(self, catid): ''' Get posts of certain catid. In Json. 根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式 ''' out_arr = {} for catinfo in MPost2Catalog.query_postinfo_by_cat(catid): out_arr[catinfo.uid] = catinfo.title json.dump(out_arr, self)
python
{ "resource": "" }
q5002
ListHandler.ajax_kindcat_arr
train
def ajax_kindcat_arr(self, kind_sig): ''' Get the sub category. 根据kind值(kind_sig)获取相应分类,返回Json格式 ''' out_arr = {} for catinfo in MCategory.query_kind_cat(kind_sig): out_arr[catinfo.uid] = catinfo.name json.dump(out_arr, self)
python
{ "resource": "" }
q5003
ListHandler.list_catalog
train
def list_catalog(self, cat_slug, **kwargs): ''' listing the posts via category 根据分类(cat_slug)显示分类列表 ''' post_data = self.get_post_data() tag = post_data.get('tag', '') def get_pager_idx(): ''' Get the pager index. ''' cur_p = kwargs.get('cur_p') the_num = int(cur_p) if cur_p else 1 the_num = 1 if the_num < 1 else the_num return the_num current_page_num = get_pager_idx() cat_rec = MCategory.get_by_slug(cat_slug) if not cat_rec: return False num_of_cat = MPost2Catalog.count_of_certain_category(cat_rec.uid, tag=tag) page_num = int(num_of_cat / CMS_CFG['list_num']) + 1 cat_name = cat_rec.name kwd = {'cat_name': cat_name, 'cat_slug': cat_slug, 'title': cat_name, 'router': router_post[cat_rec.kind], 'current_page': current_page_num, 'kind': cat_rec.kind, 'tag': tag} # Todo: review the following codes. if self.order: tmpl = 'list/catalog_list.html' else: tmpl = 'list/category_list.html' infos = MPost2Catalog.query_pager_by_slug( cat_slug, current_page_num, tag=tag, order=self.order ) # ToDo: `gen_pager_purecss` should not use any more. self.render(tmpl, catinfo=cat_rec, infos=infos, pager=tools.gen_pager_purecss( '/list/{0}'.format(cat_slug), page_num, current_page_num), userinfo=self.userinfo, html2text=html2text, cfg=CMS_CFG, kwd=kwd, router=router_post[cat_rec.kind])
python
{ "resource": "" }
q5004
send_mail
train
def send_mail(to_list, sub, content, cc=None): ''' Sending email via Python. ''' sender = SMTP_CFG['name'] + "<" + SMTP_CFG['user'] + ">" msg = MIMEText(content, _subtype='html', _charset='utf-8') msg['Subject'] = sub msg['From'] = sender msg['To'] = ";".join(to_list) if cc: msg['cc'] = ';'.join(cc) try: # Using SMTP_SSL. The alinyun ECS has masked the 25 port since 9,2016. smtper = smtplib.SMTP_SSL(SMTP_CFG['host'], port=994) smtper.login(SMTP_CFG['user'], SMTP_CFG['pass']) smtper.sendmail(sender, to_list, msg.as_string()) smtper.close() return True except: return False
python
{ "resource": "" }
q5005
PostAjaxHandler.viewinfo
train
def viewinfo(self, postinfo): ''' View the info ''' out_json = { 'uid': postinfo.uid, 'time_update': postinfo.time_update, 'title': postinfo.title, 'cnt_html': tornado.escape.xhtml_unescape(postinfo.cnt_html), } self.write(json.dumps(out_json))
python
{ "resource": "" }
q5006
PostAjaxHandler.count_plus
train
def count_plus(self, uid): ''' Ajax request, that the view count will plus 1. ''' self.set_header("Content-Type", "application/json") output = { # ToDo: Test the following codes. # MPost.__update_view_count_by_uid(uid) else 0, 'status': 1 if MPost.update_misc(uid, count=1) else 0 } # return json.dump(output, self) self.write(json.dumps(output))
python
{ "resource": "" }
q5007
PostAjaxHandler.p_recent
train
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True): ''' List posts that recent edited, partially. ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MPost.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent posts.', 'with_catalog': with_catalog, 'with_date': with_date, 'kind': kind, 'current_page': current_page_number, 'post_count': MPost.get_counts(), 'router': config.router_post[kind], } self.render('admin/post_ajax/post_list.html', kwd=kwd, view=MPost.query_recent(num=20, kind=kind), infos=MPost.query_pager_by_slug( kind=kind, current_page_num=current_page_number ), format_date=tools.format_date, userinfo=self.userinfo, cfg=CMS_CFG, )
python
{ "resource": "" }
q5008
PostAjaxHandler.j_delete
train
def j_delete(self, *args): ''' Delete the post, but return the JSON. ''' uid = args[0] current_infor = MPost.get_by_uid(uid) tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) is_deleted = MPost.delete(uid) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if is_deleted: output = { 'del_info': 1, 'cat_slug': tslug.slug, 'cat_id': tslug.uid, 'kind': current_infor.kind } else: output = { 'del_info': 0, } return json.dump(output, self)
python
{ "resource": "" }
q5009
run_init_tables
train
def run_init_tables(*args): ''' Run to init tables. ''' print('--') create_table(TabPost) create_table(TabTag) create_table(TabMember) create_table(TabWiki) create_table(TabLink) create_table(TabEntity) create_table(TabPostHist) create_table(TabWikiHist) create_table(TabCollect) create_table(TabPost2Tag) create_table(TabRel) create_table(TabEvaluation) create_table(TabUsage) create_table(TabReply) create_table(TabUser2Reply) create_table(TabRating) create_table(TabEntity2User) create_table(TabLog)
python
{ "resource": "" }
q5010
gen_whoosh_database
train
def gen_whoosh_database(kind_arr, post_type): ''' kind_arr, define the `type` except Post, Page, Wiki post_type, define the templates for different kind. ''' SITE_CFG['LANG'] = SITE_CFG.get('LANG', 'zh') # Using jieba lib for Chinese. if SITE_CFG['LANG'] == 'zh' and ChineseAnalyzer: schema = Schema(title=TEXT(stored=True, analyzer=ChineseAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=ChineseAnalyzer())) else: schema = Schema(title=TEXT(stored=True, analyzer=StemmingAnalyzer()), catid=TEXT(stored=True), type=TEXT(stored=True), link=ID(unique=True, stored=True), content=TEXT(stored=True, analyzer=StemmingAnalyzer())) whoosh_db = 'database/whoosh' if os.path.exists(whoosh_db): create_idx = open_dir(whoosh_db) else: os.makedirs(whoosh_db) create_idx = create_in(whoosh_db, schema) writer = create_idx.writer() for switch in [True, False]: do_for_post(writer, rand=switch, doc_type=post_type['1']) do_for_wiki(writer, rand=switch, doc_type=post_type['1']) do_for_page(writer, rand=switch, doc_type=post_type['1']) for kind in kind_arr: do_for_app(writer, rand=switch, kind=kind, doc_type=post_type) writer.commit()
python
{ "resource": "" }
q5011
PublishHandler.view_class2
train
def view_class2(self, fatherid=''): ''' Publishing from 2ed range category. ''' if self.is_admin(): pass else: return False kwd = {'class1str': self.format_class2(fatherid), 'parentid': '0', 'parentlist': MCategory.get_parent_list()} if fatherid.endswith('00'): self.render('misc/publish/publish2.html', userinfo=self.userinfo, kwd=kwd) else: catinfo = MCategory.get_by_uid(fatherid) self.redirect('/{1}/_cat_add/{0}'.format(fatherid, router_post[catinfo.kind]))
python
{ "resource": "" }
q5012
MEvaluation.app_evaluation_count
train
def app_evaluation_count(app_id, value=1): ''' Get the Evalution sum. ''' return TabEvaluation.select().where( (TabEvaluation.post_id == app_id) & (TabEvaluation.value == value) ).count()
python
{ "resource": "" }
q5013
MEvaluation.get_by_signature
train
def get_by_signature(user_id, app_id): ''' get by user ID, and app ID. ''' try: return TabEvaluation.get( (TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id) ) except: return None
python
{ "resource": "" }
q5014
MEvaluation.add_or_update
train
def add_or_update(user_id, app_id, value): ''' Editing evaluation. ''' rec = MEvaluation.get_by_signature(user_id, app_id) if rec: entry = TabEvaluation.update( value=value, ).where(TabEvaluation.uid == rec.uid) entry.execute() else: TabEvaluation.create( uid=tools.get_uuid(), user_id=user_id, post_id=app_id, value=value, )
python
{ "resource": "" }
q5015
PageAjaxHandler.view
train
def view(self, rec): ''' view the post. ''' out_json = { 'uid': rec.uid, 'time_update': rec.time_update, 'title': rec.title, 'cnt_html': tornado.escape.xhtml_unescape(rec.cnt_html), } self.write(json.dumps(out_json))
python
{ "resource": "" }
q5016
PageAjaxHandler.j_count_plus
train
def j_count_plus(self, slug): ''' plus count via ajax. ''' output = {'status': 1 if MWiki.view_count_plus(slug) else 0} return json.dump(output, self)
python
{ "resource": "" }
q5017
PageAjaxHandler.p_list
train
def p_list(self, kind, cur_p='', ): ''' List the post . ''' if cur_p == '': current_page_number = 1 else: current_page_number = int(cur_p) current_page_number = 1 if current_page_number < 1 else current_page_number pager_num = int(MWiki.total_number(kind) / CMS_CFG['list_num']) kwd = { 'pager': '', 'title': 'Recent pages.', 'kind': kind, 'current_page': current_page_number, 'page_count': MWiki.get_counts(), } self.render('admin/page_ajax/page_list.html', postrecs=MWiki.query_pager_by_kind(kind=kind, current_page_num=current_page_number), kwd=kwd)
python
{ "resource": "" }
q5018
MUser.set_sendemail_time
train
def set_sendemail_time(uid): ''' Set the time that send E-mail to user. ''' entry = TabMember.update( time_email=tools.timestamp(), ).where(TabMember.uid == uid) entry.execute()
python
{ "resource": "" }
q5019
MUser.check_user
train
def check_user(user_id, u_pass): ''' Checking the password by user's ID. ''' user_count = TabMember.select().where(TabMember.uid == user_id).count() if user_count == 0: return -1 the_user = TabMember.get(uid=user_id) if the_user.user_pass == tools.md5(u_pass): return 1 return 0
python
{ "resource": "" }
q5020
MUser.check_user_by_name
train
def check_user_by_name(user_name, u_pass): ''' Checking the password by user's name. ''' the_query = TabMember.select().where(TabMember.user_name == user_name) if the_query.count() == 0: return -1 the_user = the_query.get() if the_user.user_pass == tools.md5(u_pass): return 1 return 0
python
{ "resource": "" }
q5021
MUser.update_pass
train
def update_pass(user_id, newpass): ''' Update the password of a user. ''' out_dic = {'success': False, 'code': '00'} entry = TabMember.update(user_pass=tools.md5(newpass)).where(TabMember.uid == user_id) entry.execute() out_dic['success'] = True return out_dic
python
{ "resource": "" }
q5022
MUser.update_time_reset_passwd
train
def update_time_reset_passwd(user_name, the_time): ''' Update the time when user reset passwd. ''' entry = TabMember.update( time_reset_passwd=the_time, ).where(TabMember.user_name == user_name) try: entry.execute() return True except: return False
python
{ "resource": "" }
q5023
MUser.update_role
train
def update_role(u_name, newprivilege): ''' Update the role of the usr. ''' entry = TabMember.update( role=newprivilege ).where(TabMember.user_name == u_name) try: entry.execute() return True except: return False
python
{ "resource": "" }
q5024
MUser.update_time_login
train
def update_time_login(u_name): ''' Update the login time for user. ''' entry = TabMember.update( time_login=tools.timestamp() ).where( TabMember.user_name == u_name ) entry.execute()
python
{ "resource": "" }
q5025
MUser.delete_by_user_name
train
def delete_by_user_name(user_name): ''' Delete user in the database by `user_name`. ''' try: del_count = TabMember.delete().where(TabMember.user_name == user_name) del_count.execute() return True except: return False
python
{ "resource": "" }
q5026
MUser.delete
train
def delete(user_id): ''' Delele the user in the database by `user_id`. ''' try: del_count = TabMember.delete().where(TabMember.uid == user_id) del_count.execute() return True except: return False
python
{ "resource": "" }
q5027
get_meta
train
def get_meta(catid, sig): ''' Get metadata of dataset via ID. ''' meta_base = './static/dataset_list' if os.path.exists(meta_base): pass else: return False pp_data = {'logo': '', 'kind': '9'} for wroot, wdirs, wfiles in os.walk(meta_base): for wdir in wdirs: if wdir.lower().endswith(sig): # Got the dataset of certain ID. ds_base = pathlib.Path(os.path.join(wroot, wdir)) for uu in ds_base.iterdir(): if uu.name.endswith('.xlsx'): meta_dic = chuli_meta('u' + sig[2:], uu) pp_data['title'] = meta_dic['title'] pp_data['cnt_md'] = meta_dic['anytext'] pp_data['user_name'] = 'admin' pp_data['def_cat_uid'] = catid pp_data['gcat0'] = catid pp_data['def_cat_pid'] = catid[:2] + '00' pp_data['extinfo'] = {} elif uu.name.startswith('thumbnail_'): pp_data['logo'] = os.path.join(wroot, wdir, uu.name).strip('.') return pp_data
python
{ "resource": "" }
q5028
update_label
train
def update_label(signature, post_data): ''' Update the label when updating. ''' current_tag_infos = MPost2Label.get_by_uid(signature).objects() if 'tags' in post_data: pass else: return False tags_arr = [x.strip() for x in post_data['tags'].split(',')] for tag_name in tags_arr: if tag_name == '': pass else: MPost2Label.add_record(signature, tag_name, 1) for cur_info in current_tag_infos: if cur_info.tag_name in tags_arr: pass else: MPost2Label.remove_relation(signature, cur_info.tag_id)
python
{ "resource": "" }
q5029
PostHandler.index
train
def index(self): ''' The default page of POST. ''' self.render('post_{0}/post_index.html'.format(self.kind), userinfo=self.userinfo, kwd={'uid': '', })
python
{ "resource": "" }
q5030
PostHandler._view_or_add
train
def _view_or_add(self, uid): ''' Try to get the post. If not, to add the wiki. ''' postinfo = MPost.get_by_uid(uid) if postinfo: self.viewinfo(postinfo) elif self.userinfo: self._to_add(uid=uid) else: self.show404()
python
{ "resource": "" }
q5031
PostHandler._to_add
train
def _to_add(self, **kwargs): ''' Used for info1. ''' if 'catid' in kwargs: catid = kwargs['catid'] return self._to_add_with_category(catid) else: if 'uid' in kwargs and MPost.get_by_uid(kwargs['uid']): # todo: # self.redirect('/{0}/edit/{1}'.format(self.app_url_name, uid)) uid = kwargs['uid'] else: uid = '' self.render('post_{0}/post_add.html'.format(self.kind), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), userinfo=self.userinfo, kwd={'uid': uid, })
python
{ "resource": "" }
q5032
PostHandler._to_edit
train
def _to_edit(self, infoid): ''' render the HTML page for post editing. ''' postinfo = MPost.get_by_uid(infoid) if postinfo: pass else: return self.show404() if 'def_cat_uid' in postinfo.extinfo: catid = postinfo.extinfo['def_cat_uid'] elif 'gcat0' in postinfo.extinfo: catid = postinfo.extinfo['gcat0'] else: catid = '' if len(catid) == 4: pass else: catid = '' catinfo = None p_catinfo = None post2catinfo = MPost2Catalog.get_first_category(postinfo.uid) if post2catinfo: catid = post2catinfo.tag_id catinfo = MCategory.get_by_uid(catid) if catinfo: p_catinfo = MCategory.get_by_uid(catinfo.pid) kwd = { 'gcat0': catid, 'parentname': '', 'catname': '', 'parentlist': MCategory.get_parent_list(), 'userip': self.request.remote_ip, 'extinfo': json.dumps(postinfo.extinfo, indent=2, ensure_ascii=False), } if self.filter_view: tmpl = 'autogen/edit/edit_{0}.html'.format(catid) else: tmpl = 'post_{0}/post_edit.html'.format(self.kind) logger.info('Meta template: {0}'.format(tmpl)) self.render( tmpl, kwd=kwd, postinfo=postinfo, catinfo=catinfo, pcatinfo=p_catinfo, userinfo=self.userinfo, cat_enum=MCategory.get_qian2(catid[:2]), tag_infos=MCategory.query_all(by_order=True, kind=self.kind), tag_infos2=MCategory.query_all(by_order=True, kind=self.kind), app2tag_info=MPost2Catalog.query_by_entity_uid(infoid, kind=self.kind).objects(), app2label_info=MPost2Label.get_by_uid(infoid).objects() )
python
{ "resource": "" }
q5033
PostHandler._gen_last_current_relation
train
def _gen_last_current_relation(self, post_id): ''' Generate the relation for the post and last post viewed. ''' last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') self.set_secure_cookie('last_post_uid', post_id) if last_post_id and MPost.get_by_uid(last_post_id): self._add_relation(last_post_id, post_id)
python
{ "resource": "" }
q5034
PostHandler.fetch_additional_posts
train
def fetch_additional_posts(self, uid): ''' fetch the rel_recs, and random recs when view the post. ''' cats = MPost2Catalog.query_by_entity_uid(uid, kind=self.kind) cat_uid_arr = [] for cat_rec in cats: cat_uid = cat_rec.tag_id cat_uid_arr.append(cat_uid) logger.info('info category: {0}'.format(cat_uid_arr)) rel_recs = MRelation.get_app_relations(uid, 8, kind=self.kind).objects() logger.info('rel_recs count: {0}'.format(rel_recs.count())) if cat_uid_arr: rand_recs = MPost.query_cat_random(cat_uid_arr[0], limit=4 - rel_recs.count() + 4) else: rand_recs = MPost.query_random(num=4 - rel_recs.count() + 4, kind=self.kind) return rand_recs, rel_recs
python
{ "resource": "" }
q5035
PostHandler._delete
train
def _delete(self, *args, **kwargs): ''' delete the post. ''' _ = kwargs uid = args[0] current_infor = MPost.get_by_uid(uid) if MPost.delete(uid): tslug = MCategory.get_by_uid(current_infor.extinfo['def_cat_uid']) MCategory.update_count(current_infor.extinfo['def_cat_uid']) if router_post[self.kind] == 'info': url = "filter" id_dk8 = current_infor.extinfo['def_cat_uid'] else: url = "list" id_dk8 = tslug.slug self.redirect('/{0}/{1}'.format(url, id_dk8)) else: self.redirect('/{0}/{1}'.format(router_post[self.kind], uid))
python
{ "resource": "" }
q5036
PostHandler._chuli_cookie_relation
train
def _chuli_cookie_relation(self, app_id): ''' The current Info and the Info viewed last should have some relation. And the last viewed Info could be found from cookie. ''' last_app_uid = self.get_secure_cookie('use_app_uid') if last_app_uid: last_app_uid = last_app_uid.decode('utf-8') self.set_secure_cookie('use_app_uid', app_id) if last_app_uid and MPost.get_by_uid(last_app_uid): self._add_relation(last_app_uid, app_id)
python
{ "resource": "" }
q5037
PostHandler._to_edit_kind
train
def _to_edit_kind(self, post_uid): ''' Show the page for changing the category. ''' if self.userinfo and self.userinfo.role[1] >= '3': pass else: self.redirect('/') postinfo = MPost.get_by_uid(post_uid, ) json_cnt = json.dumps(postinfo.extinfo, indent=True) kwd = {} self.render('man_info/post_kind.html', postinfo=postinfo, sig_dic=router_post, userinfo=self.userinfo, json_cnt=json_cnt, kwd=kwd)
python
{ "resource": "" }
q5038
PostHandler._change_kind
train
def _change_kind(self, post_uid): ''' To modify the category of the post, and kind. ''' post_data = self.get_post_data() logger.info('admin post update: {0}'.format(post_data)) MPost.update_misc(post_uid, kind=post_data['kcat']) # self.update_category(post_uid) update_category(post_uid, post_data) self.redirect('/{0}/{1}'.format(router_post[post_data['kcat']], post_uid))
python
{ "resource": "" }
q5039
EntityHandler.list
train
def list(self, cur_p=''): ''' Lists of the entities. ''' current_page_number = int(cur_p) if cur_p else 1 current_page_number = 1 if current_page_number < 1 else current_page_number kwd = { 'current_page': current_page_number } recs = MEntity.get_all_pager(current_page_num=current_page_number) self.render('misc/entity/entity_list.html', imgs=recs, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
{ "resource": "" }
q5040
EntityHandler.down
train
def down(self, down_uid): ''' Download the entity by UID. ''' down_url = MPost.get_by_uid(down_uid).extinfo.get('tag__file_download', '') print('=' * 40) print(down_url) str_down_url = str(down_url)[15:] if down_url: ment_id = MEntity.get_id_by_impath(str_down_url) if ment_id: MEntity2User.create_entity2user(ment_id, self.userinfo.uid) return True else: return False
python
{ "resource": "" }
q5041
EntityHandler.to_add
train
def to_add(self): ''' To add the entity. ''' kwd = { 'pager': '', } self.render('misc/entity/entity_add.html', cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
{ "resource": "" }
q5042
EntityHandler.add_entity
train
def add_entity(self): ''' Add the entity. All the information got from the post data. ''' post_data = self.get_post_data() if 'kind' in post_data: if post_data['kind'] == '1': self.add_pic(post_data) elif post_data['kind'] == '2': self.add_pdf(post_data) elif post_data['kind'] == '3': self.add_url(post_data) else: pass else: self.add_pic(post_data)
python
{ "resource": "" }
q5043
EntityHandler.add_pic
train
def add_pic(self, post_data): ''' Adding the picture. ''' img_entity = self.request.files['file'][0] filename = img_entity["filename"] if filename and allowed_file(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fileout: fileout.write(img_entity["body"]) path_save = os.path.join(signature[:2], outfilename) sig_save = os.path.join(signature[:2], signature) imgpath = os.path.join(outpath, signature + '_m.jpg') imgpath_sm = os.path.join(outpath, signature + '_sm.jpg') ptr_image = Image.open(os.path.join('static/upload', path_save)) tmpl_size = (768, 768) thub_size = (256, 256) (imgwidth, imgheight) = ptr_image.size if imgwidth < tmpl_size[0] and imgheight < tmpl_size[1]: tmpl_size = (imgwidth, imgheight) ptr_image.thumbnail(tmpl_size) im0 = ptr_image.convert('RGB') im0.save(imgpath, 'JPEG') im0.thumbnail(thub_size) im0.save(imgpath_sm, 'JPEG') create_pic = MEntity.create_entity(signature, path_save, post_data['desc'] if 'desc' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else '1') if self.entity_ajax == False: self.redirect('/entity/{0}_m.jpg'.format(sig_save)) else: if create_pic: output = {'path_save': imgpath} else: output = {'path_save': ''} return json.dump(output, self)
python
{ "resource": "" }
q5044
EntityHandler.add_pdf
train
def add_pdf(self, post_data): ''' Adding the pdf file. ''' img_entity = self.request.files['file'][0] img_desc = post_data['desc'] filename = img_entity["filename"] if filename and allowed_file_pdf(filename): pass else: return False _, hou = os.path.splitext(filename) signature = str(uuid.uuid1()) outfilename = '{0}{1}'.format(signature, hou) outpath = 'static/upload/{0}'.format(signature[:2]) if os.path.exists(outpath): pass else: os.makedirs(outpath) with open(os.path.join(outpath, outfilename), "wb") as fout: fout.write(img_entity["body"]) sig_save = os.path.join(signature[:2], signature) path_save = os.path.join(signature[:2], outfilename) create_pdf = MEntity.create_entity(signature, path_save, img_desc, kind=post_data['kind'] if 'kind' in post_data else '2') if self.entity_ajax == False: self.redirect('/entity/{0}{1}'.format(sig_save, hou.lower())) else: if create_pdf: output = {'path_save': path_save} else: output = {'path_save': ''} return json.dump(output, self)
python
{ "resource": "" }
q5045
EntityHandler.add_url
train
def add_url(self, post_data): ''' Adding the URL as entity. ''' img_desc = post_data['desc'] img_path = post_data['file1'] cur_uid = tools.get_uudd(4) while MEntity.get_by_uid(cur_uid): cur_uid = tools.get_uudd(4) MEntity.create_entity(cur_uid, img_path, img_desc, kind=post_data['kind'] if 'kind' in post_data else '3') kwd = { 'kind': post_data['kind'] if 'kind' in post_data else '3', } self.render('misc/entity/entity_view.html', filename=img_path, cfg=config.CMS_CFG, kwd=kwd, userinfo=self.userinfo)
python
{ "resource": "" }
q5046
UserHandler.p_changepassword
train
def p_changepassword(self): ''' Changing password. ''' post_data = self.get_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_pass(self.userinfo.uid, post_data['user_pass']) output = {'changepass ': usercheck} else: output = {'changepass ': 0} return json.dump(output, self)
python
{ "resource": "" }
q5047
UserHandler.p_changeinfo
train
def p_changeinfo(self): ''' Change Infor via Ajax. ''' post_data, def_dic = self.fetch_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_info(self.userinfo.uid, post_data['user_email'], extinfo=def_dic) output = {'changeinfo ': usercheck} else: output = {'changeinfo ': 0} return json.dump(output, self)
python
{ "resource": "" }
q5048
UserHandler.__check_valid
train
def __check_valid(self, post_data): ''' To check if the user is succesfully created. Return the status code dict. ''' user_create_status = {'success': False, 'code': '00'} if not tools.check_username_valid(post_data['user_name']): user_create_status['code'] = '11' return user_create_status elif not tools.check_email_valid(post_data['user_email']): user_create_status['code'] = '21' return user_create_status elif MUser.get_by_name(post_data['user_name']): user_create_status['code'] = '12' return user_create_status elif MUser.get_by_email(post_data['user_email']): user_create_status['code'] = '22' return user_create_status user_create_status['success'] = True return user_create_status
python
{ "resource": "" }
q5049
UserHandler.p_to_find
train
def p_to_find(self, ): ''' To find, pager. ''' kwd = { 'pager': '', } self.render('user/user_find_list.html', kwd=kwd, view=MUser.get_by_keyword(""), cfg=config.CMS_CFG, userinfo=self.userinfo)
python
{ "resource": "" }
q5050
SysHandler.set_language
train
def set_language(self, language): ''' Set the cookie for locale. ''' if language == 'ZH': self.set_cookie('ulocale', 'zh_CN') self.set_cookie('blocale', 'zh_CN') else: self.set_cookie('ulocale', 'en_US') self.set_cookie('blocale', 'en_US')
python
{ "resource": "" }
q5051
gen_input_add
train
def gen_input_add(sig_dic): ''' Adding for HTML Input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_add_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_add'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
python
{ "resource": "" }
q5052
gen_input_edit
train
def gen_input_edit(sig_dic): ''' Editing for HTML input control. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_edit_download'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) else: html_str = HTML_TPL_DICT['input_edit'].format( sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], sig_dic=sig_dic['dic'][1], sig_type=sig_dic['type'] ) return html_str
python
{ "resource": "" }
q5053
gen_input_view
train
def gen_input_view(sig_dic): ''' Viewing the HTML text. ''' if sig_dic['en'] == 'tag_file_download': html_str = HTML_TPL_DICT['input_view_download'].format( sig_zh=sig_dic['zh'], sig_unit=sig_dic['dic'][1] ) elif sig_dic['en'] in ['tag_access_link', 'tag_dmoz_url', 'tag_online_link', 'tag_event_url', 'tag_expert_home', 'tag_pic_url']: html_str = HTML_TPL_DICT['input_view_link'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) else: html_str = HTML_TPL_DICT['input_view'].format( sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1] ) return html_str
python
{ "resource": "" }
q5054
MPost.__update_rating
train
def __update_rating(uid, rating): ''' Update the rating for post. ''' entry = TabPost.update( rating=rating ).where(TabPost.uid == uid) entry.execute()
python
{ "resource": "" }
q5055
MPost.__update_kind
train
def __update_kind(uid, kind): ''' update the kind of post. ''' entry = TabPost.update( kind=kind, ).where(TabPost.uid == uid) entry.execute() return True
python
{ "resource": "" }
q5056
MPost.update_cnt
train
def update_cnt(uid, post_data): ''' update content. ''' entry = TabPost.update( cnt_html=tools.markdown2html(post_data['cnt_md']), user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), time_update=tools.timestamp() ).where(TabPost.uid == uid) entry.execute()
python
{ "resource": "" }
q5057
MPost.update_order
train
def update_order(uid, order): ''' Update the order of the posts. ''' entry = TabPost.update( order=order ).where(TabPost.uid == uid) entry.execute()
python
{ "resource": "" }
q5058
MPost.update
train
def update(uid, post_data, update_time=False): ''' update the infor. ''' title = post_data['title'].strip() if len(title) < 2: return False cnt_html = tools.markdown2html(post_data['cnt_md']) try: if update_time: entry2 = TabPost.update( date=datetime.now(), time_create=tools.timestamp() ).where(TabPost.uid == uid) entry2.execute() except: pass cur_rec = MPost.get_by_uid(uid) entry = TabPost.update( title=title, user_name=post_data['user_name'], cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), memo=post_data['memo'] if 'memo' in post_data else '', cnt_html=cnt_html, logo=post_data['logo'], order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', kind=post_data['kind'] if 'kind' in post_data else 1, extinfo=post_data['extinfo'] if 'extinfo' in post_data else cur_rec.extinfo, time_update=tools.timestamp(), valid=post_data.get('valid', 1) ).where(TabPost.uid == uid) entry.execute()
python
{ "resource": "" }
q5059
MPost.add_or_update
train
def add_or_update(uid, post_data): ''' Add or update the post. ''' cur_rec = MPost.get_by_uid(uid) if cur_rec: MPost.update(uid, post_data) else: MPost.create_post(uid, post_data)
python
{ "resource": "" }
q5060
MPost.create_post
train
def create_post(post_uid, post_data): ''' create the post. ''' title = post_data['title'].strip() if len(title) < 2: return False cur_rec = MPost.get_by_uid(post_uid) if cur_rec: return False entry = TabPost.create( title=title, date=datetime.now(), cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md'].strip()), cnt_html=tools.markdown2html(post_data['cnt_md']), uid=post_uid, time_create=post_data.get('time_create', tools.timestamp()), time_update=post_data.get('time_update', tools.timestamp()), user_name=post_data['user_name'], view_count=post_data['view_count'] if 'view_count' in post_data else 1, logo=post_data['logo'], memo=post_data['memo'] if 'memo' in post_data else '', order=post_data['order'] if 'order' in post_data else '', keywords=post_data['keywords'] if 'keywords' in post_data else '', extinfo=post_data['extinfo'] if 'extinfo' in post_data else {}, kind=post_data['kind'] if 'kind' in post_data else '1', valid=post_data.get('valid', 1) ) return entry.uid
python
{ "resource": "" }
q5061
MPost.query_cat_random
train
def query_cat_random(catid, **kwargs): ''' Get random lists of certain category. ''' num = kwargs.get('limit', 8) if catid == '': rand_recs = TabPost.select().order_by(peewee.fn.Random()).limit(num) else: rand_recs = TabPost.select().join( TabPost2Tag, on=(TabPost.uid == TabPost2Tag.post_id) ).where( (TabPost.valid == 1) & (TabPost2Tag.tag_id == catid) ).order_by( peewee.fn.Random() ).limit(num) return rand_recs
python
{ "resource": "" }
q5062
MPost.query_random
train
def query_random(**kwargs): ''' Return the random records of centain kind. ''' if 'limit' in kwargs: limit = kwargs['limit'] elif 'num' in kwargs: limit = kwargs['num'] else: limit = 10 kind = kwargs.get('kind', None) if kind: rand_recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( peewee.fn.Random() ).limit(limit) else: rand_recs = TabPost.select().where( TabPost.valid == 1 ).order_by( peewee.fn.Random() ).limit(limit) return rand_recs
python
{ "resource": "" }
q5063
MPost.query_recent
train
def query_recent(num=8, **kwargs): ''' query recent posts. ''' order_by_create = kwargs.get('order_by_create', False) kind = kwargs.get('kind', None) if order_by_create: if kind: recent_recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_create.desc() ).limit(num) else: recent_recs = TabPost.select().where( TabPost.valid == 1 ).order_by( TabPost.time_create.desc() ).limit(num) else: if kind: recent_recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_update.desc() ).limit(num) else: recent_recs = TabPost.select().where( TabPost.valid == 1 ).order_by( TabPost.time_update.desc() ).limit(num) return recent_recs
python
{ "resource": "" }
q5064
MPost.query_all
train
def query_all(**kwargs): ''' query all the posts. ''' kind = kwargs.get('kind', '1') limit = kwargs.get('limit', 10) return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_update.desc() ).limit(limit)
python
{ "resource": "" }
q5065
MPost.query_keywords_empty
train
def query_keywords_empty(kind='1'): ''' Query keywords, empty. ''' return TabPost.select().where((TabPost.kind == kind) & (TabPost.keywords == ''))
python
{ "resource": "" }
q5066
MPost.query_recent_edited
train
def query_recent_edited(timstamp, kind='1'): ''' Query posts recently update. ''' return TabPost.select().where( (TabPost.kind == kind) & (TabPost.time_update > timstamp) ).order_by( TabPost.time_update.desc() )
python
{ "resource": "" }
q5067
MPost.query_dated
train
def query_dated(num=8, kind='1'): ''' Query posts, outdate. ''' return TabPost.select().where( TabPost.kind == kind ).order_by( TabPost.time_update.asc() ).limit(num)
python
{ "resource": "" }
q5068
MPost.query_most_pic
train
def query_most_pic(num, kind='1'): ''' Query most pics. ''' return TabPost.select().where( (TabPost.kind == kind) & (TabPost.logo != "") ).order_by(TabPost.view_count.desc()).limit(num)
python
{ "resource": "" }
q5069
MPost.query_most
train
def query_most(num=8, kind='1'): ''' Query most viewed. ''' return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.view_count.desc() ).limit(num)
python
{ "resource": "" }
q5070
MPost.update_misc
train
def update_misc(uid, **kwargs): ''' update rating, kind, or count ''' if 'rating' in kwargs: MPost.__update_rating(uid, kwargs['rating']) elif 'kind' in kwargs: MPost.__update_kind(uid, kwargs['kind']) elif 'keywords' in kwargs: MPost.__update_keywords(uid, kwargs['keywords']) elif 'count' in kwargs: MPost.__update_view_count(uid)
python
{ "resource": "" }
q5071
MPost.__update_keywords
train
def __update_keywords(uid, inkeywords): ''' Update with keywords. ''' entry = TabPost.update(keywords=inkeywords).where(TabPost.uid == uid) entry.execute()
python
{ "resource": "" }
q5072
MPost.get_next_record
train
def get_next_record(in_uid, kind='1'): ''' Get next record by time_create. ''' current_rec = MPost.get_by_uid(in_uid) recs = TabPost.select().where( (TabPost.kind == kind) & (TabPost.time_create < current_rec.time_create) ).order_by(TabPost.time_create.desc()) if recs.count(): return recs.get() return None
python
{ "resource": "" }
q5073
MPost.get_all
train
def get_all(kind='2'): ''' Get All the records. ''' return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_update.desc() )
python
{ "resource": "" }
q5074
MPost.update_jsonb
train
def update_jsonb(uid, extinfo): ''' Update the json. ''' cur_extinfo = MPost.get_by_uid(uid).extinfo for key in extinfo: cur_extinfo[key] = extinfo[key] entry = TabPost.update( extinfo=cur_extinfo, ).where(TabPost.uid == uid) entry.execute() return uid
python
{ "resource": "" }
q5075
MPost.modify_meta
train
def modify_meta(uid, data_dic, extinfo=None): ''' update meta of the rec. ''' if extinfo is None: extinfo = {} title = data_dic['title'].strip() if len(title) < 2: return False cur_info = MPost.get_by_uid(uid) if cur_info: # ToDo: should not do this. Not for 's' if DB_CFG['kind'] == 's': entry = TabPost.update( title=title, user_name=data_dic['user_name'], keywords='', time_update=tools.timestamp(), date=datetime.now(), cnt_md=data_dic['cnt_md'], memo=data_dic['memo'] if 'memo' in data_dic else '', logo=data_dic['logo'], order=data_dic['order'], cnt_html=tools.markdown2html(data_dic['cnt_md']), valid=data_dic['valid'] ).where(TabPost.uid == uid) entry.execute() else: cur_extinfo = cur_info.extinfo # Update the extinfo, Not replace for key in extinfo: cur_extinfo[key] = extinfo[key] entry = TabPost.update( title=title, user_name=data_dic['user_name'], keywords='', time_update=tools.timestamp(), date=datetime.now(), cnt_md=data_dic['cnt_md'], memo=data_dic['memo'] if 'memo' in data_dic else '', logo=data_dic['logo'], order=data_dic['order'] if 'order' in data_dic else '', cnt_html=tools.markdown2html(data_dic['cnt_md']), extinfo=cur_extinfo, valid=data_dic['valid'] ).where(TabPost.uid == uid) entry.execute() else: return MPost.add_meta(uid, data_dic, extinfo) return uid
python
{ "resource": "" }
q5076
MPost.modify_init
train
def modify_init(uid, data_dic): ''' update when init. ''' postinfo = MPost.get_by_uid(uid) entry = TabPost.update( time_update=tools.timestamp(), date=datetime.now(), kind=data_dic['kind'] if 'kind' in data_dic else postinfo.kind, keywords=data_dic['keywords'] if 'keywords' in data_dic else postinfo.keywords, ).where(TabPost.uid == uid) entry.execute() return uid
python
{ "resource": "" }
q5077
MPost.query_under_condition
train
def query_under_condition(condition, kind='2'): ''' Get All data of certain kind according to the condition ''' if DB_CFG['kind'] == 's': return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) ).order_by( TabPost.time_update.desc() ) return TabPost.select().where( (TabPost.kind == kind) & (TabPost.valid == 1) & TabPost.extinfo.contains(condition) ).order_by(TabPost.time_update.desc())
python
{ "resource": "" }
q5078
MPost.query_list_pager
train
def query_list_pager(con, idx, kind='2'): ''' Get records of certain pager. ''' all_list = MPost.query_under_condition(con, kind=kind) return all_list[(idx - 1) * CMS_CFG['list_num']: idx * CMS_CFG['list_num']]
python
{ "resource": "" }
q5079
UserListHandler.list_app
train
def list_app(self): ''' List the apps. ''' kwd = { 'pager': '', 'title': '' } self.render('user/info_list/list_app.html', kwd=kwd, userinfo=self.userinfo)
python
{ "resource": "" }
q5080
UserListHandler.user_most
train
def user_most(self): ''' User most used. ''' kwd = { 'pager': '', 'title': '', } self.render('user/info_list/user_most.html', kwd=kwd, user_name=self.get_current_user(), userinfo=self.userinfo)
python
{ "resource": "" }
q5081
UserListHandler.user_recent
train
def user_recent(self): ''' User used recently. ''' kwd = { 'pager': '', 'title': '' } self.render('user/info_list/user_recent.html', kwd=kwd, user_name=self.get_current_user(), userinfo=self.userinfo)
python
{ "resource": "" }
q5082
UserListHandler.list_recent
train
def list_recent(self): ''' List the recent. ''' recs = MPost.query_recent(20) kwd = { 'pager': '', 'title': '', } self.render('user/info_list/list.html', kwd=kwd, rand_eqs=MPost.query_random(), recs=recs, userinfo=self.userinfo)
python
{ "resource": "" }
q5083
UserListHandler.find
train
def find(self): ''' find the infors. ''' keyword = self.get_argument('keyword').strip() kwd = { 'pager': '', 'title': 'Searching Result', } self.render('user/info_list/find_list.html', userinfo=self.userinfo, kwd=kwd, recs=MPost.get_by_keyword(keyword))
python
{ "resource": "" }
q5084
RelHandler.add_relation
train
def add_relation(self, url_arr): ''' Add relationship. ''' if MPost.get_by_uid(url_arr[1]): pass else: return False last_post_id = self.get_secure_cookie('last_post_uid') if last_post_id: last_post_id = last_post_id.decode('utf-8') last_app_id = self.get_secure_cookie('use_app_uid') if last_app_id: last_app_id = last_app_id.decode('utf-8') if url_arr[0] == 'info': if last_post_id: MRelation.add_relation(last_post_id, url_arr[1], 2) MRelation.add_relation(url_arr[1], last_post_id, 1) if url_arr[0] == 'post': if last_app_id: MRelation.add_relation(last_app_id, url_arr[1], 2) MRelation.add_relation(url_arr[1], last_app_id, 1)
python
{ "resource": "" }
q5085
ReplyHandler.get_by_id
train
def get_by_id(self, reply_id): ''' Get the reply by id. ''' reply = MReply.get_by_uid(reply_id) logger.info('get_reply: {0}'.format(reply_id)) self.render('misc/reply/show_reply.html', reply=reply, username=reply.user_name, date=reply.date, vote=reply.vote, uid=reply.uid, userinfo=self.userinfo, kwd={})
python
{ "resource": "" }
q5086
ReplyHandler.add
train
def add(self, post_id): ''' Adding reply to a post. ''' post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name post_data['user_id'] = self.userinfo.uid post_data['post_id'] = post_id replyid = MReply.create_reply(post_data) if replyid: out_dic = {'pinglun': post_data['cnt_reply'], 'uid': replyid} logger.info('add reply result dic: {0}'.format(out_dic)) return json.dump(out_dic, self)
python
{ "resource": "" }
q5087
ReplyHandler.delete
train
def delete(self, del_id): ''' Delete the id ''' if MReply2User.delete(del_id): output = {'del_zan': 1} else: output = {'del_zan': 0} return json.dump(output, self)
python
{ "resource": "" }
q5088
WikiHistoryHandler.update
train
def update(self, uid): ''' Update the post via ID. ''' if self.userinfo.role[0] > '0': pass else: return False post_data = self.get_post_data() post_data['user_name'] = self.userinfo.user_name if self.userinfo else '' cur_info = MWiki.get_by_uid(uid) MWikiHist.create_wiki_history(cur_info) MWiki.update_cnt(uid, post_data) if cur_info.kind == '1': self.redirect('/wiki/{0}'.format(cur_info.title)) elif cur_info.kind == '2': self.redirect('/page/{0}.html'.format(cur_info.uid))
python
{ "resource": "" }
q5089
WikiHistoryHandler.to_edit
train
def to_edit(self, postid): ''' Try to edit the Post. ''' if self.userinfo.role[0] > '0': pass else: return False kwd = {} self.render('man_info/wiki_man_edit.html', userinfo=self.userinfo, postinfo=MWiki.get_by_uid(postid), kwd=kwd)
python
{ "resource": "" }
q5090
WikiHistoryHandler.delete
train
def delete(self, uid): ''' Delete the history of certain ID. ''' if self.check_post_role()['DELETE']: pass else: return False histinfo = MWikiHist.get_by_uid(uid) if histinfo: pass else: return False postinfo = MWiki.get_by_uid(histinfo.wiki_id) MWikiHist.delete(uid) self.redirect('/wiki_man/view/{0}'.format(postinfo.uid))
python
{ "resource": "" }
q5091
WikiHistoryHandler.restore
train
def restore(self, hist_uid): ''' Restore by ID ''' if self.check_post_role()['ADMIN']: pass else: return False histinfo = MWikiHist.get_by_uid(hist_uid) if histinfo: pass else: return False postinfo = MWiki.get_by_uid(histinfo.wiki_id) cur_cnt = tornado.escape.xhtml_unescape(postinfo.cnt_md) old_cnt = tornado.escape.xhtml_unescape(histinfo.cnt_md) MWiki.update_cnt( histinfo.wiki_id, {'cnt_md': old_cnt, 'user_name': self.userinfo.user_name} ) MWikiHist.update_cnt( histinfo.uid, {'cnt_md': cur_cnt, 'user_name': postinfo.user_name} ) if postinfo.kind == '1': self.redirect('/wiki/{0}'.format(postinfo.title)) elif postinfo.kind == '2': self.redirect('/page/{0}.html'.format(postinfo.uid))
python
{ "resource": "" }
q5092
MLog.add
train
def add(data_dic): ''' Insert new record. ''' uid = data_dic['uid'] TabLog.create( uid=uid, current_url=data_dic['url'], refer_url=data_dic['refer'], user_id=data_dic['user_id'], time_create=data_dic['timein'], time_out=data_dic['timeOut'], time=data_dic['timeon'] ) return uid
python
{ "resource": "" }
q5093
MCollect.get_by_signature
train
def get_by_signature(user_id, app_id): ''' Get the collection. ''' try: return TabCollect.get( (TabCollect.user_id == user_id) & (TabCollect.post_id == app_id) ) except: return None
python
{ "resource": "" }
q5094
MCollect.count_of_user
train
def count_of_user(user_id): ''' Get the cound of views. ''' return TabCollect.select( TabCollect, TabPost.uid.alias('post_uid'), TabPost.title.alias('post_title'), TabPost.view_count.alias('post_view_count') ).where( TabCollect.user_id == user_id ).join( TabPost, on=(TabCollect.post_id == TabPost.uid) ).count()
python
{ "resource": "" }
q5095
MCollect.add_or_update
train
def add_or_update(user_id, app_id): ''' Add the collection or update. ''' rec = MCollect.get_by_signature(user_id, app_id) if rec: entry = TabCollect.update( timestamp=int(time.time()) ).where(TabCollect.uid == rec.uid) entry.execute() else: TabCollect.create( uid=tools.get_uuid(), user_id=user_id, post_id=app_id, timestamp=int(time.time()), )
python
{ "resource": "" }
q5096
deprecated
train
def deprecated(deprecated_in=None, removed_in=None, current_version=None, details=""): """Decorate a function to signify its deprecation This function wraps a method that will soon be removed and does two things: * The docstring of the method will be modified to include a notice about deprecation, e.g., "Deprecated since 0.9.11. Use foo instead." * Raises a :class:`~deprecation.DeprecatedWarning` via the :mod:`warnings` module, which is a subclass of the built-in :class:`DeprecationWarning`. Note that built-in :class:`DeprecationWarning`\\s are ignored by default, so for users to be informed of said warnings they will need to enable them--see the :mod:`warnings` module documentation for more details. :param deprecated_in: The version at which the decorated method is considered deprecated. This will usually be the next version to be released when the decorator is added. The default is **None**, which effectively means immediate deprecation. If this is not specified, then the `removed_in` and `current_version` arguments are ignored. :param removed_in: The version when the decorated method will be removed. The default is **None**, specifying that the function is not currently planned to be removed. Note: This cannot be set to a value if `deprecated_in=None`. :param current_version: The source of version information for the currently running code. This will usually be a `__version__` attribute on your library. The default is `None`. When `current_version=None` the automation to determine if the wrapped function is actually in a period of deprecation or time for removal does not work, causing a :class:`~deprecation.DeprecatedWarning` to be raised in all cases. :param details: Extra details to be added to the method docstring and warning. For example, the details may point users to a replacement method, such as "Use the foo_bar method instead". By default there are no details. """ # You can't just jump to removal. It's weird, unfair, and also makes # building up the docstring weird. if deprecated_in is None and removed_in is not None: raise TypeError("Cannot set removed_in to a value " "without also setting deprecated_in") # Only warn when it's appropriate. There may be cases when it makes sense # to add this decorator before a formal deprecation period begins. # In CPython, PendingDeprecatedWarning gets used in that period, # so perhaps mimick that at some point. is_deprecated = False is_unsupported = False # StrictVersion won't take a None or a "", so make whatever goes to it # is at least *something*. if current_version: current_version = version.StrictVersion(current_version) if removed_in and current_version >= version.StrictVersion(removed_in): is_unsupported = True elif deprecated_in and current_version >= version.StrictVersion(deprecated_in): is_deprecated = True else: # If we can't actually calculate that we're in a period of # deprecation...well, they used the decorator, so it's deprecated. # This will cover the case of someone just using # @deprecated("1.0") without the other advantages. is_deprecated = True should_warn = any([is_deprecated, is_unsupported]) def _function_wrapper(function): if should_warn: # Everything *should* have a docstring, but just in case... existing_docstring = function.__doc__ or "" # The various parts of this decorator being optional makes for # a number of ways the deprecation notice could go. The following # makes for a nicely constructed sentence with or without any # of the parts. parts = { "deprecated_in": " in %s" % deprecated_in if deprecated_in else "", "removed_in": ", to be removed in %s" % removed_in if removed_in else "", "period": "." if deprecated_in or removed_in or details else "", "details": " %s" % details if details else ""} deprecation_note = ("*Deprecated{deprecated_in}{removed_in}" "{period}{details}*".format(**parts)) function.__doc__ = "\n\n".join([existing_docstring, deprecation_note]) @functools.wraps(function) def _inner(*args, **kwargs): if should_warn: if is_unsupported: cls = UnsupportedWarning else: cls = DeprecatedWarning the_warning = cls(function.__name__, deprecated_in, removed_in, details) warnings.warn(the_warning) return function(*args, **kwargs) return _inner return _function_wrapper
python
{ "resource": "" }
q5097
fail_if_not_removed
train
def fail_if_not_removed(method): """Decorate a test method to track removal of deprecated code This decorator catches :class:`~deprecation.UnsupportedWarning` warnings that occur during testing and causes unittests to fail, making it easier to keep track of when code should be removed. :raises: :class:`AssertionError` if an :class:`~deprecation.UnsupportedWarning` is raised while running the test method. """ def _inner(*args, **kwargs): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") rval = method(*args, **kwargs) for warning in caught_warnings: if warning.category == UnsupportedWarning: raise AssertionError( ("%s uses a function that should be removed: %s" % (method, str(warning.message)))) return rval return _inner
python
{ "resource": "" }
q5098
BaseHandler.get_post_data
train
def get_post_data(self): ''' Get all the arguments from post request. Only get the first argument by default. ''' post_data = {} for key in self.request.arguments: post_data[key] = self.get_arguments(key)[0] return post_data
python
{ "resource": "" }
q5099
BaseHandler.check_post_role
train
def check_post_role(self): ''' check the user role for docs. ''' priv_dic = {'ADD': False, 'EDIT': False, 'DELETE': False, 'ADMIN': False} if self.userinfo: if self.userinfo.role[1] > '0': priv_dic['ADD'] = True if self.userinfo.role[1] >= '1': priv_dic['EDIT'] = True if self.userinfo.role[1] >= '3': priv_dic['DELETE'] = True if self.userinfo.role[1] >= '2': priv_dic['ADMIN'] = True return priv_dic
python
{ "resource": "" }