repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
quantmind/pulsar | pulsar/utils/pylib/events.py | Event.unbind | def unbind(self, callback):
"""Remove a callback from the list
"""
handlers = self._handlers
if handlers:
filtered_callbacks = [f for f in handlers if f != callback]
removed_count = len(handlers) - len(filtered_callbacks)
if removed_count:
self._handlers = filtered_callbacks
return removed_count
return 0 | python | def unbind(self, callback):
"""Remove a callback from the list
"""
handlers = self._handlers
if handlers:
filtered_callbacks = [f for f in handlers if f != callback]
removed_count = len(handlers) - len(filtered_callbacks)
if removed_count:
self._handlers = filtered_callbacks
return removed_count
return 0 | [
"def",
"unbind",
"(",
"self",
",",
"callback",
")",
":",
"handlers",
"=",
"self",
".",
"_handlers",
"if",
"handlers",
":",
"filtered_callbacks",
"=",
"[",
"f",
"for",
"f",
"in",
"handlers",
"if",
"f",
"!=",
"callback",
"]",
"removed_count",
"=",
"len",
... | Remove a callback from the list | [
"Remove",
"a",
"callback",
"from",
"the",
"list"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L56-L66 | train |
quantmind/pulsar | pulsar/utils/pylib/events.py | Event.fire | def fire(self, exc=None, data=None):
"""Fire the event
:param exc: fire the event with an exception
:param data: fire an event with data
"""
o = self._self
if o is not None:
handlers = self._handlers
if self._onetime:
self._handlers = None
self._self = None
if handlers:
if exc is not None:
for hnd in handlers:
hnd(o, exc=exc)
elif data is not None:
for hnd in handlers:
hnd(o, data=data)
else:
for hnd in handlers:
hnd(o)
if self._waiter:
if exc:
self._waiter.set_exception(exc)
else:
self._waiter.set_result(data if data is not None else o)
self._waiter = None | python | def fire(self, exc=None, data=None):
"""Fire the event
:param exc: fire the event with an exception
:param data: fire an event with data
"""
o = self._self
if o is not None:
handlers = self._handlers
if self._onetime:
self._handlers = None
self._self = None
if handlers:
if exc is not None:
for hnd in handlers:
hnd(o, exc=exc)
elif data is not None:
for hnd in handlers:
hnd(o, data=data)
else:
for hnd in handlers:
hnd(o)
if self._waiter:
if exc:
self._waiter.set_exception(exc)
else:
self._waiter.set_result(data if data is not None else o)
self._waiter = None | [
"def",
"fire",
"(",
"self",
",",
"exc",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"o",
"=",
"self",
".",
"_self",
"if",
"o",
"is",
"not",
"None",
":",
"handlers",
"=",
"self",
".",
"_handlers",
"if",
"self",
".",
"_onetime",
":",
"self",
... | Fire the event
:param exc: fire the event with an exception
:param data: fire an event with data | [
"Fire",
"the",
"event"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L68-L98 | train |
quantmind/pulsar | pulsar/utils/pylib/events.py | EventHandler.fire_event | def fire_event(self, name, exc=None, data=None):
"""Fire event at ``name`` if it is registered
"""
if self._events and name in self._events:
self._events[name].fire(exc=exc, data=data) | python | def fire_event(self, name, exc=None, data=None):
"""Fire event at ``name`` if it is registered
"""
if self._events and name in self._events:
self._events[name].fire(exc=exc, data=data) | [
"def",
"fire_event",
"(",
"self",
",",
"name",
",",
"exc",
"=",
"None",
",",
"data",
"=",
"None",
")",
":",
"if",
"self",
".",
"_events",
"and",
"name",
"in",
"self",
".",
"_events",
":",
"self",
".",
"_events",
"[",
"name",
"]",
".",
"fire",
"("... | Fire event at ``name`` if it is registered | [
"Fire",
"event",
"at",
"name",
"if",
"it",
"is",
"registered"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L141-L145 | train |
quantmind/pulsar | pulsar/utils/pylib/events.py | EventHandler.bind_events | def bind_events(self, events):
'''Register all known events found in ``events`` key-valued parameters.
'''
evs = self._events
if evs and events:
for event in evs.values():
if event.name in events:
event.bind(events[event.name]) | python | def bind_events(self, events):
'''Register all known events found in ``events`` key-valued parameters.
'''
evs = self._events
if evs and events:
for event in evs.values():
if event.name in events:
event.bind(events[event.name]) | [
"def",
"bind_events",
"(",
"self",
",",
"events",
")",
":",
"evs",
"=",
"self",
".",
"_events",
"if",
"evs",
"and",
"events",
":",
"for",
"event",
"in",
"evs",
".",
"values",
"(",
")",
":",
"if",
"event",
".",
"name",
"in",
"events",
":",
"event",
... | Register all known events found in ``events`` key-valued parameters. | [
"Register",
"all",
"known",
"events",
"found",
"in",
"events",
"key",
"-",
"valued",
"parameters",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L147-L154 | train |
quantmind/pulsar | pulsar/utils/autoreload.py | _get_args_for_reloading | def _get_args_for_reloading():
"""Returns the executable. This contains a workaround for windows
if the executable is incorrectly reported to not have the .exe
extension which can cause bugs on reloading.
"""
rv = [sys.executable]
py_script = sys.argv[0]
if os.name == 'nt' and not os.path.exists(py_script) and \
os.path.exists(py_script + '.exe'):
py_script += '.exe'
rv.append(py_script)
rv.extend(sys.argv[1:])
return rv | python | def _get_args_for_reloading():
"""Returns the executable. This contains a workaround for windows
if the executable is incorrectly reported to not have the .exe
extension which can cause bugs on reloading.
"""
rv = [sys.executable]
py_script = sys.argv[0]
if os.name == 'nt' and not os.path.exists(py_script) and \
os.path.exists(py_script + '.exe'):
py_script += '.exe'
rv.append(py_script)
rv.extend(sys.argv[1:])
return rv | [
"def",
"_get_args_for_reloading",
"(",
")",
":",
"rv",
"=",
"[",
"sys",
".",
"executable",
"]",
"py_script",
"=",
"sys",
".",
"argv",
"[",
"0",
"]",
"if",
"os",
".",
"name",
"==",
"'nt'",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"py_scr... | Returns the executable. This contains a workaround for windows
if the executable is incorrectly reported to not have the .exe
extension which can cause bugs on reloading. | [
"Returns",
"the",
"executable",
".",
"This",
"contains",
"a",
"workaround",
"for",
"windows",
"if",
"the",
"executable",
"is",
"incorrectly",
"reported",
"to",
"not",
"have",
"the",
".",
"exe",
"extension",
"which",
"can",
"cause",
"bugs",
"on",
"reloading",
... | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/autoreload.py#L103-L115 | train |
quantmind/pulsar | pulsar/utils/autoreload.py | Reloader.restart_with_reloader | def restart_with_reloader(self):
"""Spawn a new Python interpreter with the same arguments as this one
"""
while True:
LOGGER.info('Restarting with %s reloader' % self.name)
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ[PULSAR_RUN_MAIN] = 'true'
exit_code = subprocess.call(args, env=new_environ, close_fds=False)
if exit_code != EXIT_CODE:
return exit_code | python | def restart_with_reloader(self):
"""Spawn a new Python interpreter with the same arguments as this one
"""
while True:
LOGGER.info('Restarting with %s reloader' % self.name)
args = _get_args_for_reloading()
new_environ = os.environ.copy()
new_environ[PULSAR_RUN_MAIN] = 'true'
exit_code = subprocess.call(args, env=new_environ, close_fds=False)
if exit_code != EXIT_CODE:
return exit_code | [
"def",
"restart_with_reloader",
"(",
"self",
")",
":",
"while",
"True",
":",
"LOGGER",
".",
"info",
"(",
"'Restarting with %s reloader'",
"%",
"self",
".",
"name",
")",
"args",
"=",
"_get_args_for_reloading",
"(",
")",
"new_environ",
"=",
"os",
".",
"environ",... | Spawn a new Python interpreter with the same arguments as this one | [
"Spawn",
"a",
"new",
"Python",
"interpreter",
"with",
"the",
"same",
"arguments",
"as",
"this",
"one"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/autoreload.py#L35-L45 | train |
quantmind/pulsar | pulsar/async/threads.py | Thread.kill | def kill(self, sig):
'''Invoke the stop on the event loop method.'''
if self.is_alive() and self._loop:
self._loop.call_soon_threadsafe(self._loop.stop) | python | def kill(self, sig):
'''Invoke the stop on the event loop method.'''
if self.is_alive() and self._loop:
self._loop.call_soon_threadsafe(self._loop.stop) | [
"def",
"kill",
"(",
"self",
",",
"sig",
")",
":",
"if",
"self",
".",
"is_alive",
"(",
")",
"and",
"self",
".",
"_loop",
":",
"self",
".",
"_loop",
".",
"call_soon_threadsafe",
"(",
"self",
".",
"_loop",
".",
"stop",
")"
] | Invoke the stop on the event loop method. | [
"Invoke",
"the",
"stop",
"on",
"the",
"event",
"loop",
"method",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/threads.py#L12-L15 | train |
quantmind/pulsar | pulsar/apps/http/auth.py | HTTPDigestAuth.encode | def encode(self, method, uri):
'''Called by the client to encode Authentication header.'''
if not self.username or not self.password:
return
o = self.options
qop = o.get('qop')
realm = o.get('realm')
nonce = o.get('nonce')
entdig = None
p_parsed = urlparse(uri)
path = p_parsed.path
if p_parsed.query:
path += '?' + p_parsed.query
ha1 = self.ha1(realm, self.password)
ha2 = self.ha2(qop, method, path)
if qop == 'auth':
if nonce == self.last_nonce:
self.nonce_count += 1
else:
self.nonce_count = 1
ncvalue = '%08x' % self.nonce_count
s = str(self.nonce_count).encode('utf-8')
s += nonce.encode('utf-8')
s += time.ctime().encode('utf-8')
s += os.urandom(8)
cnonce = sha1(s).hexdigest()[:16]
noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, ha2)
respdig = self.KD(ha1, noncebit)
elif qop is None:
respdig = self.KD(ha1, "%s:%s" % (nonce, ha2))
else:
# XXX handle auth-int.
return
base = ('username="%s", realm="%s", nonce="%s", uri="%s", '
'response="%s"' % (self.username, realm, nonce, path, respdig))
opaque = o.get('opaque')
if opaque:
base += ', opaque="%s"' % opaque
if entdig:
base += ', digest="%s"' % entdig
base += ', algorithm="%s"' % self.algorithm
if qop:
base += ', qop=%s, nc=%s, cnonce="%s"' % (qop, ncvalue, cnonce)
return 'Digest %s' % base | python | def encode(self, method, uri):
'''Called by the client to encode Authentication header.'''
if not self.username or not self.password:
return
o = self.options
qop = o.get('qop')
realm = o.get('realm')
nonce = o.get('nonce')
entdig = None
p_parsed = urlparse(uri)
path = p_parsed.path
if p_parsed.query:
path += '?' + p_parsed.query
ha1 = self.ha1(realm, self.password)
ha2 = self.ha2(qop, method, path)
if qop == 'auth':
if nonce == self.last_nonce:
self.nonce_count += 1
else:
self.nonce_count = 1
ncvalue = '%08x' % self.nonce_count
s = str(self.nonce_count).encode('utf-8')
s += nonce.encode('utf-8')
s += time.ctime().encode('utf-8')
s += os.urandom(8)
cnonce = sha1(s).hexdigest()[:16]
noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, ha2)
respdig = self.KD(ha1, noncebit)
elif qop is None:
respdig = self.KD(ha1, "%s:%s" % (nonce, ha2))
else:
# XXX handle auth-int.
return
base = ('username="%s", realm="%s", nonce="%s", uri="%s", '
'response="%s"' % (self.username, realm, nonce, path, respdig))
opaque = o.get('opaque')
if opaque:
base += ', opaque="%s"' % opaque
if entdig:
base += ', digest="%s"' % entdig
base += ', algorithm="%s"' % self.algorithm
if qop:
base += ', qop=%s, nc=%s, cnonce="%s"' % (qop, ncvalue, cnonce)
return 'Digest %s' % base | [
"def",
"encode",
"(",
"self",
",",
"method",
",",
"uri",
")",
":",
"if",
"not",
"self",
".",
"username",
"or",
"not",
"self",
".",
"password",
":",
"return",
"o",
"=",
"self",
".",
"options",
"qop",
"=",
"o",
".",
"get",
"(",
"'qop'",
")",
"realm... | Called by the client to encode Authentication header. | [
"Called",
"by",
"the",
"client",
"to",
"encode",
"Authentication",
"header",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/auth.py#L78-L121 | train |
quantmind/pulsar | pulsar/apps/wsgi/utils.py | handle_wsgi_error | def handle_wsgi_error(environ, exc):
'''The default error handler while serving a WSGI request.
:param environ: The WSGI environment.
:param exc: the exception
:return: a :class:`.WsgiResponse`
'''
if isinstance(exc, tuple):
exc_info = exc
exc = exc[1]
else:
exc_info = True
request = wsgi_request(environ)
request.cache.handle_wsgi_error = True
old_response = request.cache.pop('response', None)
response = request.response
if old_response:
response.content_type = old_response.content_type
logger = request.logger
#
if isinstance(exc, HTTPError):
response.status_code = exc.code or 500
else:
response.status_code = getattr(exc, 'status', 500)
response.headers.update(getattr(exc, 'headers', None) or ())
status = response.status_code
if status >= 500:
logger.critical('%s - @ %s.\n%s', exc, request.first_line,
dump_environ(environ), exc_info=exc_info)
else:
log_wsgi_info(logger.warning, environ, response.status, exc)
if has_empty_content(status, request.method) or status in REDIRECT_CODES:
response.content_type = None
response.content = None
else:
request.cache.pop('html_document', None)
renderer = environ.get('error.handler') or render_error
try:
content = renderer(request, exc)
except Exception:
logger.critical('Error while rendering error', exc_info=True)
response.content_type = 'text/plain'
content = 'Critical server error'
if content is not response:
response.content = content
return response | python | def handle_wsgi_error(environ, exc):
'''The default error handler while serving a WSGI request.
:param environ: The WSGI environment.
:param exc: the exception
:return: a :class:`.WsgiResponse`
'''
if isinstance(exc, tuple):
exc_info = exc
exc = exc[1]
else:
exc_info = True
request = wsgi_request(environ)
request.cache.handle_wsgi_error = True
old_response = request.cache.pop('response', None)
response = request.response
if old_response:
response.content_type = old_response.content_type
logger = request.logger
#
if isinstance(exc, HTTPError):
response.status_code = exc.code or 500
else:
response.status_code = getattr(exc, 'status', 500)
response.headers.update(getattr(exc, 'headers', None) or ())
status = response.status_code
if status >= 500:
logger.critical('%s - @ %s.\n%s', exc, request.first_line,
dump_environ(environ), exc_info=exc_info)
else:
log_wsgi_info(logger.warning, environ, response.status, exc)
if has_empty_content(status, request.method) or status in REDIRECT_CODES:
response.content_type = None
response.content = None
else:
request.cache.pop('html_document', None)
renderer = environ.get('error.handler') or render_error
try:
content = renderer(request, exc)
except Exception:
logger.critical('Error while rendering error', exc_info=True)
response.content_type = 'text/plain'
content = 'Critical server error'
if content is not response:
response.content = content
return response | [
"def",
"handle_wsgi_error",
"(",
"environ",
",",
"exc",
")",
":",
"if",
"isinstance",
"(",
"exc",
",",
"tuple",
")",
":",
"exc_info",
"=",
"exc",
"exc",
"=",
"exc",
"[",
"1",
"]",
"else",
":",
"exc_info",
"=",
"True",
"request",
"=",
"wsgi_request",
... | The default error handler while serving a WSGI request.
:param environ: The WSGI environment.
:param exc: the exception
:return: a :class:`.WsgiResponse` | [
"The",
"default",
"error",
"handler",
"while",
"serving",
"a",
"WSGI",
"request",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L155-L200 | train |
quantmind/pulsar | pulsar/apps/wsgi/utils.py | render_error | def render_error(request, exc):
'''Default renderer for errors.'''
cfg = request.get('pulsar.cfg')
debug = cfg.debug if cfg else False
response = request.response
if not response.content_type:
content_type = request.get('default.content_type')
response.content_type = request.content_types.best_match(
as_tuple(content_type or DEFAULT_RESPONSE_CONTENT_TYPES)
)
content_type = None
if response.content_type:
content_type = response.content_type.split(';')[0]
is_html = content_type == 'text/html'
if debug:
msg = render_error_debug(request, exc, is_html)
else:
msg = escape(error_messages.get(response.status_code) or exc)
if is_html:
msg = textwrap.dedent("""
<h1>{0[reason]}</h1>
{0[msg]}
<h3>{0[version]}</h3>
""").format({"reason": response.status, "msg": msg,
"version": request.environ['SERVER_SOFTWARE']})
#
if content_type == 'text/html':
doc = HtmlDocument(title=response.status)
doc.head.embedded_css.append(error_css)
doc.body.append(Html('div', msg, cn='pulsar-error'))
return doc.to_bytes(request)
elif content_type in JSON_CONTENT_TYPES:
return json.dumps({'status': response.status_code,
'message': msg})
else:
return '\n'.join(msg) if isinstance(msg, (list, tuple)) else msg | python | def render_error(request, exc):
'''Default renderer for errors.'''
cfg = request.get('pulsar.cfg')
debug = cfg.debug if cfg else False
response = request.response
if not response.content_type:
content_type = request.get('default.content_type')
response.content_type = request.content_types.best_match(
as_tuple(content_type or DEFAULT_RESPONSE_CONTENT_TYPES)
)
content_type = None
if response.content_type:
content_type = response.content_type.split(';')[0]
is_html = content_type == 'text/html'
if debug:
msg = render_error_debug(request, exc, is_html)
else:
msg = escape(error_messages.get(response.status_code) or exc)
if is_html:
msg = textwrap.dedent("""
<h1>{0[reason]}</h1>
{0[msg]}
<h3>{0[version]}</h3>
""").format({"reason": response.status, "msg": msg,
"version": request.environ['SERVER_SOFTWARE']})
#
if content_type == 'text/html':
doc = HtmlDocument(title=response.status)
doc.head.embedded_css.append(error_css)
doc.body.append(Html('div', msg, cn='pulsar-error'))
return doc.to_bytes(request)
elif content_type in JSON_CONTENT_TYPES:
return json.dumps({'status': response.status_code,
'message': msg})
else:
return '\n'.join(msg) if isinstance(msg, (list, tuple)) else msg | [
"def",
"render_error",
"(",
"request",
",",
"exc",
")",
":",
"cfg",
"=",
"request",
".",
"get",
"(",
"'pulsar.cfg'",
")",
"debug",
"=",
"cfg",
".",
"debug",
"if",
"cfg",
"else",
"False",
"response",
"=",
"request",
".",
"response",
"if",
"not",
"respon... | Default renderer for errors. | [
"Default",
"renderer",
"for",
"errors",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L203-L239 | train |
quantmind/pulsar | pulsar/apps/wsgi/utils.py | render_error_debug | def render_error_debug(request, exception, is_html):
'''Render the ``exception`` traceback
'''
error = Html('div', cn='well well-lg') if is_html else []
for trace in format_traceback(exception):
counter = 0
for line in trace.split('\n'):
if line.startswith(' '):
counter += 1
line = line[2:]
if line:
if is_html:
line = Html('p', escape(line), cn='text-danger')
if counter:
line.css({'margin-left': '%spx' % (20*counter)})
error.append(line)
if is_html:
error = Html('div', Html('h1', request.response.status), error)
return error | python | def render_error_debug(request, exception, is_html):
'''Render the ``exception`` traceback
'''
error = Html('div', cn='well well-lg') if is_html else []
for trace in format_traceback(exception):
counter = 0
for line in trace.split('\n'):
if line.startswith(' '):
counter += 1
line = line[2:]
if line:
if is_html:
line = Html('p', escape(line), cn='text-danger')
if counter:
line.css({'margin-left': '%spx' % (20*counter)})
error.append(line)
if is_html:
error = Html('div', Html('h1', request.response.status), error)
return error | [
"def",
"render_error_debug",
"(",
"request",
",",
"exception",
",",
"is_html",
")",
":",
"error",
"=",
"Html",
"(",
"'div'",
",",
"cn",
"=",
"'well well-lg'",
")",
"if",
"is_html",
"else",
"[",
"]",
"for",
"trace",
"in",
"format_traceback",
"(",
"exception... | Render the ``exception`` traceback | [
"Render",
"the",
"exception",
"traceback"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L242-L260 | train |
quantmind/pulsar | pulsar/async/monitor.py | arbiter | def arbiter(**params):
'''Obtain the ``arbiter``.
It returns the arbiter instance only if we are on the arbiter
context domain, otherwise it returns nothing.
'''
arbiter = get_actor()
if arbiter is None:
# Create the arbiter
return set_actor(_spawn_actor('arbiter', None, **params))
elif arbiter.is_arbiter():
return arbiter | python | def arbiter(**params):
'''Obtain the ``arbiter``.
It returns the arbiter instance only if we are on the arbiter
context domain, otherwise it returns nothing.
'''
arbiter = get_actor()
if arbiter is None:
# Create the arbiter
return set_actor(_spawn_actor('arbiter', None, **params))
elif arbiter.is_arbiter():
return arbiter | [
"def",
"arbiter",
"(",
"**",
"params",
")",
":",
"arbiter",
"=",
"get_actor",
"(",
")",
"if",
"arbiter",
"is",
"None",
":",
"return",
"set_actor",
"(",
"_spawn_actor",
"(",
"'arbiter'",
",",
"None",
",",
"**",
"params",
")",
")",
"elif",
"arbiter",
"."... | Obtain the ``arbiter``.
It returns the arbiter instance only if we are on the arbiter
context domain, otherwise it returns nothing. | [
"Obtain",
"the",
"arbiter",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L24-L35 | train |
quantmind/pulsar | pulsar/async/monitor.py | MonitorMixin.manage_actor | def manage_actor(self, monitor, actor, stop=False):
'''If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is not.
'''
if not monitor.is_running():
stop = True
if not actor.is_alive():
if not actor.should_be_alive() and not stop:
return 1
actor.join()
self._remove_monitored_actor(monitor, actor)
return 0
timeout = None
started_stopping = bool(actor.stopping_start)
# if started_stopping is True, set stop to True
stop = stop or started_stopping
if not stop and actor.notified:
gap = time() - actor.notified
stop = timeout = gap > actor.cfg.timeout
if stop: # we are stopping the actor
dt = actor.should_terminate()
if not actor.mailbox or dt:
if not actor.mailbox:
monitor.logger.warning('kill %s - no mailbox.', actor)
else:
monitor.logger.warning('kill %s - could not stop '
'after %.2f seconds.', actor, dt)
actor.kill()
self._remove_monitored_actor(monitor, actor)
return 0
elif not started_stopping:
if timeout:
monitor.logger.warning('Stopping %s. Timeout %.2f',
actor, timeout)
else:
monitor.logger.info('Stopping %s.', actor)
actor.stop()
return 1 | python | def manage_actor(self, monitor, actor, stop=False):
'''If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is not.
'''
if not monitor.is_running():
stop = True
if not actor.is_alive():
if not actor.should_be_alive() and not stop:
return 1
actor.join()
self._remove_monitored_actor(monitor, actor)
return 0
timeout = None
started_stopping = bool(actor.stopping_start)
# if started_stopping is True, set stop to True
stop = stop or started_stopping
if not stop and actor.notified:
gap = time() - actor.notified
stop = timeout = gap > actor.cfg.timeout
if stop: # we are stopping the actor
dt = actor.should_terminate()
if not actor.mailbox or dt:
if not actor.mailbox:
monitor.logger.warning('kill %s - no mailbox.', actor)
else:
monitor.logger.warning('kill %s - could not stop '
'after %.2f seconds.', actor, dt)
actor.kill()
self._remove_monitored_actor(monitor, actor)
return 0
elif not started_stopping:
if timeout:
monitor.logger.warning('Stopping %s. Timeout %.2f',
actor, timeout)
else:
monitor.logger.info('Stopping %s.', actor)
actor.stop()
return 1 | [
"def",
"manage_actor",
"(",
"self",
",",
"monitor",
",",
"actor",
",",
"stop",
"=",
"False",
")",
":",
"if",
"not",
"monitor",
".",
"is_running",
"(",
")",
":",
"stop",
"=",
"True",
"if",
"not",
"actor",
".",
"is_alive",
"(",
")",
":",
"if",
"not",... | If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is not. | [
"If",
"an",
"actor",
"failed",
"to",
"notify",
"itself",
"to",
"the",
"arbiter",
"for",
"more",
"than",
"the",
"timeout",
"stop",
"the",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L102-L143 | train |
quantmind/pulsar | pulsar/async/monitor.py | MonitorMixin.spawn_actors | def spawn_actors(self, monitor):
'''Spawn new actors if needed.
'''
to_spawn = monitor.cfg.workers - len(self.managed_actors)
if monitor.cfg.workers and to_spawn > 0:
for _ in range(to_spawn):
monitor.spawn() | python | def spawn_actors(self, monitor):
'''Spawn new actors if needed.
'''
to_spawn = monitor.cfg.workers - len(self.managed_actors)
if monitor.cfg.workers and to_spawn > 0:
for _ in range(to_spawn):
monitor.spawn() | [
"def",
"spawn_actors",
"(",
"self",
",",
"monitor",
")",
":",
"to_spawn",
"=",
"monitor",
".",
"cfg",
".",
"workers",
"-",
"len",
"(",
"self",
".",
"managed_actors",
")",
"if",
"monitor",
".",
"cfg",
".",
"workers",
"and",
"to_spawn",
">",
"0",
":",
... | Spawn new actors if needed. | [
"Spawn",
"new",
"actors",
"if",
"needed",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L145-L151 | train |
quantmind/pulsar | pulsar/async/monitor.py | MonitorMixin.stop_actors | def stop_actors(self, monitor):
"""Maintain the number of workers by spawning or killing as required
"""
if monitor.cfg.workers:
num_to_kill = len(self.managed_actors) - monitor.cfg.workers
for i in range(num_to_kill, 0, -1):
w, kage = 0, sys.maxsize
for worker in self.managed_actors.values():
age = worker.impl.age
if age < kage:
w, kage = worker, age
self.manage_actor(monitor, w, True) | python | def stop_actors(self, monitor):
"""Maintain the number of workers by spawning or killing as required
"""
if monitor.cfg.workers:
num_to_kill = len(self.managed_actors) - monitor.cfg.workers
for i in range(num_to_kill, 0, -1):
w, kage = 0, sys.maxsize
for worker in self.managed_actors.values():
age = worker.impl.age
if age < kage:
w, kage = worker, age
self.manage_actor(monitor, w, True) | [
"def",
"stop_actors",
"(",
"self",
",",
"monitor",
")",
":",
"if",
"monitor",
".",
"cfg",
".",
"workers",
":",
"num_to_kill",
"=",
"len",
"(",
"self",
".",
"managed_actors",
")",
"-",
"monitor",
".",
"cfg",
".",
"workers",
"for",
"i",
"in",
"range",
... | Maintain the number of workers by spawning or killing as required | [
"Maintain",
"the",
"number",
"of",
"workers",
"by",
"spawning",
"or",
"killing",
"as",
"required"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L153-L164 | train |
quantmind/pulsar | pulsar/async/monitor.py | ArbiterMixin.add_monitor | def add_monitor(self, actor, monitor_name, **params):
'''Add a new ``monitor``.
:param monitor_class: a :class:`.Monitor` class.
:param monitor_name: a unique name for the monitor.
:param kwargs: dictionary of key-valued parameters for the monitor.
:return: the :class:`.Monitor` added.
'''
if monitor_name in self.registered:
raise KeyError('Monitor "%s" already available' % monitor_name)
params.update(actor.actorparams())
params['name'] = monitor_name
params['kind'] = 'monitor'
return actor.spawn(**params) | python | def add_monitor(self, actor, monitor_name, **params):
'''Add a new ``monitor``.
:param monitor_class: a :class:`.Monitor` class.
:param monitor_name: a unique name for the monitor.
:param kwargs: dictionary of key-valued parameters for the monitor.
:return: the :class:`.Monitor` added.
'''
if monitor_name in self.registered:
raise KeyError('Monitor "%s" already available' % monitor_name)
params.update(actor.actorparams())
params['name'] = monitor_name
params['kind'] = 'monitor'
return actor.spawn(**params) | [
"def",
"add_monitor",
"(",
"self",
",",
"actor",
",",
"monitor_name",
",",
"**",
"params",
")",
":",
"if",
"monitor_name",
"in",
"self",
".",
"registered",
":",
"raise",
"KeyError",
"(",
"'Monitor \"%s\" already available'",
"%",
"monitor_name",
")",
"params",
... | Add a new ``monitor``.
:param monitor_class: a :class:`.Monitor` class.
:param monitor_name: a unique name for the monitor.
:param kwargs: dictionary of key-valued parameters for the monitor.
:return: the :class:`.Monitor` added. | [
"Add",
"a",
"new",
"monitor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L202-L215 | train |
quantmind/pulsar | pulsar/apps/data/store.py | PubSub.publish_event | def publish_event(self, channel, event, message):
'''Publish a new event ``message`` to a ``channel``.
'''
assert self.protocol is not None, "Protocol required"
msg = {'event': event, 'channel': channel}
if message:
msg['data'] = message
return self.publish(channel, msg) | python | def publish_event(self, channel, event, message):
'''Publish a new event ``message`` to a ``channel``.
'''
assert self.protocol is not None, "Protocol required"
msg = {'event': event, 'channel': channel}
if message:
msg['data'] = message
return self.publish(channel, msg) | [
"def",
"publish_event",
"(",
"self",
",",
"channel",
",",
"event",
",",
"message",
")",
":",
"assert",
"self",
".",
"protocol",
"is",
"not",
"None",
",",
"\"Protocol required\"",
"msg",
"=",
"{",
"'event'",
":",
"event",
",",
"'channel'",
":",
"channel",
... | Publish a new event ``message`` to a ``channel``. | [
"Publish",
"a",
"new",
"event",
"message",
"to",
"a",
"channel",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/store.py#L303-L310 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.spawn | def spawn(self, actor, aid=None, **params):
'''Spawn a new actor from ``actor``.
'''
aid = aid or create_aid()
future = actor.send('arbiter', 'spawn', aid=aid, **params)
return actor_proxy_future(aid, future) | python | def spawn(self, actor, aid=None, **params):
'''Spawn a new actor from ``actor``.
'''
aid = aid or create_aid()
future = actor.send('arbiter', 'spawn', aid=aid, **params)
return actor_proxy_future(aid, future) | [
"def",
"spawn",
"(",
"self",
",",
"actor",
",",
"aid",
"=",
"None",
",",
"**",
"params",
")",
":",
"aid",
"=",
"aid",
"or",
"create_aid",
"(",
")",
"future",
"=",
"actor",
".",
"send",
"(",
"'arbiter'",
",",
"'spawn'",
",",
"aid",
"=",
"aid",
","... | Spawn a new actor from ``actor``. | [
"Spawn",
"a",
"new",
"actor",
"from",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L90-L95 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.run_actor | def run_actor(self, actor):
'''Start running the ``actor``.
'''
set_actor(actor)
if not actor.mailbox.address:
address = ('127.0.0.1', 0)
actor._loop.create_task(
actor.mailbox.start_serving(address=address)
)
actor._loop.run_forever() | python | def run_actor(self, actor):
'''Start running the ``actor``.
'''
set_actor(actor)
if not actor.mailbox.address:
address = ('127.0.0.1', 0)
actor._loop.create_task(
actor.mailbox.start_serving(address=address)
)
actor._loop.run_forever() | [
"def",
"run_actor",
"(",
"self",
",",
"actor",
")",
":",
"set_actor",
"(",
"actor",
")",
"if",
"not",
"actor",
".",
"mailbox",
".",
"address",
":",
"address",
"=",
"(",
"'127.0.0.1'",
",",
"0",
")",
"actor",
".",
"_loop",
".",
"create_task",
"(",
"ac... | Start running the ``actor``. | [
"Start",
"running",
"the",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L97-L106 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.setup_event_loop | def setup_event_loop(self, actor):
'''Set up the event loop for ``actor``.
'''
actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
if self.cfg and self.cfg.concurrency == 'thread':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
raise
if not hasattr(loop, 'logger'):
loop.logger = actor.logger
actor.mailbox = self.create_mailbox(actor, loop)
return loop | python | def setup_event_loop(self, actor):
'''Set up the event loop for ``actor``.
'''
actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
if self.cfg and self.cfg.concurrency == 'thread':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
raise
if not hasattr(loop, 'logger'):
loop.logger = actor.logger
actor.mailbox = self.create_mailbox(actor, loop)
return loop | [
"def",
"setup_event_loop",
"(",
"self",
",",
"actor",
")",
":",
"actor",
".",
"logger",
"=",
"self",
".",
"cfg",
".",
"configured_logger",
"(",
"'pulsar.%s'",
"%",
"actor",
".",
"name",
")",
"try",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",... | Set up the event loop for ``actor``. | [
"Set",
"up",
"the",
"event",
"loop",
"for",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L111-L126 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.hand_shake | def hand_shake(self, actor, run=True):
'''Perform the hand shake for ``actor``
The hand shake occurs when the ``actor`` is in starting state.
It performs the following actions:
* set the ``actor`` as the actor of the current thread
* bind two additional callbacks to the ``start`` event
* fire the ``start`` event
If the hand shake is successful, the actor will eventually
results in a running state.
'''
try:
assert actor.state == ACTOR_STATES.STARTING
if actor.cfg.debug:
actor.logger.debug('starting handshake')
actor.event('start').fire()
if run:
self._switch_to_run(actor)
except Exception as exc:
actor.stop(exc) | python | def hand_shake(self, actor, run=True):
'''Perform the hand shake for ``actor``
The hand shake occurs when the ``actor`` is in starting state.
It performs the following actions:
* set the ``actor`` as the actor of the current thread
* bind two additional callbacks to the ``start`` event
* fire the ``start`` event
If the hand shake is successful, the actor will eventually
results in a running state.
'''
try:
assert actor.state == ACTOR_STATES.STARTING
if actor.cfg.debug:
actor.logger.debug('starting handshake')
actor.event('start').fire()
if run:
self._switch_to_run(actor)
except Exception as exc:
actor.stop(exc) | [
"def",
"hand_shake",
"(",
"self",
",",
"actor",
",",
"run",
"=",
"True",
")",
":",
"try",
":",
"assert",
"actor",
".",
"state",
"==",
"ACTOR_STATES",
".",
"STARTING",
"if",
"actor",
".",
"cfg",
".",
"debug",
":",
"actor",
".",
"logger",
".",
"debug",... | Perform the hand shake for ``actor``
The hand shake occurs when the ``actor`` is in starting state.
It performs the following actions:
* set the ``actor`` as the actor of the current thread
* bind two additional callbacks to the ``start`` event
* fire the ``start`` event
If the hand shake is successful, the actor will eventually
results in a running state. | [
"Perform",
"the",
"hand",
"shake",
"for",
"actor"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L128-L149 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.create_mailbox | def create_mailbox(self, actor, loop):
'''Create the mailbox for ``actor``.'''
client = MailboxClient(actor.monitor.address, actor, loop)
loop.call_soon_threadsafe(self.hand_shake, actor)
return client | python | def create_mailbox(self, actor, loop):
'''Create the mailbox for ``actor``.'''
client = MailboxClient(actor.monitor.address, actor, loop)
loop.call_soon_threadsafe(self.hand_shake, actor)
return client | [
"def",
"create_mailbox",
"(",
"self",
",",
"actor",
",",
"loop",
")",
":",
"client",
"=",
"MailboxClient",
"(",
"actor",
".",
"monitor",
".",
"address",
",",
"actor",
",",
"loop",
")",
"loop",
".",
"call_soon_threadsafe",
"(",
"self",
".",
"hand_shake",
... | Create the mailbox for ``actor``. | [
"Create",
"the",
"mailbox",
"for",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L156-L160 | train |
quantmind/pulsar | pulsar/async/concurrency.py | Concurrency.stop | def stop(self, actor, exc=None, exit_code=None):
"""Gracefully stop the ``actor``.
"""
if actor.state <= ACTOR_STATES.RUN:
# The actor has not started the stopping process. Starts it now.
actor.state = ACTOR_STATES.STOPPING
actor.event('start').clear()
if exc:
if not exit_code:
exit_code = getattr(exc, 'exit_code', 1)
if exit_code == 1:
exc_info = sys.exc_info()
if exc_info[0] is not None:
actor.logger.critical('Stopping', exc_info=exc_info)
else:
actor.logger.critical('Stopping: %s', exc)
elif exit_code == 2:
actor.logger.error(str(exc))
elif exit_code:
actor.stream.writeln(str(exc))
else:
if not exit_code:
exit_code = getattr(actor._loop, 'exit_code', 0)
#
# Fire stopping event
actor.exit_code = exit_code
actor.stopping_waiters = []
actor.event('stopping').fire()
if actor.stopping_waiters and actor._loop.is_running():
actor.logger.info('asynchronous stopping')
# make sure to return the future (used by arbiter for waiting)
return actor._loop.create_task(self._async_stopping(actor))
else:
if actor.logger:
actor.logger.info('stopping')
self._stop_actor(actor)
elif actor.stopped():
return self._stop_actor(actor, True) | python | def stop(self, actor, exc=None, exit_code=None):
"""Gracefully stop the ``actor``.
"""
if actor.state <= ACTOR_STATES.RUN:
# The actor has not started the stopping process. Starts it now.
actor.state = ACTOR_STATES.STOPPING
actor.event('start').clear()
if exc:
if not exit_code:
exit_code = getattr(exc, 'exit_code', 1)
if exit_code == 1:
exc_info = sys.exc_info()
if exc_info[0] is not None:
actor.logger.critical('Stopping', exc_info=exc_info)
else:
actor.logger.critical('Stopping: %s', exc)
elif exit_code == 2:
actor.logger.error(str(exc))
elif exit_code:
actor.stream.writeln(str(exc))
else:
if not exit_code:
exit_code = getattr(actor._loop, 'exit_code', 0)
#
# Fire stopping event
actor.exit_code = exit_code
actor.stopping_waiters = []
actor.event('stopping').fire()
if actor.stopping_waiters and actor._loop.is_running():
actor.logger.info('asynchronous stopping')
# make sure to return the future (used by arbiter for waiting)
return actor._loop.create_task(self._async_stopping(actor))
else:
if actor.logger:
actor.logger.info('stopping')
self._stop_actor(actor)
elif actor.stopped():
return self._stop_actor(actor, True) | [
"def",
"stop",
"(",
"self",
",",
"actor",
",",
"exc",
"=",
"None",
",",
"exit_code",
"=",
"None",
")",
":",
"if",
"actor",
".",
"state",
"<=",
"ACTOR_STATES",
".",
"RUN",
":",
"actor",
".",
"state",
"=",
"ACTOR_STATES",
".",
"STOPPING",
"actor",
".",... | Gracefully stop the ``actor``. | [
"Gracefully",
"stop",
"the",
"actor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L179-L218 | train |
quantmind/pulsar | pulsar/apps/wsgi/auth.py | DigestAuth.authenticated | def authenticated(self, environ, username=None, password=None, **params):
'''Called by the server to check if client is authenticated.'''
if username != self.username:
return False
o = self.options
qop = o.get('qop')
method = environ['REQUEST_METHOD']
uri = environ.get('PATH_INFO', '')
ha1 = self.ha1(o['realm'], password)
ha2 = self.ha2(qop, method, uri)
if qop is None:
response = hexmd5(":".join((ha1, self.nonce, ha2)))
elif qop == 'auth' or qop == 'auth-int':
response = hexmd5(":".join((ha1, o['nonce'], o['nc'],
o['cnonce'], qop, ha2)))
else:
raise ValueError("qop value are wrong")
return o['response'] == response | python | def authenticated(self, environ, username=None, password=None, **params):
'''Called by the server to check if client is authenticated.'''
if username != self.username:
return False
o = self.options
qop = o.get('qop')
method = environ['REQUEST_METHOD']
uri = environ.get('PATH_INFO', '')
ha1 = self.ha1(o['realm'], password)
ha2 = self.ha2(qop, method, uri)
if qop is None:
response = hexmd5(":".join((ha1, self.nonce, ha2)))
elif qop == 'auth' or qop == 'auth-int':
response = hexmd5(":".join((ha1, o['nonce'], o['nc'],
o['cnonce'], qop, ha2)))
else:
raise ValueError("qop value are wrong")
return o['response'] == response | [
"def",
"authenticated",
"(",
"self",
",",
"environ",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"**",
"params",
")",
":",
"if",
"username",
"!=",
"self",
".",
"username",
":",
"return",
"False",
"o",
"=",
"self",
".",
"options",
... | Called by the server to check if client is authenticated. | [
"Called",
"by",
"the",
"server",
"to",
"check",
"if",
"client",
"is",
"authenticated",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/auth.py#L103-L120 | train |
quantmind/pulsar | pulsar/apps/data/channels.py | Channels.register | async def register(self, channel, event, callback):
"""Register a callback to ``channel_name`` and ``event``.
A prefix will be added to the channel name if not already available or
the prefix is an empty string
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel where the callback
was registered
"""
channel = self.channel(channel)
event = channel.register(event, callback)
await channel.connect(event.name)
return channel | python | async def register(self, channel, event, callback):
"""Register a callback to ``channel_name`` and ``event``.
A prefix will be added to the channel name if not already available or
the prefix is an empty string
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel where the callback
was registered
"""
channel = self.channel(channel)
event = channel.register(event, callback)
await channel.connect(event.name)
return channel | [
"async",
"def",
"register",
"(",
"self",
",",
"channel",
",",
"event",
",",
"callback",
")",
":",
"channel",
"=",
"self",
".",
"channel",
"(",
"channel",
")",
"event",
"=",
"channel",
".",
"register",
"(",
"event",
",",
"callback",
")",
"await",
"chann... | Register a callback to ``channel_name`` and ``event``.
A prefix will be added to the channel name if not already available or
the prefix is an empty string
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel where the callback
was registered | [
"Register",
"a",
"callback",
"to",
"channel_name",
"and",
"event",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L135-L150 | train |
quantmind/pulsar | pulsar/apps/data/channels.py | Channels.unregister | async def unregister(self, channel, event, callback):
"""Safely unregister a callback from the list of ``event``
callbacks for ``channel_name``.
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel object where the
``callback`` was removed (if found)
"""
channel = self.channel(channel, create=False)
if channel:
channel.unregister(event, callback)
if not channel:
await channel.disconnect()
self.channels.pop(channel.name)
return channel | python | async def unregister(self, channel, event, callback):
"""Safely unregister a callback from the list of ``event``
callbacks for ``channel_name``.
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel object where the
``callback`` was removed (if found)
"""
channel = self.channel(channel, create=False)
if channel:
channel.unregister(event, callback)
if not channel:
await channel.disconnect()
self.channels.pop(channel.name)
return channel | [
"async",
"def",
"unregister",
"(",
"self",
",",
"channel",
",",
"event",
",",
"callback",
")",
":",
"channel",
"=",
"self",
".",
"channel",
"(",
"channel",
",",
"create",
"=",
"False",
")",
"if",
"channel",
":",
"channel",
".",
"unregister",
"(",
"even... | Safely unregister a callback from the list of ``event``
callbacks for ``channel_name``.
:param channel: channel name
:param event: event name
:param callback: callback to execute when event on channel occurs
:return: a coroutine which results in the channel object where the
``callback`` was removed (if found) | [
"Safely",
"unregister",
"a",
"callback",
"from",
"the",
"list",
"of",
"event",
"callbacks",
"for",
"channel_name",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L152-L168 | train |
quantmind/pulsar | pulsar/apps/data/channels.py | Channels.connect | async def connect(self, next_time=None):
"""Connect with store
:return: a coroutine and therefore it must be awaited
"""
if self.status in can_connect:
loop = self._loop
if loop.is_running():
self.status = StatusType.connecting
await self._connect(next_time) | python | async def connect(self, next_time=None):
"""Connect with store
:return: a coroutine and therefore it must be awaited
"""
if self.status in can_connect:
loop = self._loop
if loop.is_running():
self.status = StatusType.connecting
await self._connect(next_time) | [
"async",
"def",
"connect",
"(",
"self",
",",
"next_time",
"=",
"None",
")",
":",
"if",
"self",
".",
"status",
"in",
"can_connect",
":",
"loop",
"=",
"self",
".",
"_loop",
"if",
"loop",
".",
"is_running",
"(",
")",
":",
"self",
".",
"status",
"=",
"... | Connect with store
:return: a coroutine and therefore it must be awaited | [
"Connect",
"with",
"store"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L170-L179 | train |
quantmind/pulsar | pulsar/apps/data/channels.py | Channel.register | def register(self, event, callback):
"""Register a ``callback`` for ``event``
"""
pattern = self.channels.event_pattern(event)
entry = self.callbacks.get(pattern)
if not entry:
entry = event_callbacks(event, pattern, re.compile(pattern), [])
self.callbacks[entry.pattern] = entry
if callback not in entry.callbacks:
entry.callbacks.append(callback)
return entry | python | def register(self, event, callback):
"""Register a ``callback`` for ``event``
"""
pattern = self.channels.event_pattern(event)
entry = self.callbacks.get(pattern)
if not entry:
entry = event_callbacks(event, pattern, re.compile(pattern), [])
self.callbacks[entry.pattern] = entry
if callback not in entry.callbacks:
entry.callbacks.append(callback)
return entry | [
"def",
"register",
"(",
"self",
",",
"event",
",",
"callback",
")",
":",
"pattern",
"=",
"self",
".",
"channels",
".",
"event_pattern",
"(",
"event",
")",
"entry",
"=",
"self",
".",
"callbacks",
".",
"get",
"(",
"pattern",
")",
"if",
"not",
"entry",
... | Register a ``callback`` for ``event`` | [
"Register",
"a",
"callback",
"for",
"event"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L329-L341 | train |
quantmind/pulsar | pulsar/async/futures.py | add_errback | def add_errback(future, callback, loop=None):
'''Add a ``callback`` to a ``future`` executed only if an exception
or cancellation has occurred.'''
def _error_back(fut):
if fut._exception:
callback(fut.exception())
elif fut.cancelled():
callback(CancelledError())
future = ensure_future(future, loop=None)
future.add_done_callback(_error_back)
return future | python | def add_errback(future, callback, loop=None):
'''Add a ``callback`` to a ``future`` executed only if an exception
or cancellation has occurred.'''
def _error_back(fut):
if fut._exception:
callback(fut.exception())
elif fut.cancelled():
callback(CancelledError())
future = ensure_future(future, loop=None)
future.add_done_callback(_error_back)
return future | [
"def",
"add_errback",
"(",
"future",
",",
"callback",
",",
"loop",
"=",
"None",
")",
":",
"def",
"_error_back",
"(",
"fut",
")",
":",
"if",
"fut",
".",
"_exception",
":",
"callback",
"(",
"fut",
".",
"exception",
"(",
")",
")",
"elif",
"fut",
".",
... | Add a ``callback`` to a ``future`` executed only if an exception
or cancellation has occurred. | [
"Add",
"a",
"callback",
"to",
"a",
"future",
"executed",
"only",
"if",
"an",
"exception",
"or",
"cancellation",
"has",
"occurred",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/futures.py#L58-L69 | train |
quantmind/pulsar | pulsar/async/futures.py | AsyncObject.timeit | def timeit(self, method, times, *args, **kwargs):
'''Useful utility for benchmarking an asynchronous ``method``.
:param method: the name of the ``method`` to execute
:param times: number of times to execute the ``method``
:param args: positional arguments to pass to the ``method``
:param kwargs: key-valued arguments to pass to the ``method``
:return: a :class:`~asyncio.Future` which results in a :class:`Bench`
object if successful
The usage is simple::
>>> b = self.timeit('asyncmethod', 100)
'''
bench = Bench(times, loop=self._loop)
return bench(getattr(self, method), *args, **kwargs) | python | def timeit(self, method, times, *args, **kwargs):
'''Useful utility for benchmarking an asynchronous ``method``.
:param method: the name of the ``method`` to execute
:param times: number of times to execute the ``method``
:param args: positional arguments to pass to the ``method``
:param kwargs: key-valued arguments to pass to the ``method``
:return: a :class:`~asyncio.Future` which results in a :class:`Bench`
object if successful
The usage is simple::
>>> b = self.timeit('asyncmethod', 100)
'''
bench = Bench(times, loop=self._loop)
return bench(getattr(self, method), *args, **kwargs) | [
"def",
"timeit",
"(",
"self",
",",
"method",
",",
"times",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"bench",
"=",
"Bench",
"(",
"times",
",",
"loop",
"=",
"self",
".",
"_loop",
")",
"return",
"bench",
"(",
"getattr",
"(",
"self",
",",
"me... | Useful utility for benchmarking an asynchronous ``method``.
:param method: the name of the ``method`` to execute
:param times: number of times to execute the ``method``
:param args: positional arguments to pass to the ``method``
:param kwargs: key-valued arguments to pass to the ``method``
:return: a :class:`~asyncio.Future` which results in a :class:`Bench`
object if successful
The usage is simple::
>>> b = self.timeit('asyncmethod', 100) | [
"Useful",
"utility",
"for",
"benchmarking",
"an",
"asynchronous",
"method",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/futures.py#L194-L209 | train |
quantmind/pulsar | pulsar/apps/http/stream.py | HttpStream.read | async def read(self, n=None):
"""Read all content
"""
if self._streamed:
return b''
buffer = []
async for body in self:
buffer.append(body)
return b''.join(buffer) | python | async def read(self, n=None):
"""Read all content
"""
if self._streamed:
return b''
buffer = []
async for body in self:
buffer.append(body)
return b''.join(buffer) | [
"async",
"def",
"read",
"(",
"self",
",",
"n",
"=",
"None",
")",
":",
"if",
"self",
".",
"_streamed",
":",
"return",
"b''",
"buffer",
"=",
"[",
"]",
"async",
"for",
"body",
"in",
"self",
":",
"buffer",
".",
"append",
"(",
"body",
")",
"return",
"... | Read all content | [
"Read",
"all",
"content"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/stream.py#L27-L35 | train |
quantmind/pulsar | pulsar/async/commands.py | notify | def notify(request, info):
'''The actor notify itself with a dictionary of information.
The command perform the following actions:
* Update the mailbox to the current consumer of the actor connection
* Update the info dictionary
* Returns the time of the update
'''
t = time()
actor = request.actor
remote_actor = request.caller
if isinstance(remote_actor, ActorProxyMonitor):
remote_actor.mailbox = request.connection
info['last_notified'] = t
remote_actor.info = info
callback = remote_actor.callback
# if a callback is still available, this is the first
# time we got notified
if callback:
remote_actor.callback = None
callback.set_result(remote_actor)
if actor.cfg.debug:
actor.logger.debug('Got first notification from %s',
remote_actor)
elif actor.cfg.debug:
actor.logger.debug('Got notification from %s', remote_actor)
else:
actor.logger.warning('notify got a bad actor')
return t | python | def notify(request, info):
'''The actor notify itself with a dictionary of information.
The command perform the following actions:
* Update the mailbox to the current consumer of the actor connection
* Update the info dictionary
* Returns the time of the update
'''
t = time()
actor = request.actor
remote_actor = request.caller
if isinstance(remote_actor, ActorProxyMonitor):
remote_actor.mailbox = request.connection
info['last_notified'] = t
remote_actor.info = info
callback = remote_actor.callback
# if a callback is still available, this is the first
# time we got notified
if callback:
remote_actor.callback = None
callback.set_result(remote_actor)
if actor.cfg.debug:
actor.logger.debug('Got first notification from %s',
remote_actor)
elif actor.cfg.debug:
actor.logger.debug('Got notification from %s', remote_actor)
else:
actor.logger.warning('notify got a bad actor')
return t | [
"def",
"notify",
"(",
"request",
",",
"info",
")",
":",
"t",
"=",
"time",
"(",
")",
"actor",
"=",
"request",
".",
"actor",
"remote_actor",
"=",
"request",
".",
"caller",
"if",
"isinstance",
"(",
"remote_actor",
",",
"ActorProxyMonitor",
")",
":",
"remote... | The actor notify itself with a dictionary of information.
The command perform the following actions:
* Update the mailbox to the current consumer of the actor connection
* Update the info dictionary
* Returns the time of the update | [
"The",
"actor",
"notify",
"itself",
"with",
"a",
"dictionary",
"of",
"information",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/commands.py#L49-L78 | train |
quantmind/pulsar | pulsar/async/mixins.py | FlowControl.write | def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing.
"""
if self.closed:
raise ConnectionResetError(
'Transport closed - cannot write on %s' % self
)
else:
t = self.transport
if self._paused or self._buffer:
self._buffer.appendleft(data)
self._buffer_size += len(data)
self._write_from_buffer()
if self._buffer_size > 2 * self._b_limit:
if self._waiter and not self._waiter.cancelled():
self.logger.warning(
'%s buffer size is %d: limit is %d ',
self._buffer_size, self._b_limit
)
else:
t.pause_reading()
self._waiter = self._loop.create_future()
else:
t.write(data)
self.changed()
return self._waiter | python | def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing.
"""
if self.closed:
raise ConnectionResetError(
'Transport closed - cannot write on %s' % self
)
else:
t = self.transport
if self._paused or self._buffer:
self._buffer.appendleft(data)
self._buffer_size += len(data)
self._write_from_buffer()
if self._buffer_size > 2 * self._b_limit:
if self._waiter and not self._waiter.cancelled():
self.logger.warning(
'%s buffer size is %d: limit is %d ',
self._buffer_size, self._b_limit
)
else:
t.pause_reading()
self._waiter = self._loop.create_future()
else:
t.write(data)
self.changed()
return self._waiter | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ConnectionResetError",
"(",
"'Transport closed - cannot write on %s'",
"%",
"self",
")",
"else",
":",
"t",
"=",
"self",
".",
"transport",
"if",
"self",
".",
"_p... | Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing. | [
"Write",
"data",
"into",
"the",
"wire",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L20-L48 | train |
quantmind/pulsar | pulsar/async/mixins.py | Pipeline.pipeline | def pipeline(self, consumer):
"""Add a consumer to the pipeline
"""
if self._pipeline is None:
self._pipeline = ResponsePipeline(self)
self.event('connection_lost').bind(self._close_pipeline)
self._pipeline.put(consumer) | python | def pipeline(self, consumer):
"""Add a consumer to the pipeline
"""
if self._pipeline is None:
self._pipeline = ResponsePipeline(self)
self.event('connection_lost').bind(self._close_pipeline)
self._pipeline.put(consumer) | [
"def",
"pipeline",
"(",
"self",
",",
"consumer",
")",
":",
"if",
"self",
".",
"_pipeline",
"is",
"None",
":",
"self",
".",
"_pipeline",
"=",
"ResponsePipeline",
"(",
"self",
")",
"self",
".",
"event",
"(",
"'connection_lost'",
")",
".",
"bind",
"(",
"s... | Add a consumer to the pipeline | [
"Add",
"a",
"consumer",
"to",
"the",
"pipeline"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L157-L163 | train |
quantmind/pulsar | pulsar/utils/pylib/websocket.py | FrameParser.encode | def encode(self, message, final=True, masking_key=None,
opcode=None, rsv1=0, rsv2=0, rsv3=0):
'''Encode a ``message`` for writing into the wire.
To produce several frames for a given large message use
:meth:`multi_encode` method.
'''
fin = 1 if final else 0
opcode, masking_key, data = self._info(message, opcode, masking_key)
return self._encode(data, opcode, masking_key, fin,
rsv1, rsv2, rsv3) | python | def encode(self, message, final=True, masking_key=None,
opcode=None, rsv1=0, rsv2=0, rsv3=0):
'''Encode a ``message`` for writing into the wire.
To produce several frames for a given large message use
:meth:`multi_encode` method.
'''
fin = 1 if final else 0
opcode, masking_key, data = self._info(message, opcode, masking_key)
return self._encode(data, opcode, masking_key, fin,
rsv1, rsv2, rsv3) | [
"def",
"encode",
"(",
"self",
",",
"message",
",",
"final",
"=",
"True",
",",
"masking_key",
"=",
"None",
",",
"opcode",
"=",
"None",
",",
"rsv1",
"=",
"0",
",",
"rsv2",
"=",
"0",
",",
"rsv3",
"=",
"0",
")",
":",
"fin",
"=",
"1",
"if",
"final",... | Encode a ``message`` for writing into the wire.
To produce several frames for a given large message use
:meth:`multi_encode` method. | [
"Encode",
"a",
"message",
"for",
"writing",
"into",
"the",
"wire",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/websocket.py#L140-L150 | train |
quantmind/pulsar | pulsar/utils/pylib/websocket.py | FrameParser.multi_encode | def multi_encode(self, message, masking_key=None, opcode=None,
rsv1=0, rsv2=0, rsv3=0, max_payload=0):
'''Encode a ``message`` into several frames depending on size.
Returns a generator of bytes to be sent over the wire.
'''
max_payload = max(2, max_payload or self._max_payload)
opcode, masking_key, data = self._info(message, opcode, masking_key)
#
while data:
if len(data) >= max_payload:
chunk, data, fin = (data[:max_payload],
data[max_payload:], 0)
else:
chunk, data, fin = data, b'', 1
yield self._encode(chunk, opcode, masking_key, fin,
rsv1, rsv2, rsv3) | python | def multi_encode(self, message, masking_key=None, opcode=None,
rsv1=0, rsv2=0, rsv3=0, max_payload=0):
'''Encode a ``message`` into several frames depending on size.
Returns a generator of bytes to be sent over the wire.
'''
max_payload = max(2, max_payload or self._max_payload)
opcode, masking_key, data = self._info(message, opcode, masking_key)
#
while data:
if len(data) >= max_payload:
chunk, data, fin = (data[:max_payload],
data[max_payload:], 0)
else:
chunk, data, fin = data, b'', 1
yield self._encode(chunk, opcode, masking_key, fin,
rsv1, rsv2, rsv3) | [
"def",
"multi_encode",
"(",
"self",
",",
"message",
",",
"masking_key",
"=",
"None",
",",
"opcode",
"=",
"None",
",",
"rsv1",
"=",
"0",
",",
"rsv2",
"=",
"0",
",",
"rsv3",
"=",
"0",
",",
"max_payload",
"=",
"0",
")",
":",
"max_payload",
"=",
"max",... | Encode a ``message`` into several frames depending on size.
Returns a generator of bytes to be sent over the wire. | [
"Encode",
"a",
"message",
"into",
"several",
"frames",
"depending",
"on",
"size",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/websocket.py#L152-L168 | train |
quantmind/pulsar | pulsar/apps/data/redis/client.py | RedisClient.sort | def sort(self, key, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
'''Sort and return the list, set or sorted set at ``key``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
'''
if ((start is not None and num is None) or
(num is not None and start is None)):
raise CommandError("``start`` and ``num`` must both be specified")
pieces = [key]
if by is not None:
pieces.append('BY')
pieces.append(by)
if start is not None and num is not None:
pieces.append('LIMIT')
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, str):
pieces.append('GET')
pieces.append(get)
else:
for g in get:
pieces.append('GET')
pieces.append(g)
if desc:
pieces.append('DESC')
if alpha:
pieces.append('ALPHA')
if store is not None:
pieces.append('STORE')
pieces.append(store)
if groups:
if not get or isinstance(get, str) or len(get) < 2:
raise CommandError('when using "groups" the "get" argument '
'must be specified and contain at least '
'two keys')
options = {'groups': len(get) if groups else None}
return self.execute_command('SORT', *pieces, **options) | python | def sort(self, key, start=None, num=None, by=None, get=None,
desc=False, alpha=False, store=None, groups=False):
'''Sort and return the list, set or sorted set at ``key``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``.
'''
if ((start is not None and num is None) or
(num is not None and start is None)):
raise CommandError("``start`` and ``num`` must both be specified")
pieces = [key]
if by is not None:
pieces.append('BY')
pieces.append(by)
if start is not None and num is not None:
pieces.append('LIMIT')
pieces.append(start)
pieces.append(num)
if get is not None:
# If get is a string assume we want to get a single value.
# Otherwise assume it's an interable and we want to get multiple
# values. We can't just iterate blindly because strings are
# iterable.
if isinstance(get, str):
pieces.append('GET')
pieces.append(get)
else:
for g in get:
pieces.append('GET')
pieces.append(g)
if desc:
pieces.append('DESC')
if alpha:
pieces.append('ALPHA')
if store is not None:
pieces.append('STORE')
pieces.append(store)
if groups:
if not get or isinstance(get, str) or len(get) < 2:
raise CommandError('when using "groups" the "get" argument '
'must be specified and contain at least '
'two keys')
options = {'groups': len(get) if groups else None}
return self.execute_command('SORT', *pieces, **options) | [
"def",
"sort",
"(",
"self",
",",
"key",
",",
"start",
"=",
"None",
",",
"num",
"=",
"None",
",",
"by",
"=",
"None",
",",
"get",
"=",
"None",
",",
"desc",
"=",
"False",
",",
"alpha",
"=",
"False",
",",
"store",
"=",
"None",
",",
"groups",
"=",
... | Sort and return the list, set or sorted set at ``key``.
``start`` and ``num`` allow for paging through the sorted data
``by`` allows using an external key to weight and sort the items.
Use an "*" to indicate where in the key the item value is located
``get`` allows for returning items from external keys rather than the
sorted data itself. Use an "*" to indicate where int he key
the item value is located
``desc`` allows for reversing the sort
``alpha`` allows for sorting lexicographically rather than numerically
``store`` allows for storing the result of the sort into
the key ``store``
``groups`` if set to True and if ``get`` contains at least two
elements, sort will return a list of tuples, each containing the
values fetched from the arguments to ``get``. | [
"Sort",
"and",
"return",
"the",
"list",
"set",
"or",
"sorted",
"set",
"at",
"key",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/client.py#L434-L498 | train |
quantmind/pulsar | pulsar/apps/data/redis/client.py | Pipeline.commit | def commit(self, raise_on_error=True):
'''Send commands to redis.
'''
cmds = list(chain([(('multi',), {})],
self.command_stack, [(('exec',), {})]))
self.reset()
return self.store.execute_pipeline(cmds, raise_on_error) | python | def commit(self, raise_on_error=True):
'''Send commands to redis.
'''
cmds = list(chain([(('multi',), {})],
self.command_stack, [(('exec',), {})]))
self.reset()
return self.store.execute_pipeline(cmds, raise_on_error) | [
"def",
"commit",
"(",
"self",
",",
"raise_on_error",
"=",
"True",
")",
":",
"cmds",
"=",
"list",
"(",
"chain",
"(",
"[",
"(",
"(",
"'multi'",
",",
")",
",",
"{",
"}",
")",
"]",
",",
"self",
".",
"command_stack",
",",
"[",
"(",
"(",
"'exec'",
",... | Send commands to redis. | [
"Send",
"commands",
"to",
"redis",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/client.py#L533-L539 | train |
quantmind/pulsar | pulsar/utils/config.py | Config.copy_globals | def copy_globals(self, cfg):
"""Copy global settings from ``cfg`` to this config.
The settings are copied only if they were not already modified.
"""
for name, setting in cfg.settings.items():
csetting = self.settings.get(name)
if (setting.is_global and csetting is not None and
not csetting.modified):
csetting.set(setting.get()) | python | def copy_globals(self, cfg):
"""Copy global settings from ``cfg`` to this config.
The settings are copied only if they were not already modified.
"""
for name, setting in cfg.settings.items():
csetting = self.settings.get(name)
if (setting.is_global and csetting is not None and
not csetting.modified):
csetting.set(setting.get()) | [
"def",
"copy_globals",
"(",
"self",
",",
"cfg",
")",
":",
"for",
"name",
",",
"setting",
"in",
"cfg",
".",
"settings",
".",
"items",
"(",
")",
":",
"csetting",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"name",
")",
"if",
"(",
"setting",
".",
... | Copy global settings from ``cfg`` to this config.
The settings are copied only if they were not already modified. | [
"Copy",
"global",
"settings",
"from",
"cfg",
"to",
"this",
"config",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L197-L206 | train |
quantmind/pulsar | pulsar/utils/config.py | Config.parse_command_line | def parse_command_line(self, argv=None):
"""Parse the command line
"""
if self.config:
parser = argparse.ArgumentParser(add_help=False)
self.settings['config'].add_argument(parser)
opts, _ = parser.parse_known_args(argv)
if opts.config is not None:
self.set('config', opts.config)
self.params.update(self.import_from_module())
parser = self.parser()
opts = parser.parse_args(argv)
for k, v in opts.__dict__.items():
if v is None:
continue
self.set(k.lower(), v) | python | def parse_command_line(self, argv=None):
"""Parse the command line
"""
if self.config:
parser = argparse.ArgumentParser(add_help=False)
self.settings['config'].add_argument(parser)
opts, _ = parser.parse_known_args(argv)
if opts.config is not None:
self.set('config', opts.config)
self.params.update(self.import_from_module())
parser = self.parser()
opts = parser.parse_args(argv)
for k, v in opts.__dict__.items():
if v is None:
continue
self.set(k.lower(), v) | [
"def",
"parse_command_line",
"(",
"self",
",",
"argv",
"=",
"None",
")",
":",
"if",
"self",
".",
"config",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"self",
".",
"settings",
"[",
"'config'",
"]",
".",
"a... | Parse the command line | [
"Parse",
"the",
"command",
"line"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L291-L308 | train |
quantmind/pulsar | pulsar/utils/tools/text.py | num2eng | def num2eng(num):
'''English representation of a number up to a trillion.
'''
num = str(int(num)) # Convert to string, throw if bad number
if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check
return num
elif num == '0': # Zero is a special case
return 'zero'
pron = [] # Result accumulator
first = True
for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')):
num = ''.join(reversed(bits))
n = int(num)
bits = []
if n > 99: # Got hundred
bits.append('%s hundred' % _SMALL[num[0]])
num = num[1:]
n = int(num)
num = str(n)
if (n > 20) and (n != (n // 10 * 10)):
bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]]))
elif n:
bits.append(_SMALL[num])
if len(bits) == 2 and first:
first = False
p = ' and '.join(bits)
else:
p = ' '.join(bits)
if p and pr:
p = '%s %s' % (p, pr)
pron.append(p)
return ', '.join(reversed(pron)) | python | def num2eng(num):
'''English representation of a number up to a trillion.
'''
num = str(int(num)) # Convert to string, throw if bad number
if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check
return num
elif num == '0': # Zero is a special case
return 'zero'
pron = [] # Result accumulator
first = True
for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')):
num = ''.join(reversed(bits))
n = int(num)
bits = []
if n > 99: # Got hundred
bits.append('%s hundred' % _SMALL[num[0]])
num = num[1:]
n = int(num)
num = str(n)
if (n > 20) and (n != (n // 10 * 10)):
bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]]))
elif n:
bits.append(_SMALL[num])
if len(bits) == 2 and first:
first = False
p = ' and '.join(bits)
else:
p = ' '.join(bits)
if p and pr:
p = '%s %s' % (p, pr)
pron.append(p)
return ', '.join(reversed(pron)) | [
"def",
"num2eng",
"(",
"num",
")",
":",
"num",
"=",
"str",
"(",
"int",
"(",
"num",
")",
")",
"if",
"(",
"len",
"(",
"num",
")",
"/",
"3",
">=",
"len",
"(",
"_PRONOUNCE",
")",
")",
":",
"return",
"num",
"elif",
"num",
"==",
"'0'",
":",
"return... | English representation of a number up to a trillion. | [
"English",
"representation",
"of",
"a",
"number",
"up",
"to",
"a",
"trillion",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/text.py#L48-L79 | train |
quantmind/pulsar | pulsar/apps/rpc/jsonrpc.py | JsonProxy.get_params | def get_params(self, *args, **kwargs):
'''
Create an array or positional or named parameters
Mixing positional and named parameters in one
call is not possible.
'''
kwargs.update(self._data)
if args and kwargs:
raise ValueError('Cannot mix positional and named parameters')
if args:
return list(args)
else:
return kwargs | python | def get_params(self, *args, **kwargs):
'''
Create an array or positional or named parameters
Mixing positional and named parameters in one
call is not possible.
'''
kwargs.update(self._data)
if args and kwargs:
raise ValueError('Cannot mix positional and named parameters')
if args:
return list(args)
else:
return kwargs | [
"def",
"get_params",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"self",
".",
"_data",
")",
"if",
"args",
"and",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'Cannot mix positional and named parameters'",
")",
... | Create an array or positional or named parameters
Mixing positional and named parameters in one
call is not possible. | [
"Create",
"an",
"array",
"or",
"positional",
"or",
"named",
"parameters",
"Mixing",
"positional",
"and",
"named",
"parameters",
"in",
"one",
"call",
"is",
"not",
"possible",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/jsonrpc.py#L253-L265 | train |
quantmind/pulsar | pulsar/async/mailbox.py | MessageConsumer.send | def send(self, command, sender, target, args, kwargs):
"""Used by the server to send messages to the client.
Returns a future.
"""
command = get_command(command)
data = {'command': command.__name__,
'id': create_aid(),
'sender': actor_identity(sender),
'target': actor_identity(target),
'args': args if args is not None else (),
'kwargs': kwargs if kwargs is not None else {}}
waiter = self._loop.create_future()
ack = None
if command.ack:
ack = create_aid()
data['ack'] = ack
self.pending_responses[ack] = waiter
try:
self.write(data)
except Exception as exc:
waiter.set_exception(exc)
if ack:
self.pending_responses.pop(ack, None)
else:
if not ack:
waiter.set_result(None)
return waiter | python | def send(self, command, sender, target, args, kwargs):
"""Used by the server to send messages to the client.
Returns a future.
"""
command = get_command(command)
data = {'command': command.__name__,
'id': create_aid(),
'sender': actor_identity(sender),
'target': actor_identity(target),
'args': args if args is not None else (),
'kwargs': kwargs if kwargs is not None else {}}
waiter = self._loop.create_future()
ack = None
if command.ack:
ack = create_aid()
data['ack'] = ack
self.pending_responses[ack] = waiter
try:
self.write(data)
except Exception as exc:
waiter.set_exception(exc)
if ack:
self.pending_responses.pop(ack, None)
else:
if not ack:
waiter.set_result(None)
return waiter | [
"def",
"send",
"(",
"self",
",",
"command",
",",
"sender",
",",
"target",
",",
"args",
",",
"kwargs",
")",
":",
"command",
"=",
"get_command",
"(",
"command",
")",
"data",
"=",
"{",
"'command'",
":",
"command",
".",
"__name__",
",",
"'id'",
":",
"cre... | Used by the server to send messages to the client.
Returns a future. | [
"Used",
"by",
"the",
"server",
"to",
"send",
"messages",
"to",
"the",
"client",
".",
"Returns",
"a",
"future",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mailbox.py#L156-L184 | train |
quantmind/pulsar | pulsar/utils/tools/pidfile.py | Pidfile.read | def read(self):
""" Validate pidfile and make it stale if needed"""
if not self.fname:
return
try:
with open(self.fname, "r") as f:
wpid = int(f.read() or 0)
if wpid <= 0:
return
return wpid
except IOError:
return | python | def read(self):
""" Validate pidfile and make it stale if needed"""
if not self.fname:
return
try:
with open(self.fname, "r") as f:
wpid = int(f.read() or 0)
if wpid <= 0:
return
return wpid
except IOError:
return | [
"def",
"read",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"fname",
":",
"return",
"try",
":",
"with",
"open",
"(",
"self",
".",
"fname",
",",
"\"r\"",
")",
"as",
"f",
":",
"wpid",
"=",
"int",
"(",
"f",
".",
"read",
"(",
")",
"or",
"0",
... | Validate pidfile and make it stale if needed | [
"Validate",
"pidfile",
"and",
"make",
"it",
"stale",
"if",
"needed"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/pidfile.py#L54-L65 | train |
quantmind/pulsar | pulsar/apps/greenio/lock.py | GreenLock.acquire | def acquire(self, timeout=None):
"""Acquires the lock if in the unlocked state otherwise switch
back to the parent coroutine.
"""
green = getcurrent()
parent = green.parent
if parent is None:
raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet')
if self._local.locked:
future = create_future(self._loop)
self._queue.append(future)
parent.switch(future)
self._local.locked = green
return self.locked() | python | def acquire(self, timeout=None):
"""Acquires the lock if in the unlocked state otherwise switch
back to the parent coroutine.
"""
green = getcurrent()
parent = green.parent
if parent is None:
raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet')
if self._local.locked:
future = create_future(self._loop)
self._queue.append(future)
parent.switch(future)
self._local.locked = green
return self.locked() | [
"def",
"acquire",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"green",
"=",
"getcurrent",
"(",
")",
"parent",
"=",
"green",
".",
"parent",
"if",
"parent",
"is",
"None",
":",
"raise",
"MustBeInChildGreenlet",
"(",
"'GreenLock.acquire in main greenlet'",... | Acquires the lock if in the unlocked state otherwise switch
back to the parent coroutine. | [
"Acquires",
"the",
"lock",
"if",
"in",
"the",
"unlocked",
"state",
"otherwise",
"switch",
"back",
"to",
"the",
"parent",
"coroutine",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/lock.py#L38-L53 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.cookies | def cookies(self):
"""Container of request cookies
"""
cookies = SimpleCookie()
cookie = self.environ.get('HTTP_COOKIE')
if cookie:
cookies.load(cookie)
return cookies | python | def cookies(self):
"""Container of request cookies
"""
cookies = SimpleCookie()
cookie = self.environ.get('HTTP_COOKIE')
if cookie:
cookies.load(cookie)
return cookies | [
"def",
"cookies",
"(",
"self",
")",
":",
"cookies",
"=",
"SimpleCookie",
"(",
")",
"cookie",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_COOKIE'",
")",
"if",
"cookie",
":",
"cookies",
".",
"load",
"(",
"cookie",
")",
"return",
"cookies"
] | Container of request cookies | [
"Container",
"of",
"request",
"cookies"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L172-L179 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.data_and_files | def data_and_files(self, data=True, files=True, stream=None):
"""Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asyncio.Future`
which results in the tuple.
The result is cached.
"""
if self.method in ENCODE_URL_METHODS:
value = {}, None
else:
value = self.cache.get('data_and_files')
if not value:
return self._data_and_files(data, files, stream)
elif data and files:
return value
elif data:
return value[0]
elif files:
return value[1]
else:
return None | python | def data_and_files(self, data=True, files=True, stream=None):
"""Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asyncio.Future`
which results in the tuple.
The result is cached.
"""
if self.method in ENCODE_URL_METHODS:
value = {}, None
else:
value = self.cache.get('data_and_files')
if not value:
return self._data_and_files(data, files, stream)
elif data and files:
return value
elif data:
return value[0]
elif files:
return value[1]
else:
return None | [
"def",
"data_and_files",
"(",
"self",
",",
"data",
"=",
"True",
",",
"files",
"=",
"True",
",",
"stream",
"=",
"None",
")",
":",
"if",
"self",
".",
"method",
"in",
"ENCODE_URL_METHODS",
":",
"value",
"=",
"{",
"}",
",",
"None",
"else",
":",
"value",
... | Retrieve body data.
Returns a two-elements tuple of a
:class:`~.MultiValueDict` containing data from
the request body, and data from uploaded files.
If the body data is not ready, return a :class:`~asyncio.Future`
which results in the tuple.
The result is cached. | [
"Retrieve",
"body",
"data",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L266-L292 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.get_host | def get_host(self, use_x_forwarded=True):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ):
host = self.environ['HTTP_X_FORWARDED_HOST']
port = self.environ.get('HTTP_X_FORWARDED_PORT')
if port and port != ('443' if self.is_secure else '80'):
host = '%s:%s' % (host, port)
return host
elif 'HTTP_HOST' in self.environ:
host = self.environ['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.environ['SERVER_NAME']
server_port = str(self.environ['SERVER_PORT'])
if server_port != ('443' if self.is_secure else '80'):
host = '%s:%s' % (host, server_port)
return host | python | def get_host(self, use_x_forwarded=True):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ):
host = self.environ['HTTP_X_FORWARDED_HOST']
port = self.environ.get('HTTP_X_FORWARDED_PORT')
if port and port != ('443' if self.is_secure else '80'):
host = '%s:%s' % (host, port)
return host
elif 'HTTP_HOST' in self.environ:
host = self.environ['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.environ['SERVER_NAME']
server_port = str(self.environ['SERVER_PORT'])
if server_port != ('443' if self.is_secure else '80'):
host = '%s:%s' % (host, server_port)
return host | [
"def",
"get_host",
"(",
"self",
",",
"use_x_forwarded",
"=",
"True",
")",
":",
"if",
"use_x_forwarded",
"and",
"(",
"'HTTP_X_FORWARDED_HOST'",
"in",
"self",
".",
"environ",
")",
":",
"host",
"=",
"self",
".",
"environ",
"[",
"'HTTP_X_FORWARDED_HOST'",
"]",
"... | Returns the HTTP host using the environment or request headers. | [
"Returns",
"the",
"HTTP",
"host",
"using",
"the",
"environment",
"or",
"request",
"headers",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L325-L342 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.get_client_address | def get_client_address(self, use_x_forwarded=True):
"""Obtain the client IP address
"""
xfor = self.environ.get('HTTP_X_FORWARDED_FOR')
if use_x_forwarded and xfor:
return xfor.split(',')[-1].strip()
else:
return self.environ['REMOTE_ADDR'] | python | def get_client_address(self, use_x_forwarded=True):
"""Obtain the client IP address
"""
xfor = self.environ.get('HTTP_X_FORWARDED_FOR')
if use_x_forwarded and xfor:
return xfor.split(',')[-1].strip()
else:
return self.environ['REMOTE_ADDR'] | [
"def",
"get_client_address",
"(",
"self",
",",
"use_x_forwarded",
"=",
"True",
")",
":",
"xfor",
"=",
"self",
".",
"environ",
".",
"get",
"(",
"'HTTP_X_FORWARDED_FOR'",
")",
"if",
"use_x_forwarded",
"and",
"xfor",
":",
"return",
"xfor",
".",
"split",
"(",
... | Obtain the client IP address | [
"Obtain",
"the",
"client",
"IP",
"address"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L344-L351 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.full_path | def full_path(self, *args, **query):
"""Return a full path"""
path = None
if args:
if len(args) > 1:
raise TypeError("full_url() takes exactly 1 argument "
"(%s given)" % len(args))
path = args[0]
if not path:
path = self.path
elif not path.startswith('/'):
path = remove_double_slash('%s/%s' % (self.path, path))
return iri_to_uri(path, query) | python | def full_path(self, *args, **query):
"""Return a full path"""
path = None
if args:
if len(args) > 1:
raise TypeError("full_url() takes exactly 1 argument "
"(%s given)" % len(args))
path = args[0]
if not path:
path = self.path
elif not path.startswith('/'):
path = remove_double_slash('%s/%s' % (self.path, path))
return iri_to_uri(path, query) | [
"def",
"full_path",
"(",
"self",
",",
"*",
"args",
",",
"**",
"query",
")",
":",
"path",
"=",
"None",
"if",
"args",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"full_url() takes exactly 1 argument \"",
"\"(%s given)\"",
... | Return a full path | [
"Return",
"a",
"full",
"path"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L353-L365 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.absolute_uri | def absolute_uri(self, location=None, scheme=None, **query):
"""Builds an absolute URI from ``location`` and variables
available in this request.
If no ``location`` is specified, the relative URI is built from
:meth:`full_path`.
"""
if not is_absolute_uri(location):
if location or location is None:
location = self.full_path(location, **query)
if not scheme:
scheme = self.is_secure and 'https' or 'http'
base = '%s://%s' % (scheme, self.get_host())
return '%s%s' % (base, location)
elif not scheme:
return iri_to_uri(location)
else:
raise ValueError('Absolute location with scheme not valid') | python | def absolute_uri(self, location=None, scheme=None, **query):
"""Builds an absolute URI from ``location`` and variables
available in this request.
If no ``location`` is specified, the relative URI is built from
:meth:`full_path`.
"""
if not is_absolute_uri(location):
if location or location is None:
location = self.full_path(location, **query)
if not scheme:
scheme = self.is_secure and 'https' or 'http'
base = '%s://%s' % (scheme, self.get_host())
return '%s%s' % (base, location)
elif not scheme:
return iri_to_uri(location)
else:
raise ValueError('Absolute location with scheme not valid') | [
"def",
"absolute_uri",
"(",
"self",
",",
"location",
"=",
"None",
",",
"scheme",
"=",
"None",
",",
"**",
"query",
")",
":",
"if",
"not",
"is_absolute_uri",
"(",
"location",
")",
":",
"if",
"location",
"or",
"location",
"is",
"None",
":",
"location",
"=... | Builds an absolute URI from ``location`` and variables
available in this request.
If no ``location`` is specified, the relative URI is built from
:meth:`full_path`. | [
"Builds",
"an",
"absolute",
"URI",
"from",
"location",
"and",
"variables",
"available",
"in",
"this",
"request",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L367-L384 | train |
quantmind/pulsar | pulsar/apps/wsgi/wrappers.py | WsgiRequest.set_response_content_type | def set_response_content_type(self, response_content_types=None):
'''Evaluate the content type for the response to a client ``request``.
The method uses the :attr:`response_content_types` parameter of
accepted content types and the content types accepted by the client
``request`` and figures out the best match.
'''
request_content_types = self.content_types
if request_content_types:
ct = request_content_types.best_match(response_content_types)
if ct and '*' in ct:
ct = None
if not ct and response_content_types:
raise HttpException(status=415, msg=request_content_types)
self.response.content_type = ct | python | def set_response_content_type(self, response_content_types=None):
'''Evaluate the content type for the response to a client ``request``.
The method uses the :attr:`response_content_types` parameter of
accepted content types and the content types accepted by the client
``request`` and figures out the best match.
'''
request_content_types = self.content_types
if request_content_types:
ct = request_content_types.best_match(response_content_types)
if ct and '*' in ct:
ct = None
if not ct and response_content_types:
raise HttpException(status=415, msg=request_content_types)
self.response.content_type = ct | [
"def",
"set_response_content_type",
"(",
"self",
",",
"response_content_types",
"=",
"None",
")",
":",
"request_content_types",
"=",
"self",
".",
"content_types",
"if",
"request_content_types",
":",
"ct",
"=",
"request_content_types",
".",
"best_match",
"(",
"response... | Evaluate the content type for the response to a client ``request``.
The method uses the :attr:`response_content_types` parameter of
accepted content types and the content types accepted by the client
``request`` and figures out the best match. | [
"Evaluate",
"the",
"content",
"type",
"for",
"the",
"response",
"to",
"a",
"client",
"request",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L391-L405 | train |
quantmind/pulsar | pulsar/utils/tools/arity.py | checkarity | def checkarity(func, args, kwargs, discount=0):
'''Check if arguments respect a given function arity and return
an error message if the check did not pass,
otherwise it returns ``None``.
:parameter func: the function.
:parameter args: function arguments.
:parameter kwargs: function key-valued parameters.
:parameter discount: optional integer which discount the number of
positional argument to check. Default ``0``.
'''
spec = inspect.getargspec(func)
self = getattr(func, '__self__', None)
if self and spec.args:
discount += 1
args = list(args)
defaults = list(spec.defaults or ())
len_defaults = len(defaults)
len_args = len(spec.args) - discount
len_args_input = len(args)
minlen = len_args - len_defaults
totlen = len_args_input + len(kwargs)
maxlen = len_args
if spec.varargs or spec.keywords:
maxlen = None
if not minlen:
return
if not spec.defaults and maxlen:
start = '"{0}" takes'.format(func.__name__)
else:
if maxlen and totlen > maxlen:
start = '"{0}" takes at most'.format(func.__name__)
else:
start = '"{0}" takes at least'.format(func.__name__)
if totlen < minlen:
return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen)
elif maxlen and totlen > maxlen:
return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen)
# Length of parameter OK, check names
if len_args_input < len_args:
le = minlen - len_args_input
for arg in spec.args[discount:]:
if args:
args.pop(0)
else:
if le > 0:
if defaults:
defaults.pop(0)
elif arg not in kwargs:
return ('"{0}" has missing "{1}" parameter.'
.format(func.__name__, arg))
kwargs.pop(arg, None)
le -= 1
if kwargs and maxlen:
s = ''
if len(kwargs) > 1:
s = 's'
p = ', '.join('"{0}"'.format(p) for p in kwargs)
return ('"{0}" does not accept {1} parameter{2}.'
.format(func.__name__, p, s))
elif len_args_input > len_args + len_defaults:
n = len_args + len_defaults
start = '"{0}" takes'.format(func.__name__)
return ('{0} {1} positional parameters. {2} given.'
.format(start, n, len_args_input)) | python | def checkarity(func, args, kwargs, discount=0):
'''Check if arguments respect a given function arity and return
an error message if the check did not pass,
otherwise it returns ``None``.
:parameter func: the function.
:parameter args: function arguments.
:parameter kwargs: function key-valued parameters.
:parameter discount: optional integer which discount the number of
positional argument to check. Default ``0``.
'''
spec = inspect.getargspec(func)
self = getattr(func, '__self__', None)
if self and spec.args:
discount += 1
args = list(args)
defaults = list(spec.defaults or ())
len_defaults = len(defaults)
len_args = len(spec.args) - discount
len_args_input = len(args)
minlen = len_args - len_defaults
totlen = len_args_input + len(kwargs)
maxlen = len_args
if spec.varargs or spec.keywords:
maxlen = None
if not minlen:
return
if not spec.defaults and maxlen:
start = '"{0}" takes'.format(func.__name__)
else:
if maxlen and totlen > maxlen:
start = '"{0}" takes at most'.format(func.__name__)
else:
start = '"{0}" takes at least'.format(func.__name__)
if totlen < minlen:
return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen)
elif maxlen and totlen > maxlen:
return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen)
# Length of parameter OK, check names
if len_args_input < len_args:
le = minlen - len_args_input
for arg in spec.args[discount:]:
if args:
args.pop(0)
else:
if le > 0:
if defaults:
defaults.pop(0)
elif arg not in kwargs:
return ('"{0}" has missing "{1}" parameter.'
.format(func.__name__, arg))
kwargs.pop(arg, None)
le -= 1
if kwargs and maxlen:
s = ''
if len(kwargs) > 1:
s = 's'
p = ', '.join('"{0}"'.format(p) for p in kwargs)
return ('"{0}" does not accept {1} parameter{2}.'
.format(func.__name__, p, s))
elif len_args_input > len_args + len_defaults:
n = len_args + len_defaults
start = '"{0}" takes'.format(func.__name__)
return ('{0} {1} positional parameters. {2} given.'
.format(start, n, len_args_input)) | [
"def",
"checkarity",
"(",
"func",
",",
"args",
",",
"kwargs",
",",
"discount",
"=",
"0",
")",
":",
"spec",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"self",
"=",
"getattr",
"(",
"func",
",",
"'__self__'",
",",
"None",
")",
"if",
"self",
... | Check if arguments respect a given function arity and return
an error message if the check did not pass,
otherwise it returns ``None``.
:parameter func: the function.
:parameter args: function arguments.
:parameter kwargs: function key-valued parameters.
:parameter discount: optional integer which discount the number of
positional argument to check. Default ``0``. | [
"Check",
"if",
"arguments",
"respect",
"a",
"given",
"function",
"arity",
"and",
"return",
"an",
"error",
"message",
"if",
"the",
"check",
"did",
"not",
"pass",
"otherwise",
"it",
"returns",
"None",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/arity.py#L6-L73 | train |
quantmind/pulsar | docs/_ext/sphinxtogithub.py | sphinx_extension | def sphinx_extension(app, exception):
"Wrapped up as a Sphinx Extension"
if not app.builder.name in ("html", "dirhtml"):
return
if not app.config.sphinx_to_github:
if app.config.sphinx_to_github_verbose:
print("Sphinx-to-github: Disabled, doing nothing.")
return
if exception:
if app.config.sphinx_to_github_verbose:
print("Sphinx-to-github: Exception raised in main build, doing nothing.")
return
dir_helper = DirHelper(
os.path.isdir,
os.listdir,
os.walk,
shutil.rmtree
)
file_helper = FileSystemHelper(
open,
os.path.join,
shutil.move,
os.path.exists
)
operations_factory = OperationsFactory()
handler_factory = HandlerFactory()
layout_factory = LayoutFactory(
operations_factory,
handler_factory,
file_helper,
dir_helper,
app.config.sphinx_to_github_verbose,
sys.stdout,
force=True
)
layout = layout_factory.create_layout(app.outdir)
layout.process() | python | def sphinx_extension(app, exception):
"Wrapped up as a Sphinx Extension"
if not app.builder.name in ("html", "dirhtml"):
return
if not app.config.sphinx_to_github:
if app.config.sphinx_to_github_verbose:
print("Sphinx-to-github: Disabled, doing nothing.")
return
if exception:
if app.config.sphinx_to_github_verbose:
print("Sphinx-to-github: Exception raised in main build, doing nothing.")
return
dir_helper = DirHelper(
os.path.isdir,
os.listdir,
os.walk,
shutil.rmtree
)
file_helper = FileSystemHelper(
open,
os.path.join,
shutil.move,
os.path.exists
)
operations_factory = OperationsFactory()
handler_factory = HandlerFactory()
layout_factory = LayoutFactory(
operations_factory,
handler_factory,
file_helper,
dir_helper,
app.config.sphinx_to_github_verbose,
sys.stdout,
force=True
)
layout = layout_factory.create_layout(app.outdir)
layout.process() | [
"def",
"sphinx_extension",
"(",
"app",
",",
"exception",
")",
":",
"\"Wrapped up as a Sphinx Extension\"",
"if",
"not",
"app",
".",
"builder",
".",
"name",
"in",
"(",
"\"html\"",
",",
"\"dirhtml\"",
")",
":",
"return",
"if",
"not",
"app",
".",
"config",
".",... | Wrapped up as a Sphinx Extension | [
"Wrapped",
"up",
"as",
"a",
"Sphinx",
"Extension"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L242-L285 | train |
quantmind/pulsar | docs/_ext/sphinxtogithub.py | setup | def setup(app):
"Setup function for Sphinx Extension"
app.add_config_value("sphinx_to_github", True, '')
app.add_config_value("sphinx_to_github_verbose", True, '')
app.connect("build-finished", sphinx_extension) | python | def setup(app):
"Setup function for Sphinx Extension"
app.add_config_value("sphinx_to_github", True, '')
app.add_config_value("sphinx_to_github_verbose", True, '')
app.connect("build-finished", sphinx_extension) | [
"def",
"setup",
"(",
"app",
")",
":",
"\"Setup function for Sphinx Extension\"",
"app",
".",
"add_config_value",
"(",
"\"sphinx_to_github\"",
",",
"True",
",",
"''",
")",
"app",
".",
"add_config_value",
"(",
"\"sphinx_to_github_verbose\"",
",",
"True",
",",
"''",
... | Setup function for Sphinx Extension | [
"Setup",
"function",
"for",
"Sphinx",
"Extension"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L288-L292 | train |
quantmind/pulsar | pulsar/apps/wsgi/route.py | Route.url | def url(self, **urlargs):
'''Build a ``url`` from ``urlargs`` key-value parameters
'''
if self.defaults:
d = self.defaults.copy()
d.update(urlargs)
urlargs = d
url = '/'.join(self._url_generator(urlargs))
if not url:
return '/'
else:
url = '/' + url
return url if self.is_leaf else url + '/' | python | def url(self, **urlargs):
'''Build a ``url`` from ``urlargs`` key-value parameters
'''
if self.defaults:
d = self.defaults.copy()
d.update(urlargs)
urlargs = d
url = '/'.join(self._url_generator(urlargs))
if not url:
return '/'
else:
url = '/' + url
return url if self.is_leaf else url + '/' | [
"def",
"url",
"(",
"self",
",",
"**",
"urlargs",
")",
":",
"if",
"self",
".",
"defaults",
":",
"d",
"=",
"self",
".",
"defaults",
".",
"copy",
"(",
")",
"d",
".",
"update",
"(",
"urlargs",
")",
"urlargs",
"=",
"d",
"url",
"=",
"'/'",
".",
"join... | Build a ``url`` from ``urlargs`` key-value parameters | [
"Build",
"a",
"url",
"from",
"urlargs",
"key",
"-",
"value",
"parameters"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/route.py#L308-L320 | train |
quantmind/pulsar | pulsar/apps/wsgi/route.py | Route.split | def split(self):
'''Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. '''
rule = self.rule
if not self.is_leaf:
rule = rule[:-1]
if not rule:
return Route('/'), None
bits = ('/' + rule).split('/')
last = Route(bits[-1] if self.is_leaf else bits[-1] + '/')
if len(bits) > 1:
return Route('/'.join(bits[:-1]) + '/'), last
else:
return last, None | python | def split(self):
'''Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. '''
rule = self.rule
if not self.is_leaf:
rule = rule[:-1]
if not rule:
return Route('/'), None
bits = ('/' + rule).split('/')
last = Route(bits[-1] if self.is_leaf else bits[-1] + '/')
if len(bits) > 1:
return Route('/'.join(bits[:-1]) + '/'), last
else:
return last, None | [
"def",
"split",
"(",
"self",
")",
":",
"rule",
"=",
"self",
".",
"rule",
"if",
"not",
"self",
".",
"is_leaf",
":",
"rule",
"=",
"rule",
"[",
":",
"-",
"1",
"]",
"if",
"not",
"rule",
":",
"return",
"Route",
"(",
"'/'",
")",
",",
"None",
"bits",
... | Return a two element tuple containing the parent route and
the last url bit as route. If this route is the root route, it returns
the root route and ``None``. | [
"Return",
"a",
"two",
"element",
"tuple",
"containing",
"the",
"parent",
"route",
"and",
"the",
"last",
"url",
"bit",
"as",
"route",
".",
"If",
"this",
"route",
"is",
"the",
"root",
"route",
"it",
"returns",
"the",
"root",
"route",
"and",
"None",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/route.py#L351-L365 | train |
quantmind/pulsar | pulsar/apps/wsgi/routers.py | was_modified_since | def was_modified_since(header=None, mtime=0, size=0):
'''Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item.
'''
header_mtime = modified_since(header, size)
if header_mtime and header_mtime <= mtime:
return False
return True | python | def was_modified_since(header=None, mtime=0, size=0):
'''Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item.
'''
header_mtime = modified_since(header, size)
if header_mtime and header_mtime <= mtime:
return False
return True | [
"def",
"was_modified_since",
"(",
"header",
"=",
"None",
",",
"mtime",
"=",
"0",
",",
"size",
"=",
"0",
")",
":",
"header_mtime",
"=",
"modified_since",
"(",
"header",
",",
"size",
")",
"if",
"header_mtime",
"and",
"header_mtime",
"<=",
"mtime",
":",
"re... | Check if an item was modified since the user last downloaded it
:param header: the value of the ``If-Modified-Since`` header.
If this is ``None``, simply return ``True``
:param mtime: the modification time of the item in question.
:param size: the size of the item. | [
"Check",
"if",
"an",
"item",
"was",
"modified",
"since",
"the",
"user",
"last",
"downloaded",
"it"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L577-L588 | train |
quantmind/pulsar | pulsar/apps/wsgi/routers.py | file_response | def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
"""Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object
"""
file_wrapper = request.get('wsgi.file_wrapper')
if os.path.isfile(filepath):
response = request.response
info = os.stat(filepath)
size = info[stat.ST_SIZE]
modified = info[stat.ST_MTIME]
header = request.get('HTTP_IF_MODIFIED_SINCE')
if not was_modified_since(header, modified, size):
response.status_code = 304
else:
if not content_type:
content_type, encoding = mimetypes.guess_type(filepath)
file = open(filepath, 'rb')
response.headers['content-length'] = str(size)
response.content = file_wrapper(file, block)
response.content_type = content_type
response.encoding = encoding
if status_code:
response.status_code = status_code
else:
response.headers["Last-Modified"] = http_date(modified)
if cache_control:
etag = digest('modified: %d - size: %d' % (modified, size))
cache_control(response.headers, etag=etag)
return response
raise Http404 | python | def file_response(request, filepath, block=None, status_code=None,
content_type=None, encoding=None, cache_control=None):
"""Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object
"""
file_wrapper = request.get('wsgi.file_wrapper')
if os.path.isfile(filepath):
response = request.response
info = os.stat(filepath)
size = info[stat.ST_SIZE]
modified = info[stat.ST_MTIME]
header = request.get('HTTP_IF_MODIFIED_SINCE')
if not was_modified_since(header, modified, size):
response.status_code = 304
else:
if not content_type:
content_type, encoding = mimetypes.guess_type(filepath)
file = open(filepath, 'rb')
response.headers['content-length'] = str(size)
response.content = file_wrapper(file, block)
response.content_type = content_type
response.encoding = encoding
if status_code:
response.status_code = status_code
else:
response.headers["Last-Modified"] = http_date(modified)
if cache_control:
etag = digest('modified: %d - size: %d' % (modified, size))
cache_control(response.headers, etag=etag)
return response
raise Http404 | [
"def",
"file_response",
"(",
"request",
",",
"filepath",
",",
"block",
"=",
"None",
",",
"status_code",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"cache_control",
"=",
"None",
")",
":",
"file_wrapper",
"=",
"request"... | Utility for serving a local file
Typical usage::
from pulsar.apps import wsgi
class MyRouter(wsgi.Router):
def get(self, request):
return wsgi.file_response(request, "<filepath>")
:param request: Wsgi request
:param filepath: full path of file to serve
:param block: Optional block size (default 1MB)
:param status_code: Optional status code (default 200)
:return: a :class:`~.WsgiResponse` object | [
"Utility",
"for",
"serving",
"a",
"local",
"file"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L591-L635 | train |
quantmind/pulsar | pulsar/apps/wsgi/routers.py | Router.has_parent | def has_parent(self, router):
'''Check if ``router`` is ``self`` or a parent or ``self``
'''
parent = self
while parent and parent is not router:
parent = parent._parent
return parent is not None | python | def has_parent(self, router):
'''Check if ``router`` is ``self`` or a parent or ``self``
'''
parent = self
while parent and parent is not router:
parent = parent._parent
return parent is not None | [
"def",
"has_parent",
"(",
"self",
",",
"router",
")",
":",
"parent",
"=",
"self",
"while",
"parent",
"and",
"parent",
"is",
"not",
"router",
":",
"parent",
"=",
"parent",
".",
"_parent",
"return",
"parent",
"is",
"not",
"None"
] | Check if ``router`` is ``self`` or a parent or ``self`` | [
"Check",
"if",
"router",
"is",
"self",
"or",
"a",
"parent",
"or",
"self"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/routers.py#L407-L413 | train |
quantmind/pulsar | pulsar/apps/ds/utils.py | count_bytes | def count_bytes(array):
'''Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm
'''
# this algorithm can be rewritten as
# for i in array:
# count += sum(b=='1' for b in bin(i)[2:])
# but this version is almost 2 times faster
count = 0
for i in array:
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
return count | python | def count_bytes(array):
'''Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm
'''
# this algorithm can be rewritten as
# for i in array:
# count += sum(b=='1' for b in bin(i)[2:])
# but this version is almost 2 times faster
count = 0
for i in array:
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
count += (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24
return count | [
"def",
"count_bytes",
"(",
"array",
")",
":",
"count",
"=",
"0",
"for",
"i",
"in",
"array",
":",
"i",
"=",
"i",
"-",
"(",
"(",
"i",
">>",
"1",
")",
"&",
"0x55555555",
")",
"i",
"=",
"(",
"i",
"&",
"0x33333333",
")",
"+",
"(",
"(",
"i",
">>"... | Count the number of bits in a byte ``array``.
It uses the Hamming weight popcount algorithm | [
"Count",
"the",
"number",
"of",
"bits",
"in",
"a",
"byte",
"array",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ds/utils.py#L172-L186 | train |
quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.write | def write(self, message, opcode=None, encode=True, **kw):
'''Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes.
'''
if encode:
message = self.parser.encode(message, opcode=opcode, **kw)
result = self.connection.write(message)
if opcode == 0x8:
self.connection.close()
return result | python | def write(self, message, opcode=None, encode=True, **kw):
'''Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes.
'''
if encode:
message = self.parser.encode(message, opcode=opcode, **kw)
result = self.connection.write(message)
if opcode == 0x8:
self.connection.close()
return result | [
"def",
"write",
"(",
"self",
",",
"message",
",",
"opcode",
"=",
"None",
",",
"encode",
"=",
"True",
",",
"**",
"kw",
")",
":",
"if",
"encode",
":",
"message",
"=",
"self",
".",
"parser",
".",
"encode",
"(",
"message",
",",
"opcode",
"=",
"opcode",... | Write a new ``message`` into the wire.
It uses the :meth:`~.FrameParser.encode` method of the
websocket :attr:`parser`.
:param message: message to send, must be a string or bytes
:param opcode: optional ``opcode``, if not supplied it is set to 1
if ``message`` is a string, otherwise ``2`` when the message
are bytes. | [
"Write",
"a",
"new",
"message",
"into",
"the",
"wire",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L75-L91 | train |
quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.ping | def ping(self, message=None):
'''Write a ping ``frame``.
'''
return self.write(self.parser.ping(message), encode=False) | python | def ping(self, message=None):
'''Write a ping ``frame``.
'''
return self.write(self.parser.ping(message), encode=False) | [
"def",
"ping",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"ping",
"(",
"message",
")",
",",
"encode",
"=",
"False",
")"
] | Write a ping ``frame``. | [
"Write",
"a",
"ping",
"frame",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L93-L96 | train |
quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.pong | def pong(self, message=None):
'''Write a pong ``frame``.
'''
return self.write(self.parser.pong(message), encode=False) | python | def pong(self, message=None):
'''Write a pong ``frame``.
'''
return self.write(self.parser.pong(message), encode=False) | [
"def",
"pong",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"pong",
"(",
"message",
")",
",",
"encode",
"=",
"False",
")"
] | Write a pong ``frame``. | [
"Write",
"a",
"pong",
"frame",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L98-L101 | train |
quantmind/pulsar | pulsar/apps/ws/websocket.py | WebSocketProtocol.write_close | def write_close(self, code=None):
'''Write a close ``frame`` with ``code``.
'''
return self.write(self.parser.close(code), opcode=0x8, encode=False) | python | def write_close(self, code=None):
'''Write a close ``frame`` with ``code``.
'''
return self.write(self.parser.close(code), opcode=0x8, encode=False) | [
"def",
"write_close",
"(",
"self",
",",
"code",
"=",
"None",
")",
":",
"return",
"self",
".",
"write",
"(",
"self",
".",
"parser",
".",
"close",
"(",
"code",
")",
",",
"opcode",
"=",
"0x8",
",",
"encode",
"=",
"False",
")"
] | Write a close ``frame`` with ``code``. | [
"Write",
"a",
"close",
"frame",
"with",
"code",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/ws/websocket.py#L103-L106 | train |
quantmind/pulsar | pulsar/utils/html.py | escape | def escape(html, force=False):
"""Returns the given HTML with ampersands,
quotes and angle brackets encoded."""
if hasattr(html, '__html__') and not force:
return html
if html in NOTHING:
return ''
else:
return to_string(html).replace('&', '&').replace(
'<', '<').replace('>', '>').replace("'", ''').replace(
'"', '"') | python | def escape(html, force=False):
"""Returns the given HTML with ampersands,
quotes and angle brackets encoded."""
if hasattr(html, '__html__') and not force:
return html
if html in NOTHING:
return ''
else:
return to_string(html).replace('&', '&').replace(
'<', '<').replace('>', '>').replace("'", ''').replace(
'"', '"') | [
"def",
"escape",
"(",
"html",
",",
"force",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"html",
",",
"'__html__'",
")",
"and",
"not",
"force",
":",
"return",
"html",
"if",
"html",
"in",
"NOTHING",
":",
"return",
"''",
"else",
":",
"return",
"to_str... | Returns the given HTML with ampersands,
quotes and angle brackets encoded. | [
"Returns",
"the",
"given",
"HTML",
"with",
"ampersands",
"quotes",
"and",
"angle",
"brackets",
"encoded",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L45-L55 | train |
quantmind/pulsar | pulsar/utils/html.py | capfirst | def capfirst(x):
'''Capitalise the first letter of ``x``.
'''
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | python | def capfirst(x):
'''Capitalise the first letter of ``x``.
'''
x = to_string(x).strip()
if x:
return x[0].upper() + x[1:].lower()
else:
return x | [
"def",
"capfirst",
"(",
"x",
")",
":",
"x",
"=",
"to_string",
"(",
"x",
")",
".",
"strip",
"(",
")",
"if",
"x",
":",
"return",
"x",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"x",
"[",
"1",
":",
"]",
".",
"lower",
"(",
")",
"else",
":",
... | Capitalise the first letter of ``x``. | [
"Capitalise",
"the",
"first",
"letter",
"of",
"x",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L73-L80 | train |
quantmind/pulsar | pulsar/utils/html.py | nicename | def nicename(name):
'''Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space
'''
name = to_string(name)
return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split())) | python | def nicename(name):
'''Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space
'''
name = to_string(name)
return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split())) | [
"def",
"nicename",
"(",
"name",
")",
":",
"name",
"=",
"to_string",
"(",
"name",
")",
"return",
"capfirst",
"(",
"' '",
".",
"join",
"(",
"name",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"spli... | Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space | [
"Make",
"name",
"a",
"more",
"user",
"friendly",
"string",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/html.py#L83-L89 | train |
quantmind/pulsar | pulsar/utils/context.py | TaskContext.set | def set(self, key, value):
"""Set a value in the task context
"""
task = Task.current_task()
try:
context = task._context
except AttributeError:
task._context = context = {}
context[key] = value | python | def set(self, key, value):
"""Set a value in the task context
"""
task = Task.current_task()
try:
context = task._context
except AttributeError:
task._context = context = {}
context[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"task",
"=",
"Task",
".",
"current_task",
"(",
")",
"try",
":",
"context",
"=",
"task",
".",
"_context",
"except",
"AttributeError",
":",
"task",
".",
"_context",
"=",
"context",
"=",
"{"... | Set a value in the task context | [
"Set",
"a",
"value",
"in",
"the",
"task",
"context"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/context.py#L40-L48 | train |
quantmind/pulsar | pulsar/utils/context.py | TaskContext.stack_pop | def stack_pop(self, key):
"""Remove a value in a task context stack
"""
task = Task.current_task()
try:
context = task._context_stack
except AttributeError:
raise KeyError('pop from empty stack') from None
value = context[key]
stack_value = value.pop()
if not value:
context.pop(key)
return stack_value | python | def stack_pop(self, key):
"""Remove a value in a task context stack
"""
task = Task.current_task()
try:
context = task._context_stack
except AttributeError:
raise KeyError('pop from empty stack') from None
value = context[key]
stack_value = value.pop()
if not value:
context.pop(key)
return stack_value | [
"def",
"stack_pop",
"(",
"self",
",",
"key",
")",
":",
"task",
"=",
"Task",
".",
"current_task",
"(",
")",
"try",
":",
"context",
"=",
"task",
".",
"_context_stack",
"except",
"AttributeError",
":",
"raise",
"KeyError",
"(",
"'pop from empty stack'",
")",
... | Remove a value in a task context stack | [
"Remove",
"a",
"value",
"in",
"a",
"task",
"context",
"stack"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/context.py#L85-L97 | train |
quantmind/pulsar | pulsar/utils/importer.py | module_attribute | def module_attribute(dotpath, default=None, safe=False):
'''Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`.
'''
if dotpath:
bits = str(dotpath).split(':')
try:
if len(bits) == 2:
attr = bits[1]
module_name = bits[0]
else:
bits = bits[0].split('.')
if len(bits) > 1:
attr = bits[-1]
module_name = '.'.join(bits[:-1])
else:
raise ValueError('Could not find attribute in %s'
% dotpath)
module = import_module(module_name)
return getattr(module, attr)
except Exception:
if not safe:
raise
return default
else:
if not safe:
raise ImportError
return default | python | def module_attribute(dotpath, default=None, safe=False):
'''Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`.
'''
if dotpath:
bits = str(dotpath).split(':')
try:
if len(bits) == 2:
attr = bits[1]
module_name = bits[0]
else:
bits = bits[0].split('.')
if len(bits) > 1:
attr = bits[-1]
module_name = '.'.join(bits[:-1])
else:
raise ValueError('Could not find attribute in %s'
% dotpath)
module = import_module(module_name)
return getattr(module, attr)
except Exception:
if not safe:
raise
return default
else:
if not safe:
raise ImportError
return default | [
"def",
"module_attribute",
"(",
"dotpath",
",",
"default",
"=",
"None",
",",
"safe",
"=",
"False",
")",
":",
"if",
"dotpath",
":",
"bits",
"=",
"str",
"(",
"dotpath",
")",
".",
"split",
"(",
"':'",
")",
"try",
":",
"if",
"len",
"(",
"bits",
")",
... | Load an attribute from a module.
If the module or the attribute is not available, return the default
argument if *safe* is `True`. | [
"Load",
"an",
"attribute",
"from",
"a",
"module",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/importer.py#L50-L80 | train |
quantmind/pulsar | pulsar/async/actor.py | Actor.start | def start(self, exit=True):
'''Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing.
'''
if self.state == ACTOR_STATES.INITIAL:
self._concurrency.before_start(self)
self._concurrency.add_events(self)
try:
self.cfg.when_ready(self)
except Exception: # pragma nocover
self.logger.exception('Unhandled exception in when_ready hook')
self._started = self._loop.time()
self._exit = exit
self.state = ACTOR_STATES.STARTING
self._run() | python | def start(self, exit=True):
'''Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing.
'''
if self.state == ACTOR_STATES.INITIAL:
self._concurrency.before_start(self)
self._concurrency.add_events(self)
try:
self.cfg.when_ready(self)
except Exception: # pragma nocover
self.logger.exception('Unhandled exception in when_ready hook')
self._started = self._loop.time()
self._exit = exit
self.state = ACTOR_STATES.STARTING
self._run() | [
"def",
"start",
"(",
"self",
",",
"exit",
"=",
"True",
")",
":",
"if",
"self",
".",
"state",
"==",
"ACTOR_STATES",
".",
"INITIAL",
":",
"self",
".",
"_concurrency",
".",
"before_start",
"(",
"self",
")",
"self",
".",
"_concurrency",
".",
"add_events",
... | Called after forking to start the actor's life.
This is where logging is configured, the :attr:`mailbox` is
registered and the :attr:`_loop` is initialised and
started. Calling this method more than once does nothing. | [
"Called",
"after",
"forking",
"to",
"start",
"the",
"actor",
"s",
"life",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/actor.py#L265-L282 | train |
quantmind/pulsar | pulsar/async/actor.py | Actor.send | def send(self, target, action, *args, **kwargs):
'''Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future.
'''
target = self.monitor if target == 'monitor' else target
mailbox = self.mailbox
if isinstance(target, ActorProxyMonitor):
mailbox = target.mailbox
else:
actor = self.get_actor(target)
if isinstance(actor, Actor):
# this occur when sending a message from arbiter to monitors or
# vice-versa.
return command_in_context(action, self, actor, args, kwargs)
elif isinstance(actor, ActorProxyMonitor):
mailbox = actor.mailbox
if hasattr(mailbox, 'send'):
# if not mailbox.closed:
return mailbox.send(action, self, target, args, kwargs)
else:
raise CommandError('Cannot execute "%s" in %s. Unknown actor %s.'
% (action, self, target)) | python | def send(self, target, action, *args, **kwargs):
'''Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future.
'''
target = self.monitor if target == 'monitor' else target
mailbox = self.mailbox
if isinstance(target, ActorProxyMonitor):
mailbox = target.mailbox
else:
actor = self.get_actor(target)
if isinstance(actor, Actor):
# this occur when sending a message from arbiter to monitors or
# vice-versa.
return command_in_context(action, self, actor, args, kwargs)
elif isinstance(actor, ActorProxyMonitor):
mailbox = actor.mailbox
if hasattr(mailbox, 'send'):
# if not mailbox.closed:
return mailbox.send(action, self, target, args, kwargs)
else:
raise CommandError('Cannot execute "%s" in %s. Unknown actor %s.'
% (action, self, target)) | [
"def",
"send",
"(",
"self",
",",
"target",
",",
"action",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"target",
"=",
"self",
".",
"monitor",
"if",
"target",
"==",
"'monitor'",
"else",
"target",
"mailbox",
"=",
"self",
".",
"mailbox",
"if",
"isin... | Send a message to ``target`` to perform ``action`` with given
positional ``args`` and key-valued ``kwargs``.
Returns a coroutine or a Future. | [
"Send",
"a",
"message",
"to",
"target",
"to",
"perform",
"action",
"with",
"given",
"positional",
"args",
"and",
"key",
"-",
"valued",
"kwargs",
".",
"Returns",
"a",
"coroutine",
"or",
"a",
"Future",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/actor.py#L284-L306 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | String.stream | def stream(self, request, counter=0):
'''Returns an iterable over strings.
'''
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | python | def stream(self, request, counter=0):
'''Returns an iterable over strings.
'''
if self._children:
for child in self._children:
if isinstance(child, String):
yield from child.stream(request, counter+1)
else:
yield child | [
"def",
"stream",
"(",
"self",
",",
"request",
",",
"counter",
"=",
"0",
")",
":",
"if",
"self",
".",
"_children",
":",
"for",
"child",
"in",
"self",
".",
"_children",
":",
"if",
"isinstance",
"(",
"child",
",",
"String",
")",
":",
"yield",
"from",
... | Returns an iterable over strings. | [
"Returns",
"an",
"iterable",
"over",
"strings",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L158-L166 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | String.to_bytes | def to_bytes(self, request=None):
'''Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes
'''
data = bytearray()
for chunk in self.stream(request):
if isinstance(chunk, str):
chunk = chunk.encode(self.charset)
data.extend(chunk)
return bytes(data) | python | def to_bytes(self, request=None):
'''Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes
'''
data = bytearray()
for chunk in self.stream(request):
if isinstance(chunk, str):
chunk = chunk.encode(self.charset)
data.extend(chunk)
return bytes(data) | [
"def",
"to_bytes",
"(",
"self",
",",
"request",
"=",
"None",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"for",
"chunk",
"in",
"self",
".",
"stream",
"(",
"request",
")",
":",
"if",
"isinstance",
"(",
"chunk",
",",
"str",
")",
":",
"chunk",
"=",
... | Called to transform the collection of
``streams`` into the content string.
This method can be overwritten by derived classes.
:param streams: a collection (list or dictionary) containing
``strings/bytes`` used to build the final ``string/bytes``.
:return: a string or bytes | [
"Called",
"to",
"transform",
"the",
"collection",
"of",
"streams",
"into",
"the",
"content",
"string",
".",
"This",
"method",
"can",
"be",
"overwritten",
"by",
"derived",
"classes",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L184-L198 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.attr | def attr(self, *args):
'''Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``.'''
attr = self._attr
if not args:
return attr or {}
result, adding = self._attrdata('attr', *args)
if adding:
for key, value in result.items():
if DATARE.match(key):
self.data(key[5:], value)
else:
if attr is None:
self._extra['attr'] = attr = {}
attr[key] = value
result = self
return result | python | def attr(self, *args):
'''Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``.'''
attr = self._attr
if not args:
return attr or {}
result, adding = self._attrdata('attr', *args)
if adding:
for key, value in result.items():
if DATARE.match(key):
self.data(key[5:], value)
else:
if attr is None:
self._extra['attr'] = attr = {}
attr[key] = value
result = self
return result | [
"def",
"attr",
"(",
"self",
",",
"*",
"args",
")",
":",
"attr",
"=",
"self",
".",
"_attr",
"if",
"not",
"args",
":",
"return",
"attr",
"or",
"{",
"}",
"result",
",",
"adding",
"=",
"self",
".",
"_attrdata",
"(",
"'attr'",
",",
"*",
"args",
")",
... | Add the specific attribute to the attribute dictionary
with key ``name`` and value ``value`` and return ``self``. | [
"Add",
"the",
"specific",
"attribute",
"to",
"the",
"attribute",
"dictionary",
"with",
"key",
"name",
"and",
"value",
"value",
"and",
"return",
"self",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L330-L346 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.addClass | def addClass(self, cn):
'''Add the specific class names to the class set and return ``self``.
'''
if cn:
if isinstance(cn, (tuple, list, set, frozenset)):
add = self.addClass
for c in cn:
add(c)
else:
classes = self._classes
if classes is None:
self._extra['classes'] = classes = set()
add = classes.add
for cn in cn.split():
add(slugify(cn))
return self | python | def addClass(self, cn):
'''Add the specific class names to the class set and return ``self``.
'''
if cn:
if isinstance(cn, (tuple, list, set, frozenset)):
add = self.addClass
for c in cn:
add(c)
else:
classes = self._classes
if classes is None:
self._extra['classes'] = classes = set()
add = classes.add
for cn in cn.split():
add(slugify(cn))
return self | [
"def",
"addClass",
"(",
"self",
",",
"cn",
")",
":",
"if",
"cn",
":",
"if",
"isinstance",
"(",
"cn",
",",
"(",
"tuple",
",",
"list",
",",
"set",
",",
"frozenset",
")",
")",
":",
"add",
"=",
"self",
".",
"addClass",
"for",
"c",
"in",
"cn",
":",
... | Add the specific class names to the class set and return ``self``. | [
"Add",
"the",
"specific",
"class",
"names",
"to",
"the",
"class",
"set",
"and",
"return",
"self",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L364-L379 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.flatatt | def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
attr['class'] = cs
if css:
attr['style'] = ' '.join(('%s:%s;' % (k, v) for
k, v in css.items()))
if data:
for k, v in data.items():
attr['data-%s' % k] = dump_data_value(v)
if attr:
return ''.join(attr_iter(attr))
else:
return '' | python | def flatatt(self, **attr):
'''Return a string with attributes to add to the tag'''
cs = ''
attr = self._attr
classes = self._classes
data = self._data
css = self._css
attr = attr.copy() if attr else {}
if classes:
cs = ' '.join(classes)
attr['class'] = cs
if css:
attr['style'] = ' '.join(('%s:%s;' % (k, v) for
k, v in css.items()))
if data:
for k, v in data.items():
attr['data-%s' % k] = dump_data_value(v)
if attr:
return ''.join(attr_iter(attr))
else:
return '' | [
"def",
"flatatt",
"(",
"self",
",",
"**",
"attr",
")",
":",
"cs",
"=",
"''",
"attr",
"=",
"self",
".",
"_attr",
"classes",
"=",
"self",
".",
"_classes",
"data",
"=",
"self",
".",
"_data",
"css",
"=",
"self",
".",
"_css",
"attr",
"=",
"attr",
".",... | Return a string with attributes to add to the tag | [
"Return",
"a",
"string",
"with",
"attributes",
"to",
"add",
"to",
"the",
"tag"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L396-L416 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Html.css | def css(self, mapping=None):
'''Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available.
'''
css = self._css
if mapping is None:
return css
elif isinstance(mapping, Mapping):
if css is None:
self._extra['css'] = css = {}
css.update(mapping)
return self
else:
return css.get(mapping) if css else None | python | def css(self, mapping=None):
'''Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available.
'''
css = self._css
if mapping is None:
return css
elif isinstance(mapping, Mapping):
if css is None:
self._extra['css'] = css = {}
css.update(mapping)
return self
else:
return css.get(mapping) if css else None | [
"def",
"css",
"(",
"self",
",",
"mapping",
"=",
"None",
")",
":",
"css",
"=",
"self",
".",
"_css",
"if",
"mapping",
"is",
"None",
":",
"return",
"css",
"elif",
"isinstance",
"(",
"mapping",
",",
"Mapping",
")",
":",
"if",
"css",
"is",
"None",
":",
... | Update the css dictionary if ``mapping`` is a dictionary, otherwise
return the css value at ``mapping``.
If ``mapping`` is not given, return the whole ``css`` dictionary
if available. | [
"Update",
"the",
"css",
"dictionary",
"if",
"mapping",
"is",
"a",
"dictionary",
"otherwise",
"return",
"the",
"css",
"value",
"at",
"mapping",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L418-L434 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Media.absolute_path | def absolute_path(self, path, minify=True):
'''Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``.
'''
if minify:
ending = '.%s' % self.mediatype
if not path.endswith(ending):
if self.minified:
path = '%s.min' % path
path = '%s%s' % (path, ending)
#
if self.is_relative(path) and self.media_path:
return '%s%s' % (self.media_path, path)
elif self.asset_protocol and path.startswith('//'):
return '%s%s' % (self.asset_protocol, path)
else:
return path | python | def absolute_path(self, path, minify=True):
'''Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``.
'''
if minify:
ending = '.%s' % self.mediatype
if not path.endswith(ending):
if self.minified:
path = '%s.min' % path
path = '%s%s' % (path, ending)
#
if self.is_relative(path) and self.media_path:
return '%s%s' % (self.media_path, path)
elif self.asset_protocol and path.startswith('//'):
return '%s%s' % (self.asset_protocol, path)
else:
return path | [
"def",
"absolute_path",
"(",
"self",
",",
"path",
",",
"minify",
"=",
"True",
")",
":",
"if",
"minify",
":",
"ending",
"=",
"'.%s'",
"%",
"self",
".",
"mediatype",
"if",
"not",
"path",
".",
"endswith",
"(",
"ending",
")",
":",
"if",
"self",
".",
"m... | Return a suitable absolute url for ``path``.
If ``path`` :meth:`is_relative` build a suitable url by prepending
the :attr:`media_path` attribute.
:return: A url path to insert in a HTML ``link`` or ``script``. | [
"Return",
"a",
"suitable",
"absolute",
"url",
"for",
"path",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L531-L551 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Links.insert | def insert(self, index, child, rel=None, type=None, media=None,
condition=None, **kwargs):
'''Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes
'''
if child:
srel = 'stylesheet'
stype = 'text/css'
minify = rel in (None, srel) and type in (None, stype)
path = self.absolute_path(child, minify=minify)
if path.endswith('.css'):
rel = rel or srel
type = type or stype
value = Html('link', href=path, rel=rel, **kwargs)
if type:
value.attr('type', type)
if media not in (None, 'all'):
value.attr('media', media)
if condition:
value = Html(None, '<!--[if %s]>\n' % condition,
value, '<![endif]-->\n')
value = value.to_string()
if value not in self.children:
if index is None:
self.children.append(value)
else:
self.children.insert(index, value) | python | def insert(self, index, child, rel=None, type=None, media=None,
condition=None, **kwargs):
'''Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes
'''
if child:
srel = 'stylesheet'
stype = 'text/css'
minify = rel in (None, srel) and type in (None, stype)
path = self.absolute_path(child, minify=minify)
if path.endswith('.css'):
rel = rel or srel
type = type or stype
value = Html('link', href=path, rel=rel, **kwargs)
if type:
value.attr('type', type)
if media not in (None, 'all'):
value.attr('media', media)
if condition:
value = Html(None, '<!--[if %s]>\n' % condition,
value, '<![endif]-->\n')
value = value.to_string()
if value not in self.children:
if index is None:
self.children.append(value)
else:
self.children.insert(index, value) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"rel",
"=",
"None",
",",
"type",
"=",
"None",
",",
"media",
"=",
"None",
",",
"condition",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"if",
"child",
":",
"srel",
"=",
"'stylesheet'",
... | Append a link to this container.
:param child: a string indicating the location of the linked
document
:param rel: Specifies the relationship between the document
and the linked document. If not given ``stylesheet`` is used.
:param type: Specifies the content type of the linked document.
If not given ``text/css`` is used. It an empty string is given,
it won't be added.
:param media: Specifies on what device the linked document will be
displayed. If not given or ``all``, the media is for all devices.
:param kwargs: additional attributes | [
"Append",
"a",
"link",
"to",
"this",
"container",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L566-L602 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Scripts.insert | def insert(self, index, child, **kwargs):
'''add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended.
'''
if child:
script = self.script(child, **kwargs)
if script not in self.children:
if index is None:
self.children.append(script)
else:
self.children.insert(index, script) | python | def insert(self, index, child, **kwargs):
'''add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended.
'''
if child:
script = self.script(child, **kwargs)
if script not in self.children:
if index is None:
self.children.append(script)
else:
self.children.insert(index, script) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"child",
",",
"**",
"kwargs",
")",
":",
"if",
"child",
":",
"script",
"=",
"self",
".",
"script",
"(",
"child",
",",
"**",
"kwargs",
")",
"if",
"script",
"not",
"in",
"self",
".",
"children",
":",
... | add a new script to the container.
:param child: a ``string`` representing an absolute path to the script
or relative path (does not start with ``http`` or ``/``), in which
case the :attr:`Media.media_path` attribute is prepended. | [
"add",
"a",
"new",
"script",
"to",
"the",
"container",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L622-L635 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Head.get_meta | def get_meta(self, name, meta_key=None):
'''Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property')
'''
meta_key = meta_key or 'name'
for child in self.meta._children:
if isinstance(child, Html) and child.attr(meta_key) == name:
return child.attr('content') | python | def get_meta(self, name, meta_key=None):
'''Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property')
'''
meta_key = meta_key or 'name'
for child in self.meta._children:
if isinstance(child, Html) and child.attr(meta_key) == name:
return child.attr('content') | [
"def",
"get_meta",
"(",
"self",
",",
"name",
",",
"meta_key",
"=",
"None",
")",
":",
"meta_key",
"=",
"meta_key",
"or",
"'name'",
"for",
"child",
"in",
"self",
".",
"meta",
".",
"_children",
":",
"if",
"isinstance",
"(",
"child",
",",
"Html",
")",
"a... | Get the ``content`` attribute of a meta tag ``name``.
For example::
head.get_meta('decription')
returns the ``content`` attribute of the meta tag with attribute
``name`` equal to ``description`` or ``None``.
If a different meta key needs to be matched, it can be specified via
the ``meta_key`` parameter::
head.get_meta('og:title', meta_key='property') | [
"Get",
"the",
"content",
"attribute",
"of",
"a",
"meta",
"tag",
"name",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L779-L796 | train |
quantmind/pulsar | pulsar/apps/wsgi/content.py | Head.replace_meta | def replace_meta(self, name, content=None, meta_key=None):
'''Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed.
'''
children = self.meta._children
if not content: # small optimazation
children = tuple(children)
meta_key = meta_key or 'name'
for child in children:
if child.attr(meta_key) == name:
if content:
child.attr('content', content)
else:
self.meta._children.remove(child)
return
if content:
self.add_meta(**{meta_key: name, 'content': content}) | python | def replace_meta(self, name, content=None, meta_key=None):
'''Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed.
'''
children = self.meta._children
if not content: # small optimazation
children = tuple(children)
meta_key = meta_key or 'name'
for child in children:
if child.attr(meta_key) == name:
if content:
child.attr('content', content)
else:
self.meta._children.remove(child)
return
if content:
self.add_meta(**{meta_key: name, 'content': content}) | [
"def",
"replace_meta",
"(",
"self",
",",
"name",
",",
"content",
"=",
"None",
",",
"meta_key",
"=",
"None",
")",
":",
"children",
"=",
"self",
".",
"meta",
".",
"_children",
"if",
"not",
"content",
":",
"children",
"=",
"tuple",
"(",
"children",
")",
... | Replace the ``content`` attribute of meta tag ``name``
If the meta with ``name`` is not available, it is added, otherwise
its content is replaced. If ``content`` is not given or it is empty
the meta tag with ``name`` is removed. | [
"Replace",
"the",
"content",
"attribute",
"of",
"meta",
"tag",
"name"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/content.py#L798-L817 | train |
quantmind/pulsar | examples/calculator/manage.py | randompaths | def randompaths(request, num_paths=1, size=250, mu=0, sigma=1):
'''Lists of random walks.'''
r = []
for p in range(num_paths):
v = 0
path = [v]
r.append(path)
for t in range(size):
v += normalvariate(mu, sigma)
path.append(v)
return r | python | def randompaths(request, num_paths=1, size=250, mu=0, sigma=1):
'''Lists of random walks.'''
r = []
for p in range(num_paths):
v = 0
path = [v]
r.append(path)
for t in range(size):
v += normalvariate(mu, sigma)
path.append(v)
return r | [
"def",
"randompaths",
"(",
"request",
",",
"num_paths",
"=",
"1",
",",
"size",
"=",
"250",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"r",
"=",
"[",
"]",
"for",
"p",
"in",
"range",
"(",
"num_paths",
")",
":",
"v",
"=",
"0",
"path"... | Lists of random walks. | [
"Lists",
"of",
"random",
"walks",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/calculator/manage.py#L22-L32 | train |
quantmind/pulsar | examples/calculator/manage.py | Site.setup | def setup(self, environ):
'''Called once to setup the list of wsgi middleware.'''
json_handler = Root().putSubHandler('calc', Calculator())
middleware = wsgi.Router('/', post=json_handler,
accept_content_types=JSON_CONTENT_TYPES)
response = [wsgi.GZipMiddleware(200)]
return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
middleware],
response_middleware=response) | python | def setup(self, environ):
'''Called once to setup the list of wsgi middleware.'''
json_handler = Root().putSubHandler('calc', Calculator())
middleware = wsgi.Router('/', post=json_handler,
accept_content_types=JSON_CONTENT_TYPES)
response = [wsgi.GZipMiddleware(200)]
return wsgi.WsgiHandler(middleware=[wsgi.wait_for_body_middleware,
middleware],
response_middleware=response) | [
"def",
"setup",
"(",
"self",
",",
"environ",
")",
":",
"json_handler",
"=",
"Root",
"(",
")",
".",
"putSubHandler",
"(",
"'calc'",
",",
"Calculator",
"(",
")",
")",
"middleware",
"=",
"wsgi",
".",
"Router",
"(",
"'/'",
",",
"post",
"=",
"json_handler",... | Called once to setup the list of wsgi middleware. | [
"Called",
"once",
"to",
"setup",
"the",
"list",
"of",
"wsgi",
"middleware",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/calculator/manage.py#L72-L80 | train |
quantmind/pulsar | examples/chat/manage.py | AsyncResponseMiddleware | def AsyncResponseMiddleware(environ, resp):
'''This is just for testing the asynchronous response middleware
'''
future = create_future()
future._loop.call_soon(future.set_result, resp)
return future | python | def AsyncResponseMiddleware(environ, resp):
'''This is just for testing the asynchronous response middleware
'''
future = create_future()
future._loop.call_soon(future.set_result, resp)
return future | [
"def",
"AsyncResponseMiddleware",
"(",
"environ",
",",
"resp",
")",
":",
"future",
"=",
"create_future",
"(",
")",
"future",
".",
"_loop",
".",
"call_soon",
"(",
"future",
".",
"set_result",
",",
"resp",
")",
"return",
"future"
] | This is just for testing the asynchronous response middleware | [
"This",
"is",
"just",
"for",
"testing",
"the",
"asynchronous",
"response",
"middleware"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L161-L166 | train |
quantmind/pulsar | examples/chat/manage.py | Protocol.encode | def encode(self, message):
'''Encode a message when publishing.'''
if not isinstance(message, dict):
message = {'message': message}
message['time'] = time.time()
return json.dumps(message) | python | def encode(self, message):
'''Encode a message when publishing.'''
if not isinstance(message, dict):
message = {'message': message}
message['time'] = time.time()
return json.dumps(message) | [
"def",
"encode",
"(",
"self",
",",
"message",
")",
":",
"if",
"not",
"isinstance",
"(",
"message",
",",
"dict",
")",
":",
"message",
"=",
"{",
"'message'",
":",
"message",
"}",
"message",
"[",
"'time'",
"]",
"=",
"time",
".",
"time",
"(",
")",
"ret... | Encode a message when publishing. | [
"Encode",
"a",
"message",
"when",
"publishing",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L70-L75 | train |
quantmind/pulsar | examples/chat/manage.py | Chat.on_message | def on_message(self, websocket, msg):
'''When a new message arrives, it publishes to all listening clients.
'''
if msg:
lines = []
for li in msg.split('\n'):
li = li.strip()
if li:
lines.append(li)
msg = ' '.join(lines)
if msg:
return self.pubsub.publish(self.channel, msg) | python | def on_message(self, websocket, msg):
'''When a new message arrives, it publishes to all listening clients.
'''
if msg:
lines = []
for li in msg.split('\n'):
li = li.strip()
if li:
lines.append(li)
msg = ' '.join(lines)
if msg:
return self.pubsub.publish(self.channel, msg) | [
"def",
"on_message",
"(",
"self",
",",
"websocket",
",",
"msg",
")",
":",
"if",
"msg",
":",
"lines",
"=",
"[",
"]",
"for",
"li",
"in",
"msg",
".",
"split",
"(",
"'\\n'",
")",
":",
"li",
"=",
"li",
".",
"strip",
"(",
")",
"if",
"li",
":",
"lin... | When a new message arrives, it publishes to all listening clients. | [
"When",
"a",
"new",
"message",
"arrives",
"it",
"publishes",
"to",
"all",
"listening",
"clients",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L100-L111 | train |
quantmind/pulsar | examples/chat/manage.py | Rpc.rpc_message | async def rpc_message(self, request, message):
'''Publish a message via JSON-RPC'''
await self.pubsub.publish(self.channel, message)
return 'OK' | python | async def rpc_message(self, request, message):
'''Publish a message via JSON-RPC'''
await self.pubsub.publish(self.channel, message)
return 'OK' | [
"async",
"def",
"rpc_message",
"(",
"self",
",",
"request",
",",
"message",
")",
":",
"await",
"self",
".",
"pubsub",
".",
"publish",
"(",
"self",
".",
"channel",
",",
"message",
")",
"return",
"'OK'"
] | Publish a message via JSON-RPC | [
"Publish",
"a",
"message",
"via",
"JSON",
"-",
"RPC"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L122-L125 | train |
quantmind/pulsar | examples/chat/manage.py | WebChat.setup | def setup(self, environ):
'''Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information.
'''
request = wsgi_request(environ)
cfg = request.cache.cfg
loop = request.cache._loop
self.store = create_store(cfg.data_store, loop=loop)
pubsub = self.store.pubsub(protocol=Protocol())
channel = '%s_webchat' % self.name
ensure_future(pubsub.subscribe(channel), loop=loop)
return WsgiHandler([Router('/', get=self.home_page),
WebSocket('/message', Chat(pubsub, channel)),
Router('/rpc', post=Rpc(pubsub, channel),
response_content_types=JSON_CONTENT_TYPES)],
[AsyncResponseMiddleware,
GZipMiddleware(min_length=20)]) | python | def setup(self, environ):
'''Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information.
'''
request = wsgi_request(environ)
cfg = request.cache.cfg
loop = request.cache._loop
self.store = create_store(cfg.data_store, loop=loop)
pubsub = self.store.pubsub(protocol=Protocol())
channel = '%s_webchat' % self.name
ensure_future(pubsub.subscribe(channel), loop=loop)
return WsgiHandler([Router('/', get=self.home_page),
WebSocket('/message', Chat(pubsub, channel)),
Router('/rpc', post=Rpc(pubsub, channel),
response_content_types=JSON_CONTENT_TYPES)],
[AsyncResponseMiddleware,
GZipMiddleware(min_length=20)]) | [
"def",
"setup",
"(",
"self",
",",
"environ",
")",
":",
"request",
"=",
"wsgi_request",
"(",
"environ",
")",
"cfg",
"=",
"request",
".",
"cache",
".",
"cfg",
"loop",
"=",
"request",
".",
"cache",
".",
"_loop",
"self",
".",
"store",
"=",
"create_store",
... | Called once only to setup the WSGI application handler.
Check :ref:`lazy wsgi handler <wsgi-lazy-handler>`
section for further information. | [
"Called",
"once",
"only",
"to",
"setup",
"the",
"WSGI",
"application",
"handler",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/chat/manage.py#L134-L152 | train |
quantmind/pulsar | pulsar/utils/pylib/wsgiresponse.py | WsgiResponse._get_headers | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('content-length', None)
self._content = ()
else:
if not self.is_streamed():
cl = reduce(count_len, self._content, 0)
headers['content-length'] = str(cl)
ct = headers.get('content-type')
# content type encoding available
if self.encoding:
ct = ct or 'text/plain'
if ';' not in ct:
ct = '%s; charset=%s' % (ct, self.encoding)
if ct:
headers['content-type'] = ct
if method == HEAD:
self._content = ()
# Cookies
if (self.status_code < 400 and self._can_store_cookies and
self._cookies):
for c in self.cookies.values():
headers.add('set-cookie', c.OutputString())
return headers.items() | python | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('content-length', None)
self._content = ()
else:
if not self.is_streamed():
cl = reduce(count_len, self._content, 0)
headers['content-length'] = str(cl)
ct = headers.get('content-type')
# content type encoding available
if self.encoding:
ct = ct or 'text/plain'
if ';' not in ct:
ct = '%s; charset=%s' % (ct, self.encoding)
if ct:
headers['content-type'] = ct
if method == HEAD:
self._content = ()
# Cookies
if (self.status_code < 400 and self._can_store_cookies and
self._cookies):
for c in self.cookies.values():
headers.add('set-cookie', c.OutputString())
return headers.items() | [
"def",
"_get_headers",
"(",
"self",
",",
"environ",
")",
":",
"headers",
"=",
"self",
".",
"headers",
"method",
"=",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"if",
"has_empty_content",
"(",
"self",
".",
"status_code",
",",
"method",
")",
"and",
"method",
"... | The list of headers for this response | [
"The",
"list",
"of",
"headers",
"for",
"this",
"response"
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/wsgiresponse.py#L214-L243 | train |
quantmind/pulsar | pulsar/apps/rpc/handlers.py | rpc_method | def rpc_method(func, doc=None, format='json', request_handler=None):
'''A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format.
'''
def _(self, *args, **kwargs):
request = args[0]
if request_handler:
kwargs = request_handler(request, format, kwargs)
try:
return func(*args, **kwargs)
except TypeError:
msg = checkarity(func, args, kwargs)
if msg:
raise InvalidParams('Invalid Parameters. %s' % msg)
else:
raise
_.__doc__ = doc or func.__doc__
_.__name__ = func.__name__
_.FromApi = True
return _ | python | def rpc_method(func, doc=None, format='json', request_handler=None):
'''A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format.
'''
def _(self, *args, **kwargs):
request = args[0]
if request_handler:
kwargs = request_handler(request, format, kwargs)
try:
return func(*args, **kwargs)
except TypeError:
msg = checkarity(func, args, kwargs)
if msg:
raise InvalidParams('Invalid Parameters. %s' % msg)
else:
raise
_.__doc__ = doc or func.__doc__
_.__name__ = func.__name__
_.FromApi = True
return _ | [
"def",
"rpc_method",
"(",
"func",
",",
"doc",
"=",
"None",
",",
"format",
"=",
"'json'",
",",
"request_handler",
"=",
"None",
")",
":",
"def",
"_",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"request",
"=",
"args",
"[",
"0",
"]... | A decorator which exposes a function ``func`` as an rpc function.
:param func: The function to expose.
:param doc: Optional doc string. If not provided the doc string of
``func`` will be used.
:param format: Optional output format.
:param request_handler: function which takes ``request``, ``format``
and ``kwargs`` and return a new ``kwargs`` to be passed to ``func``.
It can be used to add additional parameters based on request and
format. | [
"A",
"decorator",
"which",
"exposes",
"a",
"function",
"func",
"as",
"an",
"rpc",
"function",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/handlers.py#L58-L86 | train |
quantmind/pulsar | pulsar/apps/wsgi/middleware.py | clean_path_middleware | def clean_path_middleware(environ, start_response=None):
'''Clean url from double slashes and redirect if needed.'''
path = environ['PATH_INFO']
if path and '//' in path:
url = re.sub("/+", '/', path)
if not url.startswith('/'):
url = '/%s' % url
qs = environ['QUERY_STRING']
if qs:
url = '%s?%s' % (url, qs)
raise HttpRedirect(url) | python | def clean_path_middleware(environ, start_response=None):
'''Clean url from double slashes and redirect if needed.'''
path = environ['PATH_INFO']
if path and '//' in path:
url = re.sub("/+", '/', path)
if not url.startswith('/'):
url = '/%s' % url
qs = environ['QUERY_STRING']
if qs:
url = '%s?%s' % (url, qs)
raise HttpRedirect(url) | [
"def",
"clean_path_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"path",
"=",
"environ",
"[",
"'PATH_INFO'",
"]",
"if",
"path",
"and",
"'//'",
"in",
"path",
":",
"url",
"=",
"re",
".",
"sub",
"(",
"\"/+\"",
",",
"'/'",
",",... | Clean url from double slashes and redirect if needed. | [
"Clean",
"url",
"from",
"double",
"slashes",
"and",
"redirect",
"if",
"needed",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L61-L71 | train |
quantmind/pulsar | pulsar/apps/wsgi/middleware.py | authorization_middleware | def authorization_middleware(environ, start_response=None):
'''Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function.
'''
key = 'http.authorization'
c = environ.get(key)
if c is None:
code = 'HTTP_AUTHORIZATION'
if code in environ:
environ[key] = parse_authorization_header(environ[code]) | python | def authorization_middleware(environ, start_response=None):
'''Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function.
'''
key = 'http.authorization'
c = environ.get(key)
if c is None:
code = 'HTTP_AUTHORIZATION'
if code in environ:
environ[key] = parse_authorization_header(environ[code]) | [
"def",
"authorization_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"key",
"=",
"'http.authorization'",
"c",
"=",
"environ",
".",
"get",
"(",
"key",
")",
"if",
"c",
"is",
"None",
":",
"code",
"=",
"'HTTP_AUTHORIZATION'",
"if",
... | Parse the ``HTTP_AUTHORIZATION`` key in the ``environ``.
If available, set the ``http.authorization`` key in ``environ`` with
the result obtained from :func:`~.parse_authorization_header` function. | [
"Parse",
"the",
"HTTP_AUTHORIZATION",
"key",
"in",
"the",
"environ",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L74-L85 | train |
quantmind/pulsar | pulsar/apps/wsgi/middleware.py | wait_for_body_middleware | async def wait_for_body_middleware(environ, start_response=None):
'''Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
if environ.get('wsgi.async'):
try:
chunk = await environ['wsgi.input'].read()
except TypeError:
chunk = b''
environ['wsgi.input'] = BytesIO(chunk)
environ.pop('wsgi.async') | python | async def wait_for_body_middleware(environ, start_response=None):
'''Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
if environ.get('wsgi.async'):
try:
chunk = await environ['wsgi.input'].read()
except TypeError:
chunk = b''
environ['wsgi.input'] = BytesIO(chunk)
environ.pop('wsgi.async') | [
"async",
"def",
"wait_for_body_middleware",
"(",
"environ",
",",
"start_response",
"=",
"None",
")",
":",
"if",
"environ",
".",
"get",
"(",
"'wsgi.async'",
")",
":",
"try",
":",
"chunk",
"=",
"await",
"environ",
"[",
"'wsgi.input'",
"]",
".",
"read",
"(",
... | Use this middleware to wait for the full body.
This middleware wait for the full body to be received before letting
other middleware to be processed.
Useful when using synchronous web-frameworks such as :django:`django <>`. | [
"Use",
"this",
"middleware",
"to",
"wait",
"for",
"the",
"full",
"body",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L88-L102 | train |
quantmind/pulsar | pulsar/apps/wsgi/middleware.py | middleware_in_executor | def middleware_in_executor(middleware):
'''Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
@wraps(middleware)
def _(environ, start_response):
loop = get_event_loop()
return loop.run_in_executor(None, middleware, environ, start_response)
return _ | python | def middleware_in_executor(middleware):
'''Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`.
'''
@wraps(middleware)
def _(environ, start_response):
loop = get_event_loop()
return loop.run_in_executor(None, middleware, environ, start_response)
return _ | [
"def",
"middleware_in_executor",
"(",
"middleware",
")",
":",
"@",
"wraps",
"(",
"middleware",
")",
"def",
"_",
"(",
"environ",
",",
"start_response",
")",
":",
"loop",
"=",
"get_event_loop",
"(",
")",
"return",
"loop",
".",
"run_in_executor",
"(",
"None",
... | Use this middleware to run a synchronous middleware in the event loop
executor.
Useful when using synchronous web-frameworks such as :django:`django <>`. | [
"Use",
"this",
"middleware",
"to",
"run",
"a",
"synchronous",
"middleware",
"in",
"the",
"event",
"loop",
"executor",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/middleware.py#L105-L116 | train |
quantmind/pulsar | examples/philosophers/manage.py | DiningPhilosophers.release_forks | async def release_forks(self, philosopher):
'''The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor.
'''
forks = self.forks
self.forks = []
self.started_waiting = 0
for fork in forks:
philosopher.logger.debug('Putting down fork %s', fork)
await philosopher.send('monitor', 'putdown_fork', fork)
await sleep(self.cfg.waiting_period) | python | async def release_forks(self, philosopher):
'''The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor.
'''
forks = self.forks
self.forks = []
self.started_waiting = 0
for fork in forks:
philosopher.logger.debug('Putting down fork %s', fork)
await philosopher.send('monitor', 'putdown_fork', fork)
await sleep(self.cfg.waiting_period) | [
"async",
"def",
"release_forks",
"(",
"self",
",",
"philosopher",
")",
":",
"forks",
"=",
"self",
".",
"forks",
"self",
".",
"forks",
"=",
"[",
"]",
"self",
".",
"started_waiting",
"=",
"0",
"for",
"fork",
"in",
"forks",
":",
"philosopher",
".",
"logge... | The ``philosopher`` has just eaten and is ready to release both
forks.
This method releases them, one by one, by sending the ``put_down``
action to the monitor. | [
"The",
"philosopher",
"has",
"just",
"eaten",
"and",
"is",
"ready",
"to",
"release",
"both",
"forks",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/philosophers/manage.py#L177-L190 | train |
quantmind/pulsar | examples/helloworld/manage.py | hello | def hello(environ, start_response):
'''The WSGI_ application handler which returns an iterable
over the "Hello World!" message.'''
if environ['REQUEST_METHOD'] == 'GET':
data = b'Hello World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
else:
raise MethodNotAllowed | python | def hello(environ, start_response):
'''The WSGI_ application handler which returns an iterable
over the "Hello World!" message.'''
if environ['REQUEST_METHOD'] == 'GET':
data = b'Hello World!\n'
status = '200 OK'
response_headers = [
('Content-type', 'text/plain'),
('Content-Length', str(len(data)))
]
start_response(status, response_headers)
return iter([data])
else:
raise MethodNotAllowed | [
"def",
"hello",
"(",
"environ",
",",
"start_response",
")",
":",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'GET'",
":",
"data",
"=",
"b'Hello World!\\n'",
"status",
"=",
"'200 OK'",
"response_headers",
"=",
"[",
"(",
"'Content-type'",
",",
"'text/p... | The WSGI_ application handler which returns an iterable
over the "Hello World!" message. | [
"The",
"WSGI_",
"application",
"handler",
"which",
"returns",
"an",
"iterable",
"over",
"the",
"Hello",
"World!",
"message",
"."
] | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/examples/helloworld/manage.py#L20-L33 | train |
quantmind/pulsar | pulsar/apps/wsgi/formdata.py | parse_headers | async def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = await fp.readline()
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HttpException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring) | python | async def parse_headers(fp, _class=HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse.
"""
headers = []
while True:
line = await fp.readline()
headers.append(line)
if len(headers) > _MAXHEADERS:
raise HttpException("got more than %d headers" % _MAXHEADERS)
if line in (b'\r\n', b'\n', b''):
break
hstring = b''.join(headers).decode('iso-8859-1')
return email.parser.Parser(_class=_class).parsestr(hstring) | [
"async",
"def",
"parse_headers",
"(",
"fp",
",",
"_class",
"=",
"HTTPMessage",
")",
":",
"headers",
"=",
"[",
"]",
"while",
"True",
":",
"line",
"=",
"await",
"fp",
".",
"readline",
"(",
")",
"headers",
".",
"append",
"(",
"line",
")",
"if",
"len",
... | Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct bytes here, as bytes, for email Parser
to parse. | [
"Parses",
"only",
"RFC2822",
"headers",
"from",
"a",
"file",
"pointer",
".",
"email",
"Parser",
"wants",
"to",
"see",
"strings",
"rather",
"than",
"bytes",
".",
"But",
"a",
"TextIOWrapper",
"around",
"self",
".",
"rfile",
"would",
"buffer",
"too",
"many",
... | fee44e871954aa6ca36d00bb5a3739abfdb89b26 | https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/formdata.py#L372-L389 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.