code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
with lock:
if float_bits == 32:
encode_func[float] = encode_float32
elif float_bits == 64:
encode_func[float] = encode_float64
else:
raise ValueError('Float bits (%d) is not 32 or 64' % float_bits)
r = []
encode_func[type(x)](x, r)
return b''.join(r)
|
def dumps(x, float_bits=DEFAULT_FLOAT_BITS)
|
Dump data structure to str.
Here float_bits is either 32 or 64.
| 2.810918 | 2.730417 | 1.029483 |
chars = list(u"".join(words))
start = True
for i in xrange(len(chars)):
char = chars[i]
if char.isalpha():
if start:
chars[i] = char.upper()
else:
chars[i] = char.lower()
start = False
else:
if i > 2 and chars[i - 1] in ".?!" and char.isspace():
start = True
return u"".join(chars)
|
def join(self, words)
|
Capitalize the first alpha character in the reply and the
first alpha character that follows one of [.?!] and a
space.
| 2.866751 | 2.687528 | 1.066687 |
self._learning = True
self.graph.cursor().execute("PRAGMA journal_mode=memory")
self.graph.drop_reply_indexes()
|
def start_batch_learning(self)
|
Begin a series of batch learn operations. Data will not be
committed to the database until stop_batch_learning is
called. Learn text using the normal learn(text) method.
| 15.37835 | 13.396716 | 1.147919 |
self._learning = False
self.graph.commit()
self.graph.cursor().execute("PRAGMA journal_mode=truncate")
self.graph.ensure_indexes()
|
def stop_batch_learning(self)
|
Finish a series of batch learn operations.
| 9.228198 | 8.397696 | 1.098896 |
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in the modern world.
text = text.decode("utf-8", "ignore")
tokens = self.tokenizer.split(text)
trace("Brain.learn_input_token_count", len(tokens))
self._learn_tokens(tokens)
|
def learn(self, text)
|
Learn a string of text. If the input is not already
Unicode, it will be decoded as utf-8.
| 6.995018 | 6.542152 | 1.069223 |
# prepend self.order Nones
chain = self._end_context + tokens + self._end_context
has_space = False
context = []
for i in xrange(len(chain)):
context.append(chain[i])
if len(context) == self.order:
if chain[i] == self.SPACE_TOKEN_ID:
context.pop()
has_space = True
continue
yield tuple(context), has_space
context.pop(0)
has_space = False
|
def _to_edges(self, tokens)
|
This is an iterator that returns the nodes of our graph:
"This is a test" -> "None This" "This is" "is a" "a test" "test None"
Each is annotated with a boolean that tracks whether whitespace was
found between the two tokens.
| 5.332711 | 5.242954 | 1.01712 |
prev = None
for context in contexts:
if prev is None:
prev = context
continue
yield prev[0], context[1], context[0]
prev = context
|
def _to_graph(self, contexts)
|
This is an iterator that returns each edge of our graph
with its two nodes
| 4.374341 | 3.513209 | 1.245113 |
if type(text) != types.UnicodeType:
# Assume that non-Unicode text is encoded as utf-8, which
# should be somewhat safe in the modern world.
text = text.decode("utf-8", "ignore")
tokens = self.tokenizer.split(text)
input_ids = map(self.graph.get_token_by_text, tokens)
# filter out unknown words and non-words from the potential pivots
pivot_set = self._filter_pivots(input_ids)
# Conflate the known ids with the stems of their words
if self.stemmer is not None:
self._conflate_stems(pivot_set, tokens)
# If we didn't recognize any word tokens in the input, pick
# something random from the database and babble.
if len(pivot_set) == 0:
pivot_set = self._babble()
score_cache = {}
best_score = -1.0
best_reply = None
# Loop for approximately loop_ms milliseconds. This can either
# take more (if the first reply takes a long time to generate)
# or less (if the _generate_replies search ends early) time,
# but it should stay roughly accurate.
start = time.time()
end = start + loop_ms * 0.001
count = 0
all_replies = []
_start = time.time()
for edges, pivot_node in self._generate_replies(pivot_set):
reply = Reply(self.graph, tokens, input_ids, pivot_node, edges)
if max_len and self._too_long(max_len, reply):
continue
key = reply.edge_ids
if key not in score_cache:
with trace_us("Brain.evaluate_reply_us"):
score = self.scorer.score(reply)
score_cache[key] = score
else:
# skip scoring, we've already seen this reply
score = -1
if score > best_score:
best_reply = reply
best_score = score
# dump all replies to the console if debugging is enabled
if log.isEnabledFor(logging.DEBUG):
all_replies.append((score, reply))
count += 1
if time.time() > end:
break
if best_reply is None:
# we couldn't find any pivot words in _babble(), so we're
# working with an essentially empty brain. Use the classic
# MegaHAL reply:
return "I don't know enough to answer you yet!"
_time = time.time() - _start
self.scorer.end(best_reply)
if log.isEnabledFor(logging.DEBUG):
replies = [(score, reply.to_text())
for score, reply in all_replies]
replies.sort()
for score, text in replies:
log.debug("%f %s", score, text)
trace("Brain.reply_input_token_count", len(tokens))
trace("Brain.known_word_token_count", len(pivot_set))
trace("Brain.reply_us", _time)
trace("Brain.reply_count", count, _time)
trace("Brain.best_reply_score", int(best_score * 1000))
trace("Brain.best_reply_length", len(best_reply.edge_ids))
log.debug("made %d replies (%d unique) in %f seconds"
% (count, len(score_cache), _time))
if len(text) > 60:
msg = text[0:60] + "..."
else:
msg = text
log.info("[%s] %d %f", msg, count, best_score)
# look up the words for these tokens
with trace_us("Brain.reply_words_lookup_us"):
text = best_reply.to_text()
return text
|
def reply(self, text, loop_ms=500, max_len=None)
|
Reply to a string of text. If the input is not already
Unicode, it will be decoded as utf-8.
| 4.496746 | 4.467593 | 1.006525 |
log.info("Initializing a cobe brain: %s" % filename)
if tokenizer is None:
tokenizer = "Cobe"
if tokenizer not in ("Cobe", "MegaHAL"):
log.info("Unknown tokenizer: %s. Using CobeTokenizer", tokenizer)
tokenizer = "Cobe"
graph = Graph(sqlite3.connect(filename))
with trace_us("Brain.init_time_us"):
graph.init(order, tokenizer)
|
def init(filename, order=3, tokenizer=None)
|
Initialize a brain. This brain's file must not already exist.
Keyword arguments:
order -- Order of the forward/reverse Markov chains (integer)
tokenizer -- One of Cobe, MegaHAL (default Cobe). See documentation
for cobe.tokenizers for details. (string)
| 8.637465 | 5.735863 | 1.50587 |
'Same arguments as with class instance init.'
chan_map = c.PA_CHANNEL_MAP()
if not channel_list: c.pa.channel_map_init_mono(chan_map)
else:
if not is_str(channel_list):
channel_list = b','.join(map(c.force_bytes, channel_list))
c.pa.channel_map_parse(chan_map, channel_list)
if not isinstance(volume, PulseVolumeInfo):
volume = PulseVolumeInfo(volume, chan_map.channels)
struct = c.PA_EXT_STREAM_RESTORE_INFO(
name=c.force_bytes(name),
mute=int(bool(mute)), device=c.force_bytes(device),
channel_map=chan_map, volume=volume.to_struct() )
return struct
|
def struct_from_value( cls, name, volume,
channel_list=None, mute=False, device=None )
|
Same arguments as with class instance init.
| 4.468398 | 3.82557 | 1.168035 |
'''Connect to pulseaudio server.
"autospawn" option will start new pulse daemon, if necessary.
Specifying "wait" option will make function block until pulseaudio server appears.'''
if self._loop_closed:
raise PulseError('Eventloop object was already'
' destroyed and cannot be reused from this instance.')
if self.connected is not None: self._ctx_init()
flags, self.connected = 0, None
if not autospawn: flags |= c.PA_CONTEXT_NOAUTOSPAWN
if wait: flags |= c.PA_CONTEXT_NOFAIL
try: c.pa.context_connect(self._ctx, self.server, flags, None)
except c.pa.CallError: self.connected = False
while self.connected is None: self._pulse_iterate()
if self.connected is False: raise PulseError('Failed to connect to pulseaudio server')
|
def connect(self, autospawn=False, wait=False)
|
Connect to pulseaudio server.
"autospawn" option will start new pulse daemon, if necessary.
Specifying "wait" option will make function block until pulseaudio server appears.
| 5.730145 | 4.038365 | 1.418927 |
'''timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.'''
with self._pulse_loop() as loop:
ts = c.mono_time()
ts_deadline = timeout and (ts + timeout)
while True:
delay = max(0, int((ts_deadline - ts) * 1000000)) if ts_deadline else -1
c.pa.mainloop_prepare(loop, delay) # usec
c.pa.mainloop_poll(loop)
if self._loop_closed: break # interrupted by close() or such
c.pa.mainloop_dispatch(loop)
if self._loop_stop: break
ts = c.mono_time()
if ts_deadline and ts >= ts_deadline: break
|
def _pulse_poll(self, timeout=None)
|
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
| 5.068789 | 4.049858 | 1.251597 |
'''Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))'''
def _wrapper(self, *args, **kws):
if index_arg:
if 'index' in kws: index = kws.pop('index')
else: index, args = args[0], args[1:]
pulse_args = func(*args, **kws) if func else list()
if not is_list(pulse_args): pulse_args = [pulse_args]
if index_arg: pulse_args = [index] + list(pulse_args)
with self._pulse_op_cb() as cb:
try: pulse_op(self._ctx, *(list(pulse_args) + [cb, None]))
except c.ArgumentError as err: raise TypeError(err.args)
except c.pa.CallError as err: raise PulseOperationInvalid(err.args[-1])
func_args = list(inspect.getargspec(func or (lambda: None)))
func_args[0] = list(func_args[0])
if index_arg: func_args[0] = ['index'] + func_args[0]
_wrapper.__name__ = '...'
_wrapper.__doc__ = 'Signature: func' + inspect.formatargspec(*func_args)
if func.__doc__: _wrapper.__doc__ += '\n\n' + func.__doc__
return _wrapper
|
def _pulse_method_call(pulse_op, func=None, index_arg=True)
|
Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))
| 3.751573 | 2.567587 | 1.461128 |
'''Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_list, etc).
"mode" is PulseUpdateEnum value of
'merge' (default), 'replace' or 'set' (replaces ALL entries!!!).'''
mode = PulseUpdateEnum[mode]._c_val
if is_str(obj_name_or_list):
obj_name_or_list = PulseExtStreamRestoreInfo(obj_name_or_list, **obj_kws)
if isinstance(obj_name_or_list, PulseExtStreamRestoreInfo):
obj_name_or_list = [obj_name_or_list]
# obj_array is an array of structs, laid out contiguously in memory, not pointers
obj_array = (c.PA_EXT_STREAM_RESTORE_INFO * len(obj_name_or_list))()
for n, obj in enumerate(obj_name_or_list):
obj_struct, dst_struct = obj.to_struct(), obj_array[n]
for k,t in obj_struct._fields_: setattr(dst_struct, k, getattr(obj_struct, k))
return mode, obj_array, len(obj_array), int(bool(apply_immediately))
|
def stream_restore_write( obj_name_or_list,
mode='merge', apply_immediately=False, **obj_kws )
|
Update module-stream-restore db entry for specified name.
Can be passed PulseExtStreamRestoreInfo object or list of them as argument,
or name string there and object init keywords (e.g. volume, mute, channel_list, etc).
"mode" is PulseUpdateEnum value of
'merge' (default), 'replace' or 'set' (replaces ALL entries!!!).
| 5.569167 | 2.362282 | 2.357537 |
'''Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these.'''
if is_str(obj_name_or_list, PulseExtStreamRestoreInfo):
obj_name_or_list = [obj_name_or_list]
name_list = list((obj.name if isinstance( obj,
PulseExtStreamRestoreInfo ) else obj) for obj in obj_name_or_list)
name_struct = (c.c_char_p * len(name_list))()
name_struct[:] = list(map(c.force_bytes, name_list))
return [name_struct]
|
def stream_restore_delete(obj_name_or_list)
|
Can be passed string name,
PulseExtStreamRestoreInfo object or a list of any of these.
| 4.95722 | 3.120051 | 1.588827 |
'Set passed sink or source to be used as default one by pulseaudio server.'
assert_pulse_object(obj)
method = {
PulseSinkInfo: self.sink_default_set,
PulseSourceInfo: self.source_default_set }.get(type(obj))
if not method: raise NotImplementedError(type(obj))
method(obj)
|
def default_set(self, obj)
|
Set passed sink or source to be used as default one by pulseaudio server.
| 7.434845 | 3.737092 | 1.989473 |
'''Does not return until PulseLoopStop
gets raised in event callback or timeout passes.
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
raise_on_disconnect causes PulseDisconnected exceptions by default.
Do not run any pulse operations from these callbacks.'''
assert self.event_callback
try: self._pulse_poll(timeout)
except c.pa.CallError: pass # e.g. from mainloop_dispatch() on disconnect
if raise_on_disconnect and not self.connected: raise PulseDisconnected()
|
def event_listen(self, timeout=None, raise_on_disconnect=True)
|
Does not return until PulseLoopStop
gets raised in event callback or timeout passes.
timeout should be in seconds (float),
0 for non-blocking poll and None (default) for no timeout.
raise_on_disconnect causes PulseDisconnected exceptions by default.
Do not run any pulse operations from these callbacks.
| 13.667617 | 3.449852 | 3.961798 |
'''Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something.'''
self._loop_stop = True
c.pa.mainloop_wakeup(self._loop)
|
def event_listen_stop(self)
|
Stop event_listen() loop from e.g. another thread.
Does nothing if libpulse poll is not running yet, so might be racey with
event_listen() - be sure to call it in a loop until event_listen returns or something.
| 18.209717 | 2.932541 | 6.209536 |
'''Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with number of fds that had any new events within timeout.
func_err_handler defaults to traceback.print_exception(),
and will be called on any exceptions from callback (to e.g. log these),
returning poll error code (-1) to libpulse after that.'''
if not func_err_handler: func_err_handler = traceback.print_exception
self._pa_poll_cb = c.PA_POLL_FUNC_T(ft.partial(self._pulse_poll_cb, func, func_err_handler))
c.pa.mainloop_set_poll_func(self._loop, self._pa_poll_cb, None)
|
def set_poll_func(self, func, func_err_handler=None)
|
Can be used to integrate pulse client into existing eventloop.
Function will be passed a list of pollfd structs and timeout value (seconds, float),
which it is responsible to use and modify (set poll flags) accordingly,
returning int value >= 0 with number of fds that had any new events within timeout.
func_err_handler defaults to traceback.print_exception(),
and will be called on any exceptions from callback (to e.g. log these),
returning poll error code (-1) to libpulse after that.
| 9.370031 | 1.955341 | 4.792019 |
'''
Updat the link.
'''
entry = TabLink.update(
name=post_data['name'],
link=post_data['link'],
order=post_data['order'],
logo=post_data['logo'] if 'logo' in post_data else '',
).where(TabLink.uid == uid)
try:
entry.execute()
return True
except:
return False
|
def update(uid, post_data)
|
Updat the link.
| 4.140456 | 3.390038 | 1.22136 |
'''
Add record in link.
'''
if MLink.get_by_uid(id_link):
return False
try:
the_order = int(post_data['order'])
except:
the_order = 999
TabLink.create(name=post_data['name'],
link=post_data['link'],
order=the_order,
logo=post_data['logo'] if 'logo' in post_data else '',
uid=id_link)
return id_link
|
def create_link(id_link, post_data)
|
Add record in link.
| 3.916279 | 3.467592 | 1.129394 |
'''
List recent wiki.
'''
kwd = {
'pager': '',
'title': 'Recent Pages',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_recent(),
format_date=tools.format_date,
kwd=kwd,
userinfo=self.userinfo)
|
def recent(self)
|
List recent wiki.
| 10.006101 | 7.425787 | 1.34748 |
'''
List the wikis of dated.
'''
kwd = {
'pager': '',
'title': '最近文档',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_dated(16),
format_date=tools.format_date,
kwd=kwd,
userinfo=self.userinfo)
|
def refresh(self)
|
List the wikis of dated.
| 12.422719 | 7.459726 | 1.665305 |
'''
To judge if there is a post of the title.
Then, to show, or to add.
'''
postinfo = MWiki.get_by_wiki(title)
if postinfo:
if postinfo.kind == self.kind:
self.view(postinfo)
else:
return False
else:
self.to_add(title)
|
def view_or_add(self, title)
|
To judge if there is a post of the title.
Then, to show, or to add.
| 7.83196 | 3.695213 | 2.119488 |
'''
Update the wiki.
'''
postinfo = MWiki.get_by_uid(uid)
if self.check_post_role()['EDIT'] or postinfo.user_name == self.get_current_user():
pass
else:
return False
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
cnt_old = tornado.escape.xhtml_unescape(postinfo.cnt_md).strip()
cnt_new = post_data['cnt_md'].strip()
if cnt_old == cnt_new:
pass
else:
MWikiHist.create_wiki_history(postinfo)
MWiki.update(uid, post_data)
# cele_gen_whoosh.delay()
tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh)
self.redirect('/wiki/{0}'.format(tornado.escape.url_escape(post_data['title'])))
|
def update(self, uid)
|
Update the wiki.
| 4.101202 | 3.831862 | 1.07029 |
'''
View the wiki.
'''
kwd = {
'pager': '',
'editable': self.editable(),
}
self.render('wiki_page/wiki_view.html',
postinfo=view,
kwd=kwd,
userinfo=self.userinfo)
|
def view(self, view)
|
View the wiki.
| 8.797318 | 6.830267 | 1.28799 |
'''
Add wiki
'''
post_data = self.get_post_data()
if title == '':
pass
else:
post_data['title'] = title
post_data['user_name'] = self.get_current_user()
if MWiki.get_by_wiki(post_data['title']):
pass
else:
MWiki.create_wiki(post_data)
tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh)
# cele_gen_whoosh.delay()
self.redirect('/wiki/{0}'.format(tornado.escape.url_escape(post_data['title'])))
|
def add(self, title='')
|
Add wiki
| 4.35203 | 3.981352 | 1.093104 |
'''
生成分页的导航
'''
pagination_num = int(math.ceil(rec_num * 1.0 / 10))
if pagination_num == 1 or pagination_num == 0:
fenye_str = ''
elif pagination_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''
fenye_str = '<ul class="pagination">'
if fenye_num > 1:
pager_home = '''<li class="{0}" name='fenye' onclick='change(this);'
value='{1}'><a>First Page</a></li>'''.format('', 1)
pager_pre = ''' <li class="{0}" name='fenye' onclick='change(this);'
value='{1}'><a>Previous Page</a></li>'''.format('', fenye_num - 1)
if fenye_num > 5:
cur_num = fenye_num - 4
else:
cur_num = 1
if pagination_num > 10 and cur_num < pagination_num - 10:
show_num = cur_num + 10
else:
show_num = pagination_num + 1
for num in range(cur_num, show_num):
if num == fenye_num:
checkstr = 'active'
else:
checkstr = ''
tmp_str_df = '''<li class="{0}" name='fenye' onclick='change(this);'
value='{1}'><a>{1}</a></li>'''.format(checkstr, num)
pager_mid += tmp_str_df
if fenye_num < pagination_num:
pager_next = '''<li class="{0}" name='fenye' onclick='change(this);'
value='{1}'><a>Next Page</a></li>'''.format('', fenye_num + 1)
pager_last = '''<li class="{0}" name='fenye' onclick='change(this);'
value='{1}'><a>End Page</a></li>'''.format('', pagination_num)
fenye_str += pager_home + pager_pre + pager_mid + pager_next + pager_last
fenye_str += '</ul>'
else:
return ''
return fenye_str
|
def echo_html_fenye_str(rec_num, fenye_num)
|
生成分页的导航
| 2.091093 | 2.040398 | 1.024845 |
'''
Show the HTML
'''
logger.info('info echo html: {0}'.format(url_str))
condition = self.gen_redis_kw()
url_arr = self.parse_url(url_str)
sig = url_arr[0]
num = (len(url_arr) - 2) // 2
catinfo = MCategory.get_by_uid(sig)
if catinfo.pid == '0000':
condition['def_cat_pid'] = sig
else:
condition['def_cat_uid'] = sig
fenye_num = 1
for idx in range(num):
ckey = url_arr[idx * 2 + 2]
tval = url_arr[idx * 2 + 3]
if tval == '0':
continue
if ckey == 'fenye':
# 分页参数。单独处理。
fenye_num = int(tval)
continue
else:
cval = tval
ckey = 'tag_' + ckey
condition[ckey] = cval
if url_arr[1] == 'con':
infos = MPost.query_list_pager(condition, fenye_num, kind=catinfo.kind)
self.echo_html_list_str(sig, infos)
elif url_arr[1] == 'num':
allinfos = MPost.query_under_condition(condition, kind=catinfo.kind)
self.write(
tornado.escape.xhtml_unescape(
echo_html_fenye_str(
allinfos.count(),
fenye_num
)
)
)
|
def echo_html(self, url_str)
|
Show the HTML
| 4.858377 | 4.742795 | 1.02437 |
'''
生成 list 后的 HTML 格式的字符串
'''
zhiding_str = ''
tuiguang_str = ''
imgname = 'fixed/zhanwei.png'
kwd = {
'imgname': imgname,
'zhiding': zhiding_str,
'tuiguang': tuiguang_str,
}
self.render('autogen/infolist/infolist_{0}.html'.format(catid),
userinfo=self.userinfo,
kwd=kwd,
html2text=html2text,
post_infos=infos,
widget_info=kwd)
|
def echo_html_list_str(self, catid, infos)
|
生成 list 后的 HTML 格式的字符串
| 7.62545 | 6.359673 | 1.199032 |
'''
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
'''
logger.info('Infocat input: {0}'.format(catid))
condition = self.gen_redis_kw()
sig = catid
bread_title = ''
bread_crumb_nav_str = '<li>当前位置:<a href="/">信息</a></li>'
_catinfo = MCategory.get_by_uid(catid)
logger.info('Infocat input: {0}'.format(_catinfo))
if _catinfo.pid == '0000':
pcatinfo = _catinfo
catinfo = None
parent_id = catid
parent_catname = MCategory.get_by_uid(parent_id).name
condition['parentid'] = [parent_id]
catname = MCategory.get_by_uid(sig).name
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(sig, catname)
bread_title = '{0}'.format(catname)
else:
catinfo = _catinfo
pcatinfo = MCategory.get_by_uid(_catinfo.pid)
condition['def_cat_uid'] = [sig]
parent_id = _catinfo.uid
parent_catname = MCategory.get_by_uid(parent_id).name
catname = MCategory.get_by_uid(sig).name
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(
parent_id,
parent_catname
)
bread_crumb_nav_str += '<li><a href="/list/{0}">{1}</a></li>'.format(sig, catname)
bread_title += '{0} - '.format(parent_catname)
bread_title += '{0}'.format(catname)
num = MPost.get_num_condition(condition)
kwd = {'catid': catid,
'daohangstr': bread_crumb_nav_str,
'breadtilte': bread_title,
'parentid': parent_id,
'parentlist': MCategory.get_parent_list(),
'condition': condition,
'catname': catname,
'rec_num': num}
# cat_rec = MCategory.get_by_uid(catid)
if self.get_current_user() and self.userinfo:
redis_kw = redisvr.smembers(CMS_CFG['redis_kw'] + self.userinfo.user_name)
else:
redis_kw = []
kw_condition_arr = []
for the_key in redis_kw:
kw_condition_arr.append(the_key.decode('utf-8'))
self.render('autogen/list/list_{0}.html'.format(catid),
userinfo=self.userinfo,
kwd=kwd,
widget_info=kwd,
condition_arr=kw_condition_arr,
cat_enum=MCategory.get_qian2(parent_id[:2]),
pcatinfo=pcatinfo,
catinfo=catinfo)
|
def list(self, catid)
|
页面打开后的渲染方法,不包含 list 的查询结果与分页导航
| 3.667927 | 3.347313 | 1.095783 |
'''
生成 Filter .
'''
if WORK_BOOK:
pass
else:
return False
html_dics = {}
for wk_sheet in WORK_BOOK:
for column in FILTER_COLUMNS:
kkey, kval = __write_filter_dic(wk_sheet, column)
if kkey:
html_dics[kkey] = kval
return html_dics
|
def gen_html_dic()
|
生成 Filter .
| 8.56238 | 6.303007 | 1.358459 |
'''
Return the dictionay of the switcher form XLXS file.
if valud of the column of the row is `1`, it will be added to the array.
'''
if WORK_BOOK:
pass
else:
return False
papa_id = 0
switch_dics = {}
kind_dics = {}
for work_sheet in WORK_BOOK:
kind_sig = str(work_sheet['A1'].value).strip()
# the number of the categories in a website won't greater than 1000.
for row_num in range(3, 1000):
# 父类, column A
a_cell_value = work_sheet['A{0}'.format(row_num)].value
# 子类, column B
b_cell_val = work_sheet['B{0}'.format(row_num)].value
if a_cell_value or b_cell_val:
pass
else:
break
if a_cell_value and a_cell_value != '':
papa_id = a_cell_value.strip()[1:]
u_dic = __get_switch_arr(work_sheet, row_num)
switch_dics['dic_{0}00'.format(papa_id)] = u_dic
kind_dics['kind_{0}00'.format(papa_id)] = kind_sig
if b_cell_val and b_cell_val != '':
sun_id = b_cell_val.strip()[1:]
if len(sun_id) == 4:
app_uid = sun_id
else:
app_uid = '{0}{1}'.format(papa_id, sun_id)
u_dic = __get_switch_arr(work_sheet, row_num)
switch_dics['dic_{0}'.format(app_uid)] = u_dic
kind_dics['kind_{0}'.format(app_uid)] = kind_sig
return (switch_dics, kind_dics)
|
def gen_array_crud()
|
Return the dictionay of the switcher form XLXS file.
if valud of the column of the row is `1`, it will be added to the array.
| 3.828253 | 2.844678 | 1.34576 |
'''
if valud of the column of the row is `1`, it will be added to the array.
'''
u_dic = []
for col_idx in FILTER_COLUMNS:
cell_val = work_sheet['{0}{1}'.format(col_idx, row_num)].value
if cell_val in [1, '1']:
# Appending the slug name of the switcher.
u_dic.append(work_sheet['{0}1'.format(col_idx)].value.strip().split(',')[0])
return u_dic
|
def __get_switch_arr(work_sheet, row_num)
|
if valud of the column of the row is `1`, it will be added to the array.
| 6.734259 | 3.754826 | 1.793494 |
'''
Create the record if new, else update it.
'''
rec = MUsage.query_by_signature(user_id, post_id)
cate_rec = MInfor2Catalog.get_first_category(post_id)
if cate_rec:
cat_id = cate_rec.tag_id
else:
return False
if rec.count() > 0:
logger.info('Usage update: {uid}'.format(uid=post_id))
rec = rec.get()
query = TabUsage.update(kind=kind).where(TabUsage.uid == rec.uid)
query.execute()
MUsage.count_increate(rec.uid, cat_id, rec.count)
else:
logger.info('Usage create: {uid}'.format(uid=post_id))
TabUsage.create(
uid=tools.get_uuid(),
post_id=post_id,
user_id=user_id,
count=1,
tag_id=cat_id,
timestamp=int(time.time()),
kind=kind,
)
|
def add_or_update(user_id, post_id, kind)
|
Create the record if new, else update it.
| 4.003621 | 3.622617 | 1.105174 |
'''
Send email to all user.
'''
for user_rec in MUser.query_all():
email_add = user_rec.user_email
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
email_cfg['content'])
|
def run_send_all(*args)
|
Send email to all user.
| 8.633872 | 7.225855 | 1.194858 |
'''
Send email to who not logged in recently.
'''
for user_rec in MUser.query_nologin():
email_add = user_rec.user_email
print(email_add)
send_mail([email_add],
"{0}|{1}".format(SMTP_CFG['name'], email_cfg['title']),
email_cfg['content'])
MUser.set_sendemail_time(user_rec.uid)
|
def run_send_nologin(*args)
|
Send email to who not logged in recently.
| 7.844623 | 6.095729 | 1.286905 |
'''
Genereting catetory from xlsx file.
'''
if os.path.exists(XLSX_FILE):
pass
else:
return
# 在分类中排序
order_index = 1
all_cate_arr = []
for sheet_ranges in load_workbook(filename=XLSX_FILE):
kind_sig = str(sheet_ranges['A1'].value).strip()
for row_num in range(3, 10000):
# 父类
a_cell_val = sheet_ranges['A{0}'.format(row_num)].value
b_cell_val = sheet_ranges['B{0}'.format(row_num)].value
c_cell_val = sheet_ranges['C{0}'.format(row_num)].value
if a_cell_val or b_cell_val or c_cell_val:
pass
else:
break
if a_cell_val and a_cell_val != '':
cell_arr = a_cell_val.strip()
p_uid = cell_arr[1:] # 所有以 t 开头
t_slug = sheet_ranges['C{0}'.format(row_num)].value.strip()
t_title = sheet_ranges['D{0}'.format(row_num)].value.strip()
u_uid = p_uid + (4 - len(p_uid)) * '0'
pp_uid = '0000'
elif b_cell_val and b_cell_val != '':
cell_arr = b_cell_val
c_iud = cell_arr[1:]
t_slug = sheet_ranges['C{0}'.format(row_num)].value.strip()
t_title = sheet_ranges['D{0}'.format(row_num)].value.strip()
if len(c_iud) == 4:
u_uid = c_iud
else:
u_uid = '{0}{1}'.format(p_uid, c_iud)
pp_uid = p_uid + (4 - len(p_uid)) * '0'
else:
continue
post_data = {
'name': t_title,
'slug': t_slug,
'order': order_index,
'uid': u_uid,
'pid': pp_uid,
'kind': kind_sig,
}
all_cate_arr.append(post_data)
MCategory.add_or_update(u_uid, post_data)
order_index += 1
return all_cate_arr
|
def gen_xlsx_category()
|
Genereting catetory from xlsx file.
| 2.746605 | 2.61568 | 1.050054 |
'''
Genereting catetory from YAML file.
'''
out_dic = yaml.load(open(yaml_file))
for key in out_dic:
if key.endswith('00'):
uid = key[1:]
cur_dic = out_dic[key]
porder = cur_dic['order']
cat_dic = {
'uid': uid,
'slug': cur_dic['slug'],
'name': cur_dic['name'],
'count': 0,
'tmpl': 1,
'pid': '0000',
'order': porder * 100,
'kind': '{0}'.format(sig),
}
MCategory.add_or_update(uid, cat_dic)
else:
sub_arr = out_dic[key]
pid = key[1:3]
for sub_dic in sub_arr:
porder = out_dic['z' + pid + '00']['order']
for key2 in sub_dic:
uid = key2[1:]
cur_dic = sub_dic[key2]
sorder = cur_dic['order']
cat_dic = {
'uid': uid,
'slug': cur_dic['slug'],
'name': cur_dic['name'],
'count': 0,
'tmpl': 1,
'pid': pid + '00',
'order': porder * 100 + sorder,
'kind': '{0}'.format(sig),
}
MCategory.add_or_update(pid + uid, cat_dic)
|
def gen_category(yaml_file, sig)
|
Genereting catetory from YAML file.
| 2.823588 | 2.606113 | 1.083448 |
'''
find YAML.
'''
for wroot, _, wfiles in os.walk('./database/meta'):
for wfile in wfiles:
if wfile.endswith('.yaml'):
gen_category(os.path.join(wroot, wfile), wfile[0])
|
def gen_yaml_category()
|
find YAML.
| 5.897772 | 4.922375 | 1.198156 |
'''
running some migration.
'''
print('Begin migrate ...')
torcms_migrator = migrate.PostgresqlMigrator(config.DB_CON)
memo_field = migrate.TextField(null=False, default='', help_text='Memo', )
try:
migrate.migrate(torcms_migrator.add_column('tabpost', 'memo', memo_field))
except:
pass
desc_field = migrate.CharField(null=False, default='', max_length=255, help_text='')
try:
migrate.migrate(torcms_migrator.add_column('tabentity', 'desc', desc_field))
except:
pass
extinfo_field = BinaryJSONField(null=False, default={}, help_text='Extra data in JSON.')
try:
migrate.migrate(torcms_migrator.add_column('tabmember', 'extinfo', extinfo_field))
except:
pass
par_id_field = migrate.CharField(null=False, default='', max_length=4,
help_text='父类id,对于label,top_id为""')
try:
migrate.migrate(torcms_migrator.add_column('tabpost2tag', 'par_id', par_id_field))
except:
pass
print('Migration finished.')
|
def run_migrate(*args)
|
running some migration.
| 3.855345 | 3.646861 | 1.057168 |
'''
Generate the difference as the table format.
:param rawinfo:
:param newinfo:
:return:
'''
return HtmlDiff.make_table(HtmlDiff(), rawinfo.split('\n'), newinfo.split('\n'),
context=True,
numlines=1)
|
def diff_table(rawinfo, newinfo)
|
Generate the difference as the table format.
:param rawinfo:
:param newinfo:
:return:
| 5.912592 | 4.006292 | 1.475827 |
'''
随机获取给定位数的整数
'''
sel_arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
rarr = random.sample(sel_arr, lenth)
while rarr[0] == '0':
rarr = random.sample(sel_arr, lenth)
return int(''.join(rarr))
|
def get_uudd(lenth)
|
随机获取给定位数的整数
| 3.239917 | 2.261685 | 1.432524 |
'''
Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text.
'''
html = markdown.markdown(
markdown_text,
extensions=[
WikiLinkExtension(base_url='/wiki/', end_url=''),
'markdown.extensions.extra',
'markdown.extensions.toc',
'markdown.extensions.codehilite',
'markdown.extensions.meta'
]
)
han_biaodians = ['。', ',', ';', '、', '!', '?']
for han_biaodian in han_biaodians:
html = html.replace(han_biaodian + '\n', han_biaodian)
return tornado.escape.xhtml_escape(html)
|
def markdown2html(markdown_text)
|
Convert markdown text to HTML. with extensions.
:param markdown_text: The markdown text.
:return: The HTML text.
| 3.122209 | 2.530882 | 1.233644 |
'''
Generate pager of purecss.
'''
if page_num == 1:
return ''
pager_shouye = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}"><< 首页</a></li>'''.format(
'hidden' if current <= 1 else '', cat_slug
)
pager_pre = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}/{2}">< 前页</a>
</li>'''.format('hidden' if current <= 1 else '',
cat_slug,
current - 1)
pager_mid = ''
for ind in range(0, page_num):
tmp_mid = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}/{2}">{2}</a></li>
'''.format('selected' if ind + 1 == current else '',
cat_slug,
ind + 1)
pager_mid += tmp_mid
pager_next = '''<li class="pure-menu-item {0}">
<a class="pure-menu-link" href="{1}/{2}">后页 ></a>
</li> '''.format('hidden' if current >= page_num else '',
cat_slug,
current + 1)
pager_last = '''<li class="pure-menu-item {0}">
<a hclass="pure-menu-link" ref="{1}/{2}">末页
>></a>
</li> '''.format('hidden' if current >= page_num else '',
cat_slug,
page_num)
pager = pager_shouye + pager_pre + pager_mid + pager_next + pager_last
return pager
|
def gen_pager_purecss(cat_slug, page_num, current)
|
Generate pager of purecss.
| 2.003798 | 1.95281 | 1.026111 |
'''
Get the configure value.
'''
cfg_var = dir(cfg)
if 'DB_CFG' in cfg_var:
db_cfg = cfg.DB_CFG
else:
db_cfg = ConfigDefault.DB_CFG
if 'SMTP_CFG' in cfg_var:
smtp_cfg = cfg.SMTP_CFG
else:
smtp_cfg = ConfigDefault.SMTP_CFG
if 'SITE_CFG' in cfg_var:
site_cfg = cfg.SITE_CFG
else:
site_cfg = ConfigDefault.SITE_CFG
if 'ROLE_CFG' in cfg_var:
role_cfg = cfg.ROLE_CFG
else:
role_cfg = ConfigDefault.ROLE_CFG
role_cfg['view'] = role_cfg.get('view', '')
role_cfg['add'] = role_cfg.get('add', '1000')
role_cfg['edit'] = role_cfg.get('edit', '2000')
role_cfg['delete'] = role_cfg.get('delete', '3000')
role_cfg['admin'] = role_cfg.get('admin', '0300')
###################################################################
site_url = site_cfg['site_url'].strip('/')
site_cfg['site_url'] = site_url
infor = site_url.split(':')
if len(infor) == 1:
site_cfg['PORT'] = 8888
else:
site_cfg['PORT'] = infor[-1]
if 'DEBUG' in site_cfg:
pass
else:
site_cfg['DEBUG'] = False
db_con = PostgresqlExtDatabase(
db_cfg['db'],
user=db_cfg.get('user', db_cfg['db']),
password=db_cfg['pass'],
host='127.0.0.1',
port=db_cfg.get('port', '5432'),
autocommit=True,
autorollback=True)
return (db_con, smtp_cfg, site_cfg, role_cfg)
|
def get_cfg()
|
Get the configure value.
| 2.171391 | 2.116767 | 1.025806 |
'''
When access with the slug, It will add the page if there is no record in database.
'''
rec_page = MWiki.get_by_uid(slug)
if rec_page:
if rec_page.kind == self.kind:
self.view(rec_page)
else:
return False
else:
self.to_add(slug)
|
def view_or_add(self, slug)
|
When access with the slug, It will add the page if there is no record in database.
| 7.923716 | 4.152249 | 1.908295 |
'''
To Add page.
'''
kwd = {
'cats': MCategory.query_all(),
'slug': citiao,
'pager': '',
}
self.render('wiki_page/page_add.html',
kwd=kwd,
userinfo=self.userinfo)
|
def to_add(self, citiao)
|
To Add page.
| 10.05754 | 8.183568 | 1.228992 |
'''
Test if the user could edit the page.
'''
page_rec = MWiki.get_by_uid(slug)
if not page_rec:
return False
if self.check_post_role()['EDIT']:
return True
elif page_rec.user_name == self.userinfo.user_name:
return True
else:
return False
|
def __could_edit(self, slug)
|
Test if the user could edit the page.
| 6.063014 | 5.235289 | 1.158105 |
'''
Update the page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
pageinfo = MWiki.get_by_uid(slug)
cnt_old = tornado.escape.xhtml_unescape(pageinfo.cnt_md).strip()
cnt_new = post_data['cnt_md'].strip()
if cnt_old == cnt_new:
pass
else:
MWikiHist.create_wiki_history(MWiki.get_by_uid(slug))
MWiki.update(slug, post_data)
tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh)
self.redirect('/page/{0}'.format(post_data['slug']))
|
def update(self, slug)
|
Update the page.
| 4.279276 | 4.055441 | 1.055194 |
'''
Try to modify the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_edit.html',
postinfo=MWiki.get_by_uid(uid),
kwd=kwd,
cfg=CMS_CFG,
userinfo=self.userinfo)
|
def to_modify(self, uid)
|
Try to modify the page.
| 9.930079 | 7.932567 | 1.251812 |
'''
View the page.
'''
kwd = {
'pager': '',
}
self.render('wiki_page/page_view.html',
postinfo=rec,
kwd=kwd,
author=rec.user_name,
format_date=tools.format_date,
userinfo=self.userinfo,
cfg=CMS_CFG)
|
def view(self, rec)
|
View the page.
| 8.10226 | 7.014067 | 1.155144 |
'''
post count plus one via ajax.
'''
output = {
'status': 1 if MWiki.view_count_plus(slug) else 0,
}
return json.dump(output, self)
|
def ajax_count_plus(self, slug)
|
post count plus one via ajax.
| 11.828489 | 7.735763 | 1.529066 |
'''
View the list of the pages.
'''
kwd = {
'pager': '',
'title': '单页列表',
}
self.render('wiki_page/page_list.html',
kwd=kwd,
view=MWiki.query_recent(),
view_all=MWiki.query_all(),
format_date=tools.format_date,
userinfo=self.userinfo,
cfg=CMS_CFG)
|
def list(self)
|
View the list of the pages.
| 8.363318 | 6.397851 | 1.307207 |
'''
Add new page.
'''
post_data = self.get_post_data()
post_data['user_name'] = self.userinfo.user_name
if MWiki.get_by_uid(slug):
self.set_status(400)
return False
else:
MWiki.create_page(slug, post_data)
tornado.ioloop.IOLoop.instance().add_callback(self.cele_gen_whoosh)
self.redirect('/page/{0}'.format(slug))
|
def add_page(self, slug)
|
Add new page.
| 5.068398 | 4.726242 | 1.072395 |
'''
in infor.
'''
post_data = {}
for key in self.request.arguments:
post_data[key] = self.get_arguments(key)[0]
MLog.add(post_data)
kwargs.pop('uid', None) # delete `uid` if exists in kwargs
self.redirect('/log/')
|
def add(self, **kwargs)
|
in infor.
| 8.123283 | 7.209315 | 1.126776 |
'''
View the list of the Log.
'''
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(MLog.total_number() / CMS_CFG['list_num'])
kwd = {
'pager': '',
'title': '',
'current_page': current_page_number,
}
if self.is_p:
self.render('admin/log_ajax/user_list.html',
kwd=kwd,
user_list=MLog.query_all_user(),
no_user_list=MLog.query_all(current_page_num=current_page_number),
format_date=tools.format_date,
userinfo=self.userinfo)
else:
self.render('misc/log/user_list.html',
kwd=kwd,
user_list=MLog.query_all_user(),
no_user_list=MLog.query_all(current_page_num=current_page_number),
format_date=tools.format_date,
userinfo=self.userinfo)
|
def list(self, cur_p='')
|
View the list of the Log.
| 3.125771 | 2.893759 | 1.080177 |
'''
View the list of the Log.
'''
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(MLog.total_number() / CMS_CFG['list_num'])
kwd = {
'pager': '',
'title': '',
'current_page': current_page_number,
'user_id': userid,
}
if self.is_p:
self.render('admin/log_ajax/user_log_list.html',
kwd=kwd,
infos=MLog.query_pager_by_user(
userid,
current_page_num=current_page_number
),
format_date=tools.format_date,
userinfo=self.userinfo)
else:
self.render('misc/log/user_log_list.html',
kwd=kwd,
infos=MLog.query_pager_by_user(
userid,
current_page_num=current_page_number
),
format_date=tools.format_date,
userinfo=self.userinfo)
|
def user_log_list(self, userid, cur_p='')
|
View the list of the Log.
| 3.003334 | 2.790831 | 1.076144 |
'''
View the list of the Log.
'''
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(MLog.total_number() / CMS_CFG['list_num'])
kwd = {
'pager': '',
'title': '',
'current_page': current_page_number,
}
arr_num = []
postinfo = MLog.query_all_current_url()
for i in postinfo:
postnum = MLog.count_of_current_url(i.current_url)
arr_num.append(postnum)
self.render('misc/log/pageview.html',
kwd=kwd,
infos=MLog.query_all_pageview(current_page_num=current_page_number),
postinfo=postinfo,
arr_num=arr_num,
format_date=tools.format_date,
userinfo=self.userinfo)
|
def pageview(self, cur_p='')
|
View the list of the Log.
| 4.133822 | 3.799031 | 1.088125 |
'''
Delete by uid
'''
del_count = TabPostHist.delete().where(TabPostHist.uid == uid)
try:
del_count.execute()
return False
except:
return True
|
def delete(uid)
|
Delete by uid
| 7.118481 | 6.419911 | 1.108813 |
'''
Update the content by ID.
'''
entry = TabPostHist.update(
user_name=post_data['user_name'],
cnt_md=tornado.escape.xhtml_escape(post_data['cnt_md']),
time_update=tools.timestamp(),
).where(TabPostHist.uid == uid)
entry.execute()
|
def update_cnt(uid, post_data)
|
Update the content by ID.
| 6.610137 | 5.254656 | 1.257958 |
'''
Query history of certian records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(
TabPostHist.time_update.desc()
).limit(limit)
return recs
|
def query_by_postid(postid, limit=5)
|
Query history of certian records.
| 6.807238 | 4.166614 | 1.633758 |
'''
Get the last one of the records.
'''
recs = TabPostHist.select().where(
TabPostHist.post_id == postid
).order_by(TabPostHist.time_update.desc()).limit(limit)
if recs.count():
return recs.get()
return None
|
def get_last(postid, limit=10)
|
Get the last one of the records.
| 4.876302 | 3.812691 | 1.278966 |
'''
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
|
def create_post_history(raw_data)
|
Create the history of certain post.
| 5.183705 | 4.284715 | 1.209813 |
'''
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)
|
def ajax_list_catalog(self, catid)
|
Get posts of certain catid. In Json.
根据分类ID(catid)获取 该分类下 post 的相关信息,返回Json格式
| 11.6307 | 4.273985 | 2.721277 |
'''
Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_sub_cat(pid):
out_arr[catinfo.uid] = catinfo.name
json.dump(out_arr, self)
|
def ajax_subcat_arr(self, pid)
|
Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式
| 13.567393 | 3.598679 | 3.770103 |
'''
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)
|
def ajax_kindcat_arr(self, kind_sig)
|
Get the sub category.
根据kind值(kind_sig)获取相应分类,返回Json格式
| 9.294114 | 4.369769 | 2.126912 |
'''
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])
|
def list_catalog(self, cat_slug, **kwargs)
|
listing the posts via category
根据分类(cat_slug)显示分类列表
| 4.130668 | 3.71139 | 1.112971 |
'''
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
|
def send_mail(to_list, sub, content, cc=None)
|
Sending email via Python.
| 3.47162 | 3.201575 | 1.084348 |
'''
pager for searching results.
'''
pager = ''
if page_num == 1 or page_num == 0:
pager = ''
elif page_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''
pager = '<ul class="pagination">'
if current > 1:
pager_home = '''<li class="{0}" name='fenye' onclick='change(this);'>
<a href="{1}/{2}">首页</a></li>'''.format('', cat_slug, 1)
pager_pre = ''' <li class="{0}" name='fenye' onclick='change(this);'>
<a href="{1}/{2}">上一页</a></li>'''.format('', cat_slug, current - 1)
if current > 5:
cur_num = current - 4
else:
cur_num = 1
if page_num > 10 and cur_num < page_num - 10:
show_num = cur_num + 10
else:
show_num = page_num + 1
for num in range(cur_num, show_num):
if num == current:
checkstr = 'active'
else:
checkstr = ''
tmp_str_df = '''<li class="{0}" name='fenye' onclick='change(this);'>
<a href="{1}/{2}">{2}</a></li>'''.format(checkstr, cat_slug, num)
pager_mid += tmp_str_df
if current < page_num:
pager_next = '''
<li class="{0}" name='fenye' onclick='change(this);'
><a href="{1}/{2}">下一页</a></li>'''.format('', cat_slug, current + 1)
pager_last = '''
<li class="{0}" name='fenye' onclick='change(this);'
><a href="{1}/{2}">末页</a></li>'''.format('', cat_slug, page_num)
pager += pager_home + pager_pre + pager_mid + pager_next + pager_last
pager += '</ul>'
else:
pass
return pager
|
def gen_pager_bootstrap_url(cat_slug, page_num, current)
|
pager for searching results.
| 2.311207 | 2.228062 | 1.037317 |
'''
perform searching.
'''
if p_index == '' or p_index == '-1':
current_page_number = 1
else:
current_page_number = int(p_index)
res_all = self.ysearch.get_all_num(keyword)
results = self.ysearch.search_pager(
keyword,
page_index=current_page_number,
doc_per_page=CMS_CFG['list_num']
)
page_num = int(res_all / CMS_CFG['list_num'])
kwd = {'title': '查找结果',
'pager': '',
'count': res_all,
'keyword': keyword,
'catid': '',
'current_page': current_page_number}
self.render('misc/search/search_list.html',
kwd=kwd,
srecs=results,
pager=gen_pager_bootstrap_url(
'/search/{0}'.format(keyword),
page_num,
current_page_number
),
userinfo=self.userinfo,
cfg=CMS_CFG)
|
def search(self, keyword, p_index='')
|
perform searching.
| 4.486898 | 4.267251 | 1.051473 |
'''
Searching according the kind.
'''
catid = 'sid' + catid
logger.info('-' * 20)
logger.info('search cat')
logger.info('catid: {0}'.format(catid))
logger.info('keyword: {0}'.format(keyword))
# catid = ''
if p_index == '' or p_index == '-1':
current_page_number = 1
else:
current_page_number = int(p_index)
res_all = self.ysearch.get_all_num(keyword, catid=catid)
results = self.ysearch.search_pager(
keyword,
catid=catid,
page_index=current_page_number,
doc_per_page=CMS_CFG['list_num']
)
page_num = int(res_all / CMS_CFG['list_num'])
kwd = {'title': '查找结果',
'pager': '',
'count': res_all,
'current_page': current_page_number,
'catid': catid,
'keyword': keyword}
self.render('misc/search/search_list.html',
kwd=kwd,
srecs=results,
pager=gen_pager_bootstrap_url(
'/search/{0}/{1}'.format(catid, keyword),
page_num,
current_page_number
),
userinfo=self.userinfo,
cfg=CMS_CFG)
|
def search_cat(self, catid, keyword, p_index=1)
|
Searching according the kind.
| 3.990384 | 3.68111 | 1.084017 |
'''
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))
|
def viewinfo(self, postinfo)
|
View the info
| 4.21724 | 3.896605 | 1.082286 |
'''
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))
|
def count_plus(self, uid)
|
Ajax request, that the view count will plus 1.
| 8.564591 | 6.045611 | 1.416663 |
'''
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, )
|
def p_recent(self, kind, cur_p='', with_catalog=True, with_date=True)
|
List posts that recent edited, partially.
| 4.825654 | 4.052967 | 1.190647 |
'''
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)
|
def j_delete(self, *args)
|
Delete the post, but return the JSON.
| 4.757228 | 4.03017 | 1.180404 |
'''
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)
|
def run_init_tables(*args)
|
Run to init tables.
| 3.613254 | 3.295226 | 1.096512 |
'''
List the entities of the user.
'''
# ToDo: 代码与 entity_handler 中 list 方法有重复
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 = MEntity2User.get_all_pager(current_page_num=current_page_number).objects()
self.render('misc/entity/entity_download.html',
imgs=recs,
cfg=config.CMS_CFG,
kwd=kwd,
userinfo=self.userinfo)
|
def all_list(self, cur_p='')
|
List the entities of the user.
| 6.698614 | 5.852057 | 1.14466 |
'''
List the entities of the user.
'''
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 = MEntity2User.get_all_pager_by_username(userid, current_page_num=current_page_number).objects()
self.render('misc/entity/entity_user_download.html',
imgs=recs,
cfg=config.CMS_CFG,
kwd=kwd,
userinfo=self.userinfo)
|
def user_list(self, userid, cur_p='')
|
List the entities of the user.
| 5.28363 | 4.747028 | 1.11304 |
'''
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()
|
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.
| 3.104087 | 2.53345 | 1.225241 |
'''
弹出的二级发布菜单
'''
fatherid = catstr[1:]
self.write(self.format_class2(fatherid))
|
def echo_class2(self, catstr='')
|
弹出的二级发布菜单
| 22.993246 | 8.776815 | 2.619771 |
'''
Publishing from 1st range category.
'''
dbdata = MCategory.get_parent_list(kind=kind_sig)
class1str = ''
for rec in dbdata:
class1str += '''
<a onclick="select_sub_tag('/publish/2{0}');" class="btn btn-primary"
style="display: inline-block;margin:3px;" >
{1}</a>'''.format(rec.uid, rec.name)
kwd = {'class1str': class1str,
'parentid': '0',
'parentlist': MCategory.get_parent_list()}
self.render('misc/publish/publish.html',
userinfo=self.userinfo,
kwd=kwd)
|
def view_class1(self, kind_sig)
|
Publishing from 1st range category.
| 7.42147 | 5.732425 | 1.294647 |
'''
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]))
|
def view_class2(self, fatherid='')
|
Publishing from 2ed range category.
| 9.584446 | 6.882307 | 1.392621 |
'''
Get the Evalution sum.
'''
return TabEvaluation.select().where(
(TabEvaluation.post_id == app_id) & (TabEvaluation.value == value)
).count()
|
def app_evaluation_count(app_id, value=1)
|
Get the Evalution sum.
| 8.701231 | 4.921344 | 1.76806 |
'''
get by user ID, and app ID.
'''
try:
return TabEvaluation.get(
(TabEvaluation.user_id == user_id) & (TabEvaluation.post_id == app_id)
)
except:
return None
|
def get_by_signature(user_id, app_id)
|
get by user ID, and app ID.
| 5.482855 | 4.5132 | 1.214849 |
'''
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,
)
|
def add_or_update(user_id, app_id, value)
|
Editing evaluation.
| 4.83174 | 4.075119 | 1.185668 |
'''
Index funtion.
'''
self.render('ext_excel/index.html',
userinfo=self.userinfo,
cfg=CMS_CFG,
kwd={}, )
|
def index(self)
|
Index funtion.
| 28.115395 | 19.301134 | 1.456671 |
'''
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))
|
def view(self, rec)
|
view the post.
| 4.857634 | 4.2371 | 1.146452 |
'''
plus count via ajax.
'''
output = {'status': 1 if MWiki.view_count_plus(slug) else 0}
return json.dump(output, self)
|
def j_count_plus(self, slug)
|
plus count via ajax.
| 13.815969 | 9.120824 | 1.514772 |
'''
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)
|
def p_list(self, kind, cur_p='', )
|
List the post .
| 5.048178 | 4.390994 | 1.149666 |
'''
Set the time that send E-mail to user.
'''
entry = TabMember.update(
time_email=tools.timestamp(),
).where(TabMember.uid == uid)
entry.execute()
|
def set_sendemail_time(uid)
|
Set the time that send E-mail to user.
| 11.365427 | 7.812165 | 1.454837 |
'''
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
|
def check_user(user_id, u_pass)
|
Checking the password by user's ID.
| 4.150442 | 3.193217 | 1.299768 |
'''
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
|
def check_user_by_name(user_name, u_pass)
|
Checking the password by user's name.
| 3.90567 | 3.104327 | 1.258137 |
'''
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
|
def update_pass(user_id, newpass)
|
Update the password of a user.
| 5.967082 | 5.762827 | 1.035443 |
'''
Query the users who do not login recently (90 days).
and not send email (120 days).
time_model: num * month * hours * minite * second
time_login: 3 * 30 * 24 * 60 * 60
time_email: 4 * 30 * 24 * 60 * 60
'''
time_now = tools.timestamp()
return TabMember.select().where(
((time_now - TabMember.time_login) > 7776000)
& ((time_now - TabMember.time_email) > 10368000)
)
|
def query_nologin()
|
Query the users who do not login recently (90 days).
and not send email (120 days).
time_model: num * month * hours * minite * second
time_login: 3 * 30 * 24 * 60 * 60
time_email: 4 * 30 * 24 * 60 * 60
| 5.31615 | 2.130036 | 2.495803 |
'''
Update the user info by user_id.
21: standsfor invalide E-mail.
91: standsfor unkown reson.
'''
if extinfo is None:
extinfo = {}
out_dic = {'success': False, 'code': '00'}
if not tools.check_email_valid(newemail):
out_dic['code'] = '21'
return out_dic
cur_info = MUser.get_by_uid(user_id)
cur_extinfo = cur_info.extinfo
for key in extinfo:
cur_extinfo[key] = extinfo[key]
try:
entry = TabMember.update(
user_email=newemail,
extinfo=cur_extinfo
).where(
TabMember.uid == user_id
)
entry.execute()
out_dic['success'] = True
except:
out_dic['code'] = '91'
return out_dic
|
def update_info(user_id, newemail, extinfo=None)
|
Update the user info by user_id.
21: standsfor invalide E-mail.
91: standsfor unkown reson.
| 3.806482 | 2.458808 | 1.5481 |
'''
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
|
def update_time_reset_passwd(user_name, the_time)
|
Update the time when user reset passwd.
| 4.218302 | 3.615652 | 1.166678 |
'''
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
|
def update_role(u_name, newprivilege)
|
Update the role of the usr.
| 5.614533 | 4.176754 | 1.344234 |
'''
Update the login time for user.
'''
entry = TabMember.update(
time_login=tools.timestamp()
).where(
TabMember.user_name == u_name
)
entry.execute()
|
def update_time_login(u_name)
|
Update the login time for user.
| 6.529727 | 5.743523 | 1.136885 |
'''
Create the user.
The code used if `False`.
11: standsfor invalid username.
21: standsfor invalide E-mail.
91: standsfor unkown reson.
'''
out_dic = {'success': False, 'code': '00'}
if not tools.check_username_valid(post_data['user_name']):
out_dic['code'] = '11'
return out_dic
if not tools.check_email_valid(post_data['user_email']):
out_dic['code'] = '21'
return out_dic
try:
TabMember.create(uid=tools.get_uuid(),
user_name=post_data['user_name'],
user_pass=tools.md5(post_data['user_pass']),
user_email=post_data['user_email'],
role='1000', # ‘1000' as default role.
time_create=tools.timestamp(),
time_update=tools.timestamp(),
time_reset_passwd=tools.timestamp(),
time_login=tools.timestamp(),
time_email=tools.timestamp())
out_dic['success'] = True
except:
out_dic['code'] = '91'
return out_dic
|
def create_user(post_data)
|
Create the user.
The code used if `False`.
11: standsfor invalid username.
21: standsfor invalide E-mail.
91: standsfor unkown reson.
| 3.55492 | 2.231326 | 1.593187 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.