signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@verify_type(console=WConsoleProto)<EOL><INDENT>def __init__(self, console):<DEDENT>
self.__console = console<EOL>self.__previous_data = '<STR_LIT>'<EOL>self.__cursor_position = <NUM_LIT:0><EOL>if self.width() < <NUM_LIT:2>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if self.height() < <NUM_LIT:2>:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>
Create new console window :param console: console, that this window is linked to
f9905:c2:m0
@abstractmethod<EOL><INDENT>def width(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Get window width. If windows width was changed - window must be refreshed via :meth:`.WConsoleWindowProto.refresh` :return: int
f9905:c2:m1
@abstractmethod<EOL><INDENT>def height(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Get window height. If windows height was changed - window must be refreshed via :meth:`.WConsoleWindowProto.refresh` :return: int
f9905:c2:m2
@abstractmethod<EOL><INDENT>def clear(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Clear window and remove every symbol it has :return: None
f9905:c2:m3
@abstractmethod<EOL><INDENT>@verify_type(line_index=int, line=str)<EOL>@verify_value(line_index=lambda x: x >= <NUM_LIT:0>)<EOL>def write_line(self, line_index, line):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Write string on specified line :param line_index: line index to display :param line: string to display (must fit windows width) :return:
f9905:c2:m4
@abstractmethod<EOL><INDENT>@verify_type(y=int, x=int)<EOL>@verify_value(x=lambda x: x >= <NUM_LIT:0>, y=lambda x: x >= <NUM_LIT:0>)<EOL>def set_cursor(self, y, x):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Set input cursor in window to specified coordinates. 0, 0 - is top left coordinates :param y: vertical coordinates, 0 - top, bottom - positive value :param x: horizontal coordinates, 0 - left, right - positive value :return:
f9905:c2:m5
@verify_type(prompt_show=bool)<EOL><INDENT>def refresh(self, prompt_show=True):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Refresh current window. Clear current window and redraw it with one of drawers :param prompt_show: flag, that specifies, whether to show prompt and current row at the windows end, or not :return: None
f9905:c2:m6
@verify_type(previous_data=bool, prompt=bool, console_row=bool, console_row_to_cursor=bool)<EOL><INDENT>@verify_type(console_row_from_cursor=bool)<EOL>def data(<EOL>self, previous_data=False, prompt=False, console_row=False,<EOL>console_row_to_cursor=False, console_row_from_cursor=False<EOL>):<DEDENT>
result = '<STR_LIT>'<EOL>if previous_data:<EOL><INDENT>result += self.__previous_data<EOL><DEDENT>if prompt or console_row or console_row_to_cursor:<EOL><INDENT>result += self.console().prompt()<EOL><DEDENT>if console_row or (console_row_from_cursor and console_row_to_cursor):<EOL><INDENT>result += self.console().row()<EOL><DEDENT>elif console_row_to_cursor:<EOL><INDENT>result += self.console().row()[:self.cursor()]<EOL><DEDENT>elif console_row_from_cursor:<EOL><INDENT>result += self.console().row()[self.cursor():]<EOL><DEDENT>return result<EOL>
Return output data. Flags specifies what data to append. If no flags was specified nul-length string returned :param previous_data: If True, then previous output appends :param prompt: If True, then console prompt appends. If console_row or console_row_to_cursor is True, \ then this value is omitted :param console_row: If True, then console prompt and current input appends. :param console_row_to_cursor: If True, then console prompt and current input till cursor appends. \ If console_row is True, then this value is omitted :param console_row_from_cursor: If True, then current input from cursor appends. \ If console_row is True, then this value is omitted :return: str
f9905:c2:m7
@verify_type('<STR_LIT>', previous_data=bool, prompt=bool, console_row=bool, console_row_to_cursor=bool)<EOL><INDENT>@verify_type('<STR_LIT>', console_row_from_cursor=bool)<EOL>def list_data(<EOL>self, previous_data=False, prompt=False, console_row=False,<EOL>console_row_to_cursor=False, console_row_from_cursor=False<EOL>):<DEDENT>
return self.split(self.data(<EOL>previous_data, prompt, console_row, console_row_to_cursor, console_row_from_cursor<EOL>))<EOL>
Return list of strings. Where each string is fitted to windows width. Parameters are the same as they are in :meth:`.WConsoleWindow.data` method :return: list of str
f9905:c2:m8
def console(self):
return self.__console<EOL>
Return linked console :return: WConsoleProto
f9905:c2:m9
@verify_type('<STR_LIT>', start_position=int)<EOL><INDENT>@verify_value('<STR_LIT>', start_position=lambda x: x >= <NUM_LIT:0>)<EOL>@verify_type(data=list)<EOL>def write_data(self, data, start_position=<NUM_LIT:0>):<DEDENT>
if len(data) > self.height():<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>for i in range(len(data)):<EOL><INDENT>self.write_line(start_position + i, data[i])<EOL><DEDENT>
Write data from the specified line :param data: string to write, each one on new line :param start_position: starting line :return:
f9905:c2:m10
@verify_type(pos=(None, int))<EOL><INDENT>@verify_value(pos=lambda x: x is None or x >= <NUM_LIT:0>)<EOL>def cursor(self, pos=None):<DEDENT>
if pos is not None:<EOL><INDENT>self.__cursor_position = pos<EOL><DEDENT>return self.__cursor_position<EOL>
Set and/or get relative cursor position. Defines cursor position in current input row. :param pos: if value is not None, then current cursor position is set to this value and the same value \ is returned :return: int
f9905:c2:m11
def commit(self):
self.__previous_data += (self.data(console_row=True) + '<STR_LIT:\n>')<EOL>
Store current input row. Keep current input row as previous output :return: None
f9905:c2:m12
@verify_type(data=str)<EOL><INDENT>def split(self, data):<DEDENT>
line = deepcopy(data)<EOL>line_width = (self.width() - <NUM_LIT:1>)<EOL>lines = []<EOL>while len(line):<EOL><INDENT>new_line = line[:line_width]<EOL>new_line_pos = new_line.find('<STR_LIT:\n>')<EOL>if new_line_pos >= <NUM_LIT:0>:<EOL><INDENT>new_line = line[:new_line_pos]<EOL>line = line[(new_line_pos + <NUM_LIT:1>):]<EOL><DEDENT>else:<EOL><INDENT>line = line[line_width:]<EOL><DEDENT>lines.append(new_line)<EOL><DEDENT>return lines<EOL>
Split data into list of string, each (self.width() - 1) length or less. If nul-length string specified then empty list is returned :param data: data to split :return: list of str
f9905:c2:m13
@verify_type(feedback=str, cr=bool)<EOL><INDENT>def write_feedback(self, feedback, cr=True):<DEDENT>
self.__previous_data += feedback<EOL>if cr is True:<EOL><INDENT>self.__previous_data += '<STR_LIT:\n>'<EOL><DEDENT>
Store feedback. Keep specified feedback as previous output :param feedback: data to store :param cr: whether to write carriage return to the end or not :return: None
f9905:c2:m14
@verify_type(length=int)<EOL><INDENT>@verify_value(length=lambda x: x >= <NUM_LIT:0>)<EOL>def truncate_feedback(self, length):<DEDENT>
self.__previous_data = self.__previous_data[:-length]<EOL>
Remove data from feedback (removes text from previous output) :param length: string length to remove (including required cr-characters) :return: None
f9905:c2:m15
@abstractmethod<EOL><INDENT>@verify_type(window=WConsoleWindowProto, prompt_show=bool)<EOL>def suitable(self, window, prompt_show=True):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Check if this class can display console content :param window: window that should be drawn :param prompt_show: same as 'prompt_show' in :meth:`.WConsoleWindowProto.refresh` method :return: bool (True if this class can draw console content, False - if it can not)
f9905:c3:m0
@abstractmethod<EOL><INDENT>@verify_type(window=WConsoleWindowProto, prompt_show=bool)<EOL>def draw(self, window, prompt_show=True):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Display console content on console window :param window: windows to draw :param prompt_show: same as 'prompt_show' in :meth:`.WConsoleWindowProto.refresh` method :return: None
f9905:c3:m1
@verify_type(console=WConsoleProto, drawers=WConsoleDrawerProto)<EOL><INDENT>def __init__(self, console, *drawers):<DEDENT>
WConsoleWindowProto.__init__(self, console)<EOL>self.__drawers = []<EOL>self.__drawers.extend(drawers)<EOL>
:param drawers: drawers to use
f9905:c4:m0
@verify_type('<STR_LIT>', prompt_show=bool)<EOL><INDENT>def refresh(self, prompt_show=True):<DEDENT>
self.clear()<EOL>for drawer in self.__drawers:<EOL><INDENT>if drawer.suitable(self, prompt_show=prompt_show):<EOL><INDENT>drawer.draw(self, prompt_show=prompt_show)<EOL>return<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>
Refresh current window. Clear current window and redraw it with one of drawers :param prompt_show: flag, that specifies, whether to show prompt and current row at the windows end, or not :return: None
f9905:c4:m1
def start_session(self):
self.window().cursor(<NUM_LIT:0>)<EOL>WConsoleProto.start_session(self)<EOL>
:meth:`.WConsoleProto.start_session` implementation. Sets cursor to 0 position before session :return: None
f9905:c5:m3
def fin_session(self):
self.window().commit()<EOL>WConsoleProto.fin_session(self)<EOL>
:meth:`.WConsoleProto.fin_session` implementation. Commits current input row :return: None
f9905:c5:m4
@verify_type('<STR_LIT>', result=str, cr=bool)<EOL><INDENT>def write(self, result, cr=True):<DEDENT>
self.window().write_feedback(result, cr=cr)<EOL>
Shortcut for self.window().write_feedback(result) call :param result: same as feedback in :meth:`WConsoleWindowProto.write_feedback` :param cr: same as cr in :meth:`WConsoleWindowProto.write_feedback` :return: None
f9905:c5:m5
@verify_type('<STR_LIT>', length=int)<EOL><INDENT>@verify_value('<STR_LIT>', length=lambda x: x >= <NUM_LIT:0>)<EOL>def truncate(self, length):<DEDENT>
self.window().truncate_feedback(length)<EOL>
Shortcut for self.window().truncate_feedback(result) call :param length: same as length in :meth:`WConsoleWindowProto.truncate_feedback` :return: None
f9905:c5:m6
def refresh_window(self):
self.window().refresh(prompt_show=self.prompt_show())<EOL>
Shortcut for self.window().refresh() call :return: None
f9905:c5:m7
def prompt(self):
return '<STR_LIT>'<EOL>
:meth:`.WConsoleProto.prompt` implementation
f9905:c5:m8
@verify_type(blocking=bool, timeout=(int, float, None), raise_exception=bool)<EOL>@verify_value(lock_fn=lambda x: callable(x))<EOL>@verify_value(timeout=lambda x: x is None or x > <NUM_LIT:0>)<EOL>def critical_section_dynamic_lock(lock_fn, blocking=True, timeout=None, raise_exception=True):
if blocking is False or timeout is None:<EOL><INDENT>timeout = -<NUM_LIT:1><EOL><DEDENT>def first_level_decorator(decorated_function):<EOL><INDENT>def second_level_decorator(original_function, *args, **kwargs):<EOL><INDENT>lock = lock_fn(*args, **kwargs)<EOL>if lock.acquire(blocking=blocking, timeout=timeout) is True:<EOL><INDENT>try:<EOL><INDENT>result = original_function(*args, **kwargs)<EOL>return result<EOL><DEDENT>finally:<EOL><INDENT>lock.release()<EOL><DEDENT><DEDENT>elif raise_exception is True:<EOL><INDENT>raise WCriticalSectionError('<STR_LIT>')<EOL><DEDENT><DEDENT>return decorator(second_level_decorator)(decorated_function)<EOL><DEDENT>return first_level_decorator<EOL>
Protect a function with a lock, that was get from the specified function. If a lock can not be acquire, then no function call will be made :param lock_fn: callable that returns a lock, with which a function may be protected :param blocking: whenever to block operations with lock acquiring :param timeout: timeout with which a lock acquiring will be made :param raise_exception: whenever to raise an WCriticalSectionError exception if lock can not be acquired :return: decorator with which a target function may be protected
f9909:m0
@verify_type('<STR_LIT>', blocking=bool, timeout=(int, float, None), raise_exception=bool)<EOL>@verify_value('<STR_LIT>', timeout=lambda x: x is None or x > <NUM_LIT:0>)<EOL>@verify_type(lock=Lock().__class__)<EOL>def critical_section_lock(lock=None, blocking=True, timeout=None, raise_exception=True):
def lock_getter(*args, **kwargs):<EOL><INDENT>return lock<EOL><DEDENT>return critical_section_dynamic_lock(<EOL>lock_fn=lock_getter, blocking=blocking, timeout=timeout, raise_exception=raise_exception<EOL>)<EOL>
An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object instead of a function that returns a lock with which a function protection will be made :param lock: lock with which a function will be protected :param blocking: same as blocking in :func:`.critical_section_dynamic_lock` function :param timeout: same as timeout in :func:`.critical_section_dynamic_lock` function :param raise_exception: same as raise_exception in :func:`.critical_section_dynamic_lock` function :return: decorator with which a target function may be protected
f9909:m1
def __init__(self):
self.__lock = Lock()<EOL>
Create lock and return new object
f9909:c1:m0
def thread_lock(self):
return self.__lock<EOL>
Return lock with which a bounded methods may be protected :return: threading.Lock
f9909:c1:m1
@verify_type('<STR_LIT:strict>', signal_names=str)<EOL><INDENT>def __init__(self, *signal_names):<DEDENT>
WSignalSourceProto.__init__(self)<EOL>self.__signal_names = signal_names<EOL>self.__queues = {x: WMCQueue(callback=self.__watchers_callbacks_exec(x)) for x in signal_names}<EOL>self.__watchers_callbacks = {x: weakref.WeakSet() for x in signal_names}<EOL>self.__direct_callbacks = {x: weakref.WeakSet() for x in signal_names}<EOL>
Create new signal source :param signal_names: names of signals that this object may send :type signal_names: str
f9910:c0:m0
def __watchers_callbacks_exec(self, signal_name):
def callback_fn():<EOL><INDENT>for watcher in self.__watchers_callbacks[signal_name]:<EOL><INDENT>if watcher is not None:<EOL><INDENT>watcher.notify()<EOL><DEDENT><DEDENT><DEDENT>return callback_fn<EOL>
Generate callback for a queue :param signal_name: name of a signal that callback is generated for :type signal_name: str :rtype: callable
f9910:c0:m1
@verify_type('<STR_LIT:strict>', signal_name=str)<EOL><INDENT>def send_signal(self, signal_name, signal_args=None):<DEDENT>
try:<EOL><INDENT>self.__queues[signal_name].push(signal_args)<EOL>for callback in self.__direct_callbacks[signal_name]:<EOL><INDENT>if callback is not None:<EOL><INDENT>callback(self, signal_name, signal_args)<EOL><DEDENT><DEDENT><DEDENT>except KeyError:<EOL><INDENT>raise WUnknownSignalException('<STR_LIT>' % signal_name)<EOL><DEDENT>
:meth:`.WSignalSourceProto.send_signal` implementation
f9910:c0:m2
def signals(self):
return self.__signal_names<EOL>
:meth:`.WSignalSourceProto.signals` implementation
f9910:c0:m3
@verify_type('<STR_LIT:strict>', signal_name=str)<EOL><INDENT>def watch(self, signal_name):<DEDENT>
watcher = WSignalSource.Watcher(<EOL>self.__queues[signal_name], lambda x: self.__watchers_callbacks[signal_name].remove(x)<EOL>)<EOL>self.__watchers_callbacks[signal_name].add(watcher)<EOL>return watcher<EOL>
:meth:`.WSignalSourceProto.watch` implementation :rtype: watcher: WSignalSource.Watcher
f9910:c0:m4
@verify_type('<STR_LIT:strict>', watcher=Watcher)<EOL><INDENT>def remove_watcher(self, watcher):<DEDENT>
watcher.unsubscribe()<EOL>
:meth:`.WSignalSourceProto.remove_watcher` implementation :type watcher: WSignalSource.Watcher
f9910:c0:m5
@verify_type('<STR_LIT:strict>', signal_name=str)<EOL><INDENT>@verify_value('<STR_LIT:strict>', callback=lambda x: callable(x))<EOL>def callback(self, signal_name, callback):<DEDENT>
self.__direct_callbacks[signal_name].add(callback)<EOL>
:meth:`.WSignalSourceProto.callback` implementation
f9910:c0:m6
@verify_type('<STR_LIT:strict>', signal_name=str)<EOL><INDENT>@verify_value('<STR_LIT:strict>', callback=lambda x: callable(x))<EOL>def remove_callback(self, signal_name, callback):<DEDENT>
try:<EOL><INDENT>self.__direct_callbacks[signal_name].remove(callback)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>' % signal_name)<EOL><DEDENT>
:meth:`.WSignalSourceProto.remove_callback` implementation
f9910:c0:m7
def __init__(self):
WSignalProxyProto.__init__(self)<EOL>self.__signal_source = WSignalSource(WSignalProxy.__proxy_signal_name__)<EOL>self.__watcher = self.__signal_source.watch(WSignalProxy.__proxy_signal_name__)<EOL>self.__callback = WSignalProxy.ProxyCallback(self.__signal_source)<EOL>self.__weak_ref_callback = WSignalProxy.ProxyCallback(self.__signal_source, weak_ref=True)<EOL>
Create new proxy object
f9910:c1:m0
@verify_type('<STR_LIT:strict>', signal_source=WSignalSourceProto, signal_names=str, weak_ref=bool)<EOL><INDENT>@verify_value(signal_names=lambda x: len(x) > <NUM_LIT:0>)<EOL>def proxy(self, signal_source, *signal_names, weak_ref=False):<DEDENT>
callback = self.__callback if weak_ref is False else self.__weak_ref_callback<EOL>for signal_name in signal_names:<EOL><INDENT>signal_source.callback(signal_name, callback)<EOL><DEDENT>
:meth:`.WSignalProxyProto.proxy` implementation
f9910:c1:m1
@verify_type('<STR_LIT:strict>', signal_source=WSignalSourceProto, signal_names=str)<EOL><INDENT>def stop_proxying(self, signal_source, *signal_names, weak_ref=False):<DEDENT>
callback = self.__callback if weak_ref is False else self.__weak_ref_callback<EOL>for signal_name in signal_names:<EOL><INDENT>signal_source.remove_callback(signal_name, callback)<EOL><DEDENT>
:meth:`.WSignalProxyProto.stop_proxying` implementation
f9910:c1:m2
def wait(self, timeout=None):
return self.__watcher.wait(timeout=timeout)<EOL>
:meth:`.WSignalProxyProto.wait` implementation
f9910:c1:m3
def has_next(self):
return self.__watcher.has_next()<EOL>
:meth:`.WSignalProxyProto.has_next` implementation
f9910:c1:m4
def next(self):
return self.__watcher.next()<EOL>
:meth:`.WSignalProxyProto.next` implementation
f9910:c1:m5
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', timeout=(int, float, None))<EOL>@verify_value(timeout=lambda x: x is None or x >= <NUM_LIT:0>)<EOL>def wait(self, timeout=None):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return True if there is an unhandled signal. False - otherwise :param timeout: If it is specified it means a period to wait for a new signal. If it is not set then this method will wait "forever" :rtype: bool
f9911:c0:m0
@abstractmethod<EOL><INDENT>def has_next(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Check if there is unhandled signal already :return: True if there is at least one unhandled signal, False - otherwise :rtype: bool
f9911:c0:m1
@abstractmethod<EOL><INDENT>def next(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return next unhandled signal. If there is no unhandled signal then an exception will be raised :rtype: any
f9911:c0:m2
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_name=str)<EOL>def send_signal(self, signal_name, signal_arg=None):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Send a signal from this object :param signal_name: a name of a signal to send :type signal_name: str :param signal_arg: a signal argument that may be send with a signal :type signal_arg: any :rtype: None
f9911:c1:m0
@abstractmethod<EOL><INDENT>def signals(self):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Return names of signals that may be sent :rtype: tuple of str
f9911:c1:m1
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_name=str)<EOL>def watch(self, signal_name):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Create a "watcher" that helps to wait for a new (unhandled) signal :param signal_name: signal to wait :type signal_name: str :rtype: WSignalWatcherProto
f9911:c1:m2
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', watcher=WSignalWatcherProto)<EOL>def remove_watcher(self, watcher):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Unregister the specified watcher and prevent it to be notified when new signal is sent :param watcher: watcher that should be unregistered :type watcher: WSignalWatcherProto :rtype: None
f9911:c1:m3
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_name=str)<EOL>@verify_value('<STR_LIT:strict>', callback=lambda x: callable(x))<EOL>def callback(self, signal_name, callback):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Register a callback that will be executed when new signal is sent :param signal_name: signal that will trigger a callback :type signal_name: str :param callback: callback that must be executed :type callback: WSignalCallbackProto | callable :rtype: None
f9911:c1:m4
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_name=str)<EOL>@verify_value('<STR_LIT:strict>', callback=lambda x: callable(x))<EOL>def remove_callback(self, signal_name, callback):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Unregister the specified callback and prevent it to be executed when new signal is sent :param signal_name: signal that should be avoided :type signal_name: str :param callback: callback that should be unregistered :type callback: WSignalCallbackProto | callable :rtype: None
f9911:c1:m5
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_source=WSignalSourceProto, signal_name=str)<EOL>def __call__(self, signal_source, signal_name, signal_arg=None):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
A callback that will be called when a signal is sent :param signal_source: origin of a signal :type signal_source: WSignalSourceProto :param signal_name: name of a signal that was send :type signal_name: str :param signal_arg: any argument that you want to pass with the specified signal. A specific signal may relay on this argument and may raise an exception if unsupported value is spotted :type signal_arg: any :rtype: None
f9911:c2:m0
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_source=WSignalSourceProto, signal_names=str, weak_ref=bool)<EOL>def proxy(self, signal_source, *signal_names, weak_ref=False):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Start proxying new signals :param signal_source: signal origin to proxy :type signal_source: WSignalSourceProto :param signal_names: names of signals to proxy :type signal_names: str :param weak_ref: whether signal origin will be stored as is or as a weak reference :type weak_ref: bool :rtype: None
f9911:c3:m0
@abstractmethod<EOL><INDENT>@verify_type('<STR_LIT:strict>', signal_source=WSignalSourceProto, signal_names=str, weak_ref=bool)<EOL>def stop_proxying(self, signal_source, *signal_names, weak_ref=False):<DEDENT>
raise NotImplementedError('<STR_LIT>')<EOL>
Stop proxying signals :param signal_source: signal origin to stop proxying :type signal_source: WSignalSourceProto :param signal_names: names of signals that should not be proxied :type signal_names: str :param weak_ref: whether signal origin was requested as weak ref or as a ordinary object :type weak_ref: bool :rtype: None
f9911:c3:m1
@verify_type(cipher=WAES)<EOL><INDENT>def __init__(self, raw, cipher):<DEDENT>
io.BufferedWriter.__init__(self, raw)<EOL>self.__cipher_padding = cipher.mode().padding()<EOL>if self.__cipher_padding is None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>self.__cipher = cipher.cipher()<EOL>self.__cipher_block_size = cipher.mode().key_size()<EOL>self.__buffer = b'<STR_LIT>'<EOL>
Create new encryption writer :param cipher: cipher to use. As written data size may differ - cipher must be constructed with padding object :param raw: target file-like object to write to
f9912:c6:m0
@verify_type(b=(bytes, memoryview))<EOL><INDENT>def write(self, b):<DEDENT>
self.__buffer += bytes(b)<EOL>bytes_written = <NUM_LIT:0><EOL>while len(self.__buffer) >= self.__cipher_block_size:<EOL><INDENT>io.BufferedWriter.write(self, self.__cipher.encrypt_block(self.__buffer[:self.__cipher_block_size]))<EOL>self.__buffer = self.__buffer[self.__cipher_block_size:]<EOL>bytes_written += self.__cipher_block_size<EOL><DEDENT>return len(b)<EOL>
Encrypt and write data :param b: data to encrypt and write :return: None
f9912:c6:m1
def _decode(self, obj, context):
return b'<STR_LIT>'.join(map(int2byte, [c + <NUM_LIT> for c in bytearray(obj)])).decode("<STR_LIT:utf8>")<EOL>
Get the python representation of the obj
f9920:c1:m0
def _encode(self, obj, context):
return [c - <NUM_LIT> for c in bytearray(obj.encode("<STR_LIT:utf8>"))]<EOL>
Get the bytes representation of the obj
f9920:c1:m1
def list_domains(self):
self.connect()<EOL>results = self.server.list_domains(self.session_id)<EOL>return {i['<STR_LIT>']: i['<STR_LIT>'] for i in results}<EOL>
Return all domains. Domain is a key, so group by them
f9924:c0:m5
def list_websites(self):
self.connect()<EOL>results = self.server.list_websites(self.session_id)<EOL>return results<EOL>
Return all websites, name is not a key
f9924:c0:m6
def website_exists(self, website, websites=None):
if websites is None:<EOL><INDENT>websites = self.list_websites()<EOL><DEDENT>if isinstance(website, str):<EOL><INDENT>website = {"<STR_LIT:name>": website}<EOL><DEDENT>ignored_fields = ('<STR_LIT:id>',) <EOL>results = []<EOL>for other in websites:<EOL><INDENT>different = False<EOL>for key in website:<EOL><INDENT>if key in ignored_fields:<EOL><INDENT>continue<EOL><DEDENT>if other.get(key) != website.get(key):<EOL><INDENT>different = True<EOL>break<EOL><DEDENT><DEDENT>if different is False:<EOL><INDENT>results.append(other)<EOL><DEDENT><DEDENT>return results<EOL>
Look for websites matching the one passed
f9924:c0:m14
def is_website_affected(self, website):
if self.domain is None:<EOL><INDENT>return True<EOL><DEDENT>if not self.include_subdomains:<EOL><INDENT>return self.domain in website['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>dotted_domain = "<STR_LIT:.>" + self.domain<EOL>for subdomain in website['<STR_LIT>']:<EOL><INDENT>if subdomain == self.domain or subdomain.endswith(dotted_domain):<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL><DEDENT>
Tell if the website is affected by the domain change
f9925:c0:m1
def get_affected_domains(self):
results = set()<EOL>dotted_domain = ("<STR_LIT:.>" + self.domain) if self.domain else None<EOL>for website in self.websites:<EOL><INDENT>for subdomain in website['<STR_LIT>']:<EOL><INDENT>if self.domain is None or subdomain == self.domain or(self.include_subdomains and subdomain.endswith(dotted_domain)):<EOL><INDENT>results.add(subdomain)<EOL><DEDENT><DEDENT><DEDENT>results = sorted(list(results), key=lambda item: len(item))<EOL>return results<EOL>
Return a list of all affected domain and subdomains
f9925:c0:m2
def website_exists_as_secure(self, website):
if website['<STR_LIT>']:<EOL><INDENT>logger.info("<STR_LIT>" % website['<STR_LIT:name>'])<EOL>return website<EOL><DEDENT>for other in self._websites:<EOL><INDENT>if other['<STR_LIT:id>'] == website['<STR_LIT:id>']:<EOL><INDENT>continue<EOL><DEDENT>if other['<STR_LIT:name>'] == website['<STR_LIT:name>'] and other['<STR_LIT>']:<EOL><INDENT>return other<EOL><DEDENT><DEDENT>return None<EOL>
Return true if the website has an equivalent that is secure we will have 2 websites with the same name, one insecure (that will contain just the redirect and the identity-verification) and one secured
f9925:c0:m5
def secured_apps_copy(self, apps):
return [[app_name, path] for app_name, path in apps if<EOL>app_name not in (self.LETSENCRYPT_VERIFY_APP_NAME,)]<EOL>
Given the http app list of a website, return what should be in the secure version
f9925:c0:m8
def create_le_verification_app(self):
if self.LETSENCRYPT_VERIFY_APP_NAME in self._apps:<EOL><INDENT>logger.debug(<EOL>"<STR_LIT>" % self.LETSENCRYPT_VERIFY_APP_NAME<EOL>)<EOL>verification_app = self._apps[self.LETSENCRYPT_VERIFY_APP_NAME]<EOL><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>")<EOL>verification_app = self.api.create_app(<EOL>self.LETSENCRYPT_VERIFY_APP_NAME,<EOL>'<STR_LIT>',<EOL>)<EOL>self._apps[self.LETSENCRYPT_VERIFY_APP_NAME] = verification_app<EOL><DEDENT>app_root = os.path.join('<STR_LIT>', self.LETSENCRYPT_VERIFY_APP_NAME)<EOL>well_known_folder = os.path.join(app_root, '<STR_LIT>')<EOL>if not is_link(well_known_folder):<EOL><INDENT>logger.info("<STR_LIT>")<EOL>run('<STR_LIT>'.format(**locals()))<EOL><DEDENT>return verification_app<EOL>
Create the let's encrypt app to verify the ownership of the domain
f9925:c0:m11
def website_verificable(self, website):
required_app = [self.LETSENCRYPT_VERIFY_APP_NAME, '<STR_LIT>']<EOL>for app in website['<STR_LIT>']:<EOL><INDENT>if app == required_app:<EOL><INDENT>return True<EOL><DEDENT><DEDENT>return False<EOL>
True if the website is LetsEncrypt verificable: it should have the verification app on the /.well-known path
f9925:c0:m13
def sync_certificates(self, subdomains=None):
result = run("<STR_LIT>", quiet=True)<EOL>logger.info("<STR_LIT>")<EOL>for acme_certificate_description in result.split('<STR_LIT:\n>')[<NUM_LIT:1>:]:<EOL><INDENT>main_domain = acme_certificate_description.split()[<NUM_LIT:0>]<EOL>if subdomains and main_domain not in subdomains:<EOL><INDENT>continue<EOL><DEDENT>if exists(os.path.join("<STR_LIT>", main_domain)):<EOL><INDENT>certificate_cer = self.get_remote_content(<EOL>os.path.join("<STR_LIT>", main_domain, main_domain + "<STR_LIT>")<EOL>)<EOL>certificate_key = self.get_remote_content(<EOL>os.path.join("<STR_LIT>", main_domain, main_domain + "<STR_LIT>")<EOL>)<EOL>certificate_ca = self.get_remote_content(<EOL>os.path.join("<STR_LIT>", main_domain, "<STR_LIT>")<EOL>)<EOL>certificate_name = self.slugify(main_domain)<EOL>certificate = self._certificates.get(certificate_name)<EOL>if (certificate is None<EOL>or certificate['<STR_LIT>'] != certificate_cer<EOL>or certificate['<STR_LIT>'] != certificate_key<EOL>or certificate['<STR_LIT>'] != certificate_ca):<EOL><INDENT>new_certificate = dict(<EOL>name=certificate_name,<EOL>certificate=certificate_cer,<EOL>private_key=certificate_key,<EOL>intermediates=certificate_ca,<EOL>)<EOL>if certificate is None:<EOL><INDENT>logger.info("<STR_LIT>" % main_domain)<EOL>self.api.create_certificate(new_certificate)<EOL><DEDENT>else:<EOL><INDENT>logger.info("<STR_LIT>" % main_domain)<EOL>self.api.update_certificate(new_certificate)<EOL><DEDENT>self._certificates[certificate_name] = new_certificate<EOL><DEDENT><DEDENT><DEDENT>
Check all certificates available in acme in the host and sync them with the webfaction certificates
f9925:c0:m14
@staticmethod<EOL><INDENT>def get_remote_content(filepath):<DEDENT>
with hide('<STR_LIT>'):<EOL><INDENT>temp = BytesIO()<EOL>get(filepath, temp)<EOL>content = temp.getvalue().decode('<STR_LIT:utf-8>')<EOL><DEDENT>return content.strip()<EOL>
A handy wrapper to get a remote file content
f9925:c0:m15
@staticmethod<EOL><INDENT>def slugify(domain):<DEDENT>
return domain.replace("<STR_LIT:.>", "<STR_LIT:_>")<EOL>
Slugify the domain to create a certificate name for Webfaction. Simple for now (should be alphanumerical)
f9925:c0:m16
def get_main_domain(self, website):
subdomains = website['<STR_LIT>']<EOL>main_domains = set()<EOL>for sub in subdomains:<EOL><INDENT>for d in self._domains:<EOL><INDENT>if sub == d or sub.endswith("<STR_LIT:.>" + d):<EOL><INDENT>main_domains.add(d)<EOL><DEDENT><DEDENT><DEDENT>if len(main_domains) > <NUM_LIT:1>:<EOL><INDENT>logger.error(<EOL>"<STR_LIT>" % website['<STR_LIT:name>']<EOL>)<EOL>exit(<NUM_LIT:1>)<EOL><DEDENT>elif not main_domains:<EOL><INDENT>logger.error("<STR_LIT>" % website['<STR_LIT:name>'])<EOL><DEDENT>return list(main_domains)[<NUM_LIT:0>]<EOL>
Given a list of subdomains, return the main domain of them If the subdomain are across multiple domain, then we cannot have a single website it should be splitted
f9925:c0:m18
def main(args=None):
<EOL>parser = get_cli_parser()<EOL>if args is None:<EOL><INDENT>args = sys.argv[<NUM_LIT:1>:]<EOL><DEDENT>args = parser.parse_args(args)<EOL>if args.webfaction_user:<EOL><INDENT>os.environ['<STR_LIT>'] = args.webfaction_user<EOL><DEDENT>if args.webfaction_pass:<EOL><INDENT>os.environ['<STR_LIT>'] = args.webfaction_pass<EOL><DEDENT>if args.webfaction_host:<EOL><INDENT>os.environ['<STR_LIT>'] = args.webfaction_host<EOL><DEDENT>if args.action == "<STR_LIT>":<EOL><INDENT>if args.name == '<STR_LIT>':<EOL><INDENT>if not args.app_name:<EOL><INDENT>print("<STR_LIT>")<EOL>sys.exit(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % args.name)<EOL><DEDENT><DEDENT>elif args.action == "<STR_LIT>":<EOL><INDENT>print("<STR_LIT>" % (args.name or '<STR_LIT:*>'))<EOL>w = WebfactionWebsiteToSsl(force=args.force)<EOL>w.secure(domain=args.name)<EOL><DEDENT>elif args.action == "<STR_LIT>":<EOL><INDENT>domain = args.name<EOL>if not domain:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>" % domain)<EOL><DEDENT>w = WebfactionWebsiteToSsl(force=args.force)<EOL>w.sync_certificates(subdomains=args.name)<EOL><DEDENT>
The main routine.
f9926:m1
@staticmethod<EOL><INDENT>def query_all():<DEDENT>
<EOL>
查询全部记录
f9931:c0:m1
def index(self):
self.render('<STR_LIT>',<EOL>userinfo=self.userinfo,<EOL>cfg=CMS_CFG,<EOL>kwd={}, )<EOL>
Index funtion.
f9932:c0:m2
def update_category(uid, postdata, kwargs):
catid = kwargs['<STR_LIT>'] if ('<STR_LIT>' in kwargs and MCategory.get_by_uid(kwargs['<STR_LIT>'])) else None<EOL>post_data = postdata<EOL>current_infos = MPost2Catalog.query_by_entity_uid(uid, kind='<STR_LIT>').objects()<EOL>new_category_arr = []<EOL>def_cate_arr = ['<STR_LIT>'.format(x) for x in range(<NUM_LIT:10>)]<EOL>def_cate_arr.append('<STR_LIT>')<EOL>cat_dic = {}<EOL>for key in def_cate_arr:<EOL><INDENT>if key not in post_data:<EOL><INDENT>continue<EOL><DEDENT>if post_data[key] == '<STR_LIT>' or post_data[key] == '<STR_LIT:0>':<EOL><INDENT>continue<EOL><DEDENT>if post_data[key] in new_category_arr:<EOL><INDENT>continue<EOL><DEDENT>new_category_arr.append(post_data[key] + '<STR_LIT:U+0020>' * (<NUM_LIT:4> - len(post_data[key])))<EOL>cat_dic[key] = post_data[key] + '<STR_LIT:U+0020>' * (<NUM_LIT:4> - len(post_data[key]))<EOL><DEDENT>if catid:<EOL><INDENT>def_cat_id = catid<EOL><DEDENT>elif new_category_arr:<EOL><INDENT>def_cat_id = new_category_arr[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>def_cat_id = None<EOL><DEDENT>if def_cat_id:<EOL><INDENT>cat_dic['<STR_LIT>'] = def_cat_id<EOL>cat_dic['<STR_LIT>'] = MCategory.get_by_uid(def_cat_id).pid<EOL><DEDENT>print('<STR_LIT:=>' * <NUM_LIT>)<EOL>print(uid)<EOL>print(cat_dic)<EOL>MPost.update_jsonb(uid, cat_dic)<EOL>for index, catid in enumerate(new_category_arr):<EOL><INDENT>MPost2Catalog.add_record(uid, catid, index)<EOL><DEDENT>for cur_info in current_infos:<EOL><INDENT>if cur_info.tag_id not in new_category_arr:<EOL><INDENT>MPost2Catalog.remove_relation(uid, cur_info.tag_id)<EOL><DEDENT><DEDENT>
Update the category of the post.
f9939:m0
def get_meta(catid, sig):
meta_base = '<STR_LIT>'<EOL>if os.path.exists(meta_base):<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>pp_data = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}<EOL>for wroot, wdirs, wfiles in os.walk(meta_base):<EOL><INDENT>for wdir in wdirs:<EOL><INDENT>if wdir.lower().endswith(sig):<EOL><INDENT>ds_base = pathlib.Path(os.path.join(wroot, wdir))<EOL>for uu in ds_base.iterdir():<EOL><INDENT>if uu.name.endswith('<STR_LIT>'):<EOL><INDENT>meta_dic = chuli_meta('<STR_LIT:u>' + sig[<NUM_LIT:2>:], uu)<EOL>pp_data['<STR_LIT:title>'] = meta_dic['<STR_LIT:title>']<EOL>pp_data['<STR_LIT>'] = meta_dic['<STR_LIT>']<EOL>pp_data['<STR_LIT>'] = '<STR_LIT>'<EOL>pp_data['<STR_LIT>'] = catid<EOL>pp_data['<STR_LIT>'] = catid<EOL>pp_data['<STR_LIT>'] = catid[:<NUM_LIT:2>] + '<STR_LIT>'<EOL>pp_data['<STR_LIT>'] = {}<EOL><DEDENT>elif uu.name.startswith('<STR_LIT>'):<EOL><INDENT>pp_data['<STR_LIT>'] = os.path.join(wroot, wdir, uu.name).strip('<STR_LIT:.>')<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return pp_data<EOL>
Get metadata of dataset via ID.
f9942:m1
def Test():
urls = [<EOL>("<STR_LIT>", ListHandler, dict()),<EOL>("<STR_LIT>", MCategory, dict()),<EOL>]<EOL>assert urls<EOL>
Test
f9975:m0
def get_app(self):
self.app = Application(<EOL>handlers=[("<STR_LIT>", UserHandler, dict())],<EOL>**SETTINGS)<EOL>return self.app<EOL>
Test
f9976:c0:m0
def Test():
<EOL>urls = [<EOL>("<STR_LIT>", EvaluationHandler, dict()), ]<EOL>assert urls<EOL>
Test
f9977:m0
def get_app(self):
return APP<EOL>
Test
f9978:c0:m0
def get_app(self):
return APP<EOL>
Test
f9979:c0:m0
def get_app(self):
return APP<EOL>
Test
f9981:c0:m1
def Test():
urls = [<EOL>("<STR_LIT>", LogHandler, dict()),<EOL>("<STR_LIT>", LogPartialHandler, dict()), ]<EOL>assert urls<EOL>
Test
f9986:m0
def get_app(self):
return APP<EOL>
Test
f9991:c0:m0
def Test():
<EOL>urls = [<EOL>("<STR_LIT>", CollectHandler, dict()), ]<EOL>assert urls<EOL>
Test
f9992:m0
def Test():
<EOL>urls = [("<STR_LIT>", AdminHandler, dict()), ]<EOL>assert urls<EOL>
Test
f9993:m0
def get_app(self):
return APP<EOL>
Test
f9995:c0:m0
def Test():
<EOL>urls = [<EOL>("<STR_LIT>", PublishHandler, dict()), ]<EOL>assert urls<EOL>
Test
f10001:m0
def Test():
<EOL>urls = [<EOL>("<STR_LIT>", EntityHandler, dict()), ]<EOL>assert urls<EOL>
Test
f10002:m0
def get_app(self):
return APP<EOL>
Test
f10003:c0:m0
@staticmethod<EOL><INDENT>def delete(uid):<DEDENT>
return MHelper.delete(TabTag, uid)<EOL>
Delete by uid
f10010:c0:m0
@staticmethod<EOL><INDENT>def get_qian2(qian2):<DEDENT>
return TabTag.select().where(<EOL>TabTag.uid.startswith(qian2)<EOL>).order_by(TabTag.order)<EOL>
用于首页。根据前两位,找到所有的大类与小类。 :param qian2: 分类id的前两位 :return: 数组,包含了找到的分类
f10010:c0:m2
@staticmethod<EOL><INDENT>def query_all(kind='<STR_LIT:1>', by_count=False, by_order=True):<DEDENT>
if by_count:<EOL><INDENT>recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.count.desc())<EOL><DEDENT>elif by_order:<EOL><INDENT>recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.order)<EOL><DEDENT>else:<EOL><INDENT>recs = TabTag.select().where(TabTag.kind == kind).order_by(TabTag.uid)<EOL><DEDENT>return recs<EOL>
Qeury all the categories, order by count or defined order.
f10010:c0:m8
@staticmethod<EOL><INDENT>def query_field_count(limit_num, kind='<STR_LIT:1>'):<DEDENT>
return TabTag.select().where(<EOL>TabTag.kind == kind<EOL>).order_by(<EOL>TabTag.count.desc()<EOL>).limit(limit_num)<EOL>
Query the posts count of certain category.
f10010:c0:m9
@staticmethod<EOL><INDENT>def get_by_slug(slug):<DEDENT>
rec = TabTag.select().where(TabTag.slug == slug)<EOL>if rec.count() > <NUM_LIT:0>:<EOL><INDENT>return rec.get()<EOL><DEDENT>return None<EOL>
return the category record .
f10010:c0:m10
@staticmethod<EOL><INDENT>def update_count(cat_id):<DEDENT>
<EOL>entry2 = TabTag.update(<EOL>count=TabPost2Tag.select().where(<EOL>TabPost2Tag.tag_id == cat_id<EOL>).count()<EOL>).where(TabTag.uid == cat_id)<EOL>entry2.execute()<EOL>
Update the count of certain category.
f10010:c0:m11
@staticmethod<EOL><INDENT>def update(uid, post_data):<DEDENT>
raw_rec = TabTag.get(TabTag.uid == uid)<EOL>entry = TabTag.update(<EOL>name=post_data['<STR_LIT:name>'] if '<STR_LIT:name>' in post_data else raw_rec.name,<EOL>slug=post_data['<STR_LIT>'] if '<STR_LIT>' in post_data else raw_rec.slug,<EOL>order=post_data['<STR_LIT>'] if '<STR_LIT>' in post_data else raw_rec.order,<EOL>kind=post_data['<STR_LIT>'] if '<STR_LIT>' in post_data else raw_rec.kind,<EOL>pid=post_data['<STR_LIT>'],<EOL>).where(TabTag.uid == uid)<EOL>entry.execute()<EOL>
Update the category.
f10010:c0:m12
@staticmethod<EOL><INDENT>def add_or_update(uid, post_data):<DEDENT>
catinfo = MCategory.get_by_uid(uid)<EOL>if catinfo:<EOL><INDENT>MCategory.update(uid, post_data)<EOL><DEDENT>else:<EOL><INDENT>TabTag.create(<EOL>uid=uid,<EOL>name=post_data['<STR_LIT:name>'],<EOL>slug=post_data['<STR_LIT>'],<EOL>order=post_data['<STR_LIT>'],<EOL>kind=post_data['<STR_LIT>'] if '<STR_LIT>' in post_data else '<STR_LIT:1>',<EOL>pid=post_data['<STR_LIT>'],<EOL>)<EOL><DEDENT>return uid<EOL>
Add or update the data by the given ID of post.
f10010:c0:m13