_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259800 | LegacyClientStream.auth_timeout | validation | def auth_timeout(self):
"""Handle legacy authentication timeout.
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Timeout while waiting for jabber:iq:auth result")
if self._auth_methods_left:
self._auth_methods_left.pop(0)
fi... | python | {
"resource": ""
} |
q259801 | LegacyClientStream.auth_error | validation | def auth_error(self,stanza):
"""Handle legacy authentication error.
[client only]"""
self.lock.acquire()
try:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
ae=ae[0].name
else:
... | python | {
"resource": ""
} |
q259802 | LegacyClientStream.auth_finish | validation | def auth_finish(self, _unused):
"""Handle success of the legacy authentication."""
self.lock.acquire()
try:
self.__logger.debug("Authenticated")
self.authenticated=True
self.state_change("authorized",self.my_jid)
self._post_auth()
finally:
... | python | {
"resource": ""
} |
q259803 | LegacyClientStream.registration_error | validation | def registration_error(self, stanza):
"""Handle in-band registration error.
[client only]
:Parameters:
- `stanza`: the error stanza received or `None` on timeout.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
self.lock.acquire()
try:
... | python | {
"resource": ""
} |
q259804 | LegacyClientStream.registration_form_received | validation | def registration_form_received(self, stanza):
"""Handle registration form received.
[client only]
Call self.registration_callback with the registration form received
as the argument. Use the value returned by the callback will be a
filled-in form.
:Parameters:
... | python | {
"resource": ""
} |
q259805 | LegacyClientStream.submit_registration_form | validation | def submit_registration_form(self, form):
"""Submit a registration form.
[client only]
:Parameters:
- `form`: the filled-in form. When form is `None` or its type is
"cancel" the registration is to be canceled.
:Types:
- `form`: `pyxmpp.jabber.data... | python | {
"resource": ""
} |
q259806 | LegacyClientStream.registration_success | validation | def registration_success(self, stanza):
"""Handle registration success.
[client only]
Clean up registration stuff, change state to "registered" and initialize
authentication.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyx... | python | {
"resource": ""
} |
q259807 | request_software_version | validation | def request_software_version(stanza_processor, target_jid, callback,
error_callback = None):
"""Request software version information from a remote entity.
When a valid response is received the `callback` will be handled
with a `VersionPayload` instance as... | python | {
"resource": ""
} |
q259808 | StreamBase._setup_stream_element_handlers | validation | def _setup_stream_element_handlers(self):
"""Set up stream element handlers.
Scans the `handlers` list for `StreamFeatureHandler`
instances and updates `_element_handlers` mapping with their
methods decorated with @`stream_element_handler`
"""
# pylint: disable-msg=W0212... | python | {
"resource": ""
} |
q259809 | StreamBase.event | validation | def event(self, event): # pylint: disable-msg=R0201
"""Handle a stream event.
Called when connection state is changed.
Should not be called with self.lock acquired!
"""
event.stream = self
logger.debug(u"Stream event: {0}".format(event))
self.settings["event_que... | python | {
"resource": ""
} |
q259810 | StreamBase.transport_connected | validation | def transport_connected(self):
"""Called when transport has been connected.
Send the stream head if initiator.
"""
with self.lock:
if self.initiator:
if self._output_state is None:
self._initiate() | python | {
"resource": ""
} |
q259811 | StreamBase._send_stream_start | validation | def _send_stream_start(self, stream_id = None, stream_to = None):
"""Send stream start tag."""
if self._output_state in ("open", "closed"):
raise StreamError("Stream start already sent")
if not self.language:
self.language = self.settings["language"]
if stream_to:... | python | {
"resource": ""
} |
q259812 | StreamBase._send_stream_error | validation | def _send_stream_error(self, condition):
"""Same as `send_stream_error`, but expects `lock` acquired.
"""
if self._output_state is "closed":
return
if self._output_state in (None, "restart"):
self._send_stream_start()
element = StreamErrorElement(condition... | python | {
"resource": ""
} |
q259813 | StreamBase._restart_stream | validation | def _restart_stream(self):
"""Restart the stream as needed after SASL and StartTLS negotiation."""
self._input_state = "restart"
self._output_state = "restart"
self.features = None
self.transport.restart()
if self.initiator:
self._send_stream_start(self.stream... | python | {
"resource": ""
} |
q259814 | StreamBase._send | validation | def _send(self, stanza):
"""Same as `send` but assume `lock` is acquired."""
self.fix_out_stanza(stanza)
element = stanza.as_xml()
self._write_element(element) | python | {
"resource": ""
} |
q259815 | StreamBase.uplink_receive | validation | def uplink_receive(self, stanza):
"""Handle stanza received from the stream."""
with self.lock:
if self.stanza_route:
self.stanza_route.uplink_receive(stanza)
else:
logger.debug(u"Stanza dropped (no route): {0!r}".format(stanza)) | python | {
"resource": ""
} |
q259816 | StreamBase.process_stream_error | validation | def process_stream_error(self, error):
"""Process stream error element received.
:Parameters:
- `error`: error received
:Types:
- `error`: `StreamErrorElement`
"""
# pylint: disable-msg=R0201
logger.debug("Unhandled stream error: condition: {0} {... | python | {
"resource": ""
} |
q259817 | StreamBase.set_peer_authenticated | validation | def set_peer_authenticated(self, peer, restart_stream = False):
"""Mark the other side of the stream authenticated as `peer`
:Parameters:
- `peer`: local JID just authenticated
- `restart_stream`: `True` when stream should be restarted (needed
after SASL authentica... | python | {
"resource": ""
} |
q259818 | StreamBase.set_authenticated | validation | def set_authenticated(self, me, restart_stream = False):
"""Mark stream authenticated as `me`.
:Parameters:
- `me`: local JID just authenticated
- `restart_stream`: `True` when stream should be restarted (needed
after SASL authentication)
:Types:
... | python | {
"resource": ""
} |
q259819 | StreamBase.auth_properties | validation | def auth_properties(self):
"""Authentication properties of the stream.
Derived from the transport with 'local-jid' and 'service-type' added.
"""
props = dict(self.settings["extra_auth_properties"])
if self.transport:
props.update(self.transport.auth_properties)
... | python | {
"resource": ""
} |
q259820 | ClientStream.fix_out_stanza | validation | def fix_out_stanza(self, stanza):
"""Fix outgoing stanza.
On a client clear the sender JID. On a server set the sender
address to the own JID if the address is not set yet."""
StreamBase.fix_out_stanza(self, stanza)
if self.initiator:
if stanza.from_jid:
... | python | {
"resource": ""
} |
q259821 | ClientStream.fix_in_stanza | validation | def fix_in_stanza(self, stanza):
"""Fix an incoming stanza.
Ona server replace the sender address with authorized client JID."""
StreamBase.fix_in_stanza(self, stanza)
if not self.initiator:
if stanza.from_jid != self.peer:
stanza.set_from(self.peer) | python | {
"resource": ""
} |
q259822 | Register.__from_xml | validation | def __from_xml(self, xmlnode):
"""Initialize `Register` from an XML node.
:Parameters:
- `xmlnode`: the jabber:x:register XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`"""
self.__logger.debug("Converting jabber:iq:register element from XML")
if xmln... | python | {
"resource": ""
} |
q259823 | Register.get_form | validation | def get_form(self, form_type = "form"):
"""Return Data Form for the `Register` object.
Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.
:Parameters:
- `form_type`: If "form", then a form to fill-in should be
returned. If "su... | python | {
"resource": ""
} |
q259824 | Register.submit_form | validation | def submit_form(self, form):
"""Make `Register` object for submitting the registration form.
Convert form data to legacy fields if `self.form` is `None`.
:Parameters:
- `form`: The form to submit. Its type doesn't have to be "submit"
(a "submit" form will be created h... | python | {
"resource": ""
} |
q259825 | Delay.from_xml | validation | def from_xml(self,xmlnode):
"""Initialize Delay object from an XML node.
:Parameters:
- `xmlnode`: the jabber:x:delay XML element.
:Types:
- `xmlnode`: `libxml2.xmlNode`"""
if xmlnode.type!="element":
raise ValueError("XML node is not a jabber:x:delay... | python | {
"resource": ""
} |
q259826 | TCPListener.handle_read | validation | def handle_read(self):
"""
Accept any incoming connections.
"""
with self._lock:
logger.debug("handle_read()")
if self._socket is None:
return
while True:
try:
sock, address = self._socket.accept()
... | python | {
"resource": ""
} |
q259827 | Presence.make_error_response | validation | def make_error_response(self, cond):
"""Create error response for the any non-error presence stanza.
:Parameters:
- `cond`: error condition name, as defined in XMPP specification.
:Types:
- `cond`: `unicode`
:return: new presence stanza.
:returntype: `Pr... | python | {
"resource": ""
} |
q259828 | BillingPlan.activate | validation | def activate(self):
"""
Activate an plan in a CREATED state.
"""
obj = self.find_paypal_object()
if obj.state == enums.BillingPlanState.CREATED:
success = obj.activate()
if not success:
raise PaypalApiError("Failed to activate plan: %r" % (obj.error))
# Resync the updated data to the database
se... | python | {
"resource": ""
} |
q259829 | PreparedBillingAgreement.execute | validation | def execute(self):
"""
Execute the PreparedBillingAgreement by creating and executing a
matching BillingAgreement.
"""
# Save the execution time first.
# If execute() fails, executed_at will be set, with no executed_agreement set.
self.executed_at = now()
self.save()
with transaction.atomic():
ret... | python | {
"resource": ""
} |
q259830 | webhook_handler | validation | def webhook_handler(*event_types):
"""
Decorator that registers a function as a webhook handler.
Usage examples:
>>> # Hook a single event
>>> @webhook_handler("payment.sale.completed")
>>> def on_payment_received(event):
>>> payment = event.get_resource()
>>> print("Received payment:", payment)
>>>... | python | {
"resource": ""
} |
q259831 | WebhookEventTrigger.from_request | validation | def from_request(cls, request, webhook_id=PAYPAL_WEBHOOK_ID):
"""
Create, validate and process a WebhookEventTrigger given a Django
request object.
The webhook_id parameter expects the ID of the Webhook that was
triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required
for Webhook verification.
... | python | {
"resource": ""
} |
q259832 | check_paypal_api_key | validation | def check_paypal_api_key(app_configs=None, **kwargs):
"""Check that the Paypal API keys are configured correctly"""
messages = []
mode = getattr(djpaypal_settings, "PAYPAL_MODE", None)
if mode not in VALID_MODES:
msg = "Invalid PAYPAL_MODE specified: {}.".format(repr(mode))
hint = "PAYPAL_MODE must be one of {... | python | {
"resource": ""
} |
q259833 | AsyncJsonWebsocketDemultiplexer._create_upstream_applications | validation | async def _create_upstream_applications(self):
"""
Create the upstream applications.
"""
loop = asyncio.get_event_loop()
for steam_name, ApplicationsCls in self.applications.items():
application = ApplicationsCls(self.scope)
upstream_queue = asyncio.Queue(... | python | {
"resource": ""
} |
q259834 | AsyncJsonWebsocketDemultiplexer.send_upstream | validation | async def send_upstream(self, message, stream_name=None):
"""
Send a message upstream to a de-multiplexed application.
If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream
steams.
"""
if stream_name is None:
... | python | {
"resource": ""
} |
q259835 | AsyncJsonWebsocketDemultiplexer.dispatch_downstream | validation | async def dispatch_downstream(self, message, steam_name):
"""
Handle a downstream message coming from an upstream steam.
if there is not handling method set for this method type it will propagate the message further downstream.
This is called as part of the co-routine of an upstream st... | python | {
"resource": ""
} |
q259836 | AsyncJsonWebsocketDemultiplexer.receive_json | validation | async def receive_json(self, content, **kwargs):
"""
Rout the message down the correct stream.
"""
# Check the frame looks good
if isinstance(content, dict) and "stream" in content and "payload" in content:
# Match it to a channel
steam_name = content["str... | python | {
"resource": ""
} |
q259837 | AsyncJsonWebsocketDemultiplexer.websocket_disconnect | validation | async def websocket_disconnect(self, message):
"""
Handle the disconnect message.
This is propagated to all upstream applications.
"""
# set this flag so as to ensure we don't send a downstream `websocket.close` message due to all
# child applications closing.
se... | python | {
"resource": ""
} |
q259838 | AsyncJsonWebsocketDemultiplexer.disconnect | validation | async def disconnect(self, code):
"""
default is to wait for the child applications to close.
"""
try:
await asyncio.wait(
self.application_futures.values(),
return_when=asyncio.ALL_COMPLETED,
timeout=self.application_close_time... | python | {
"resource": ""
} |
q259839 | AsyncJsonWebsocketDemultiplexer.websocket_send | validation | async def websocket_send(self, message, stream_name):
"""
Capture downstream websocket.send messages from the upstream applications.
"""
text = message.get("text")
# todo what to do on binary!
json = await self.decode_json(text)
data = {
"stream": stre... | python | {
"resource": ""
} |
q259840 | AsyncJsonWebsocketDemultiplexer.websocket_accept | validation | async def websocket_accept(self, message, stream_name):
"""
Intercept downstream `websocket.accept` message and thus allow this upsteam application to accept websocket
frames.
"""
is_first = not self.applications_accepting_frames
self.applications_accepting_frames.add(str... | python | {
"resource": ""
} |
q259841 | AsyncJsonWebsocketDemultiplexer.websocket_close | validation | async def websocket_close(self, message, stream_name):
"""
Handle downstream `websocket.close` message.
Will disconnect this upstream application from receiving any new frames.
If there are not more upstream applications accepting messages it will then call `close`.
"""
... | python | {
"resource": ""
} |
q259842 | FxCurve.cast | validation | def cast(cls, fx_spot, domestic_curve=None, foreign_curve=None):
"""
creator method to build FxCurve
:param float fx_spot: fx spot rate
:param RateCurve domestic_curve: domestic discount curve
:param RateCurve foreign_curve: foreign discount curve
:return:
"""
... | python | {
"resource": ""
} |
q259843 | retry | validation | def retry(
exceptions=(Exception,), interval=0, max_retries=10, success=None,
timeout=-1):
"""Decorator to retry a function 'max_retries' amount of times
:param tuple exceptions: Exceptions to be caught for retries
:param int interval: Interval between retries in seconds
:param int max_... | python | {
"resource": ""
} |
q259844 | MeleeUploader.__button_action | validation | def __button_action(self, data=None):
"""Button action event"""
if any(not x for x in (self._ename.value, self._p1.value, self._p2.value, self._file.value)):
print("Missing one of the required fields (event name, player names, file name)")
return
self.__p1chars = []
... | python | {
"resource": ""
} |
q259845 | multiglob_compile | validation | def multiglob_compile(globs, prefix=False):
"""Generate a single "A or B or C" regex from a list of shell globs.
:param globs: Patterns to be processed by :mod:`fnmatch`.
:type globs: iterable of :class:`~__builtins__.str`
:param prefix: If ``True``, then :meth:`~re.RegexObject.match` will
per... | python | {
"resource": ""
} |
q259846 | getPaths | validation | def getPaths(roots, ignores=None):
"""
Recursively walk a set of paths and return a listing of contained files.
:param roots: Relative or absolute paths to files or folders.
:type roots: :class:`~__builtins__.list` of :class:`~__builtins__.str`
:param ignores: A list of :py:mod:`fnmatch` globs to ... | python | {
"resource": ""
} |
q259847 | groupBy | validation | def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False,
*args, **kwargs):
"""Subdivide groups of paths according to a function.
:param groups_in: Grouped sets of paths.
:type groups_in: :class:`~__builtins__.dict` of iterables
:param classifier: Function to group a list of pat... | python | {
"resource": ""
} |
q259848 | groupify | validation | def groupify(function):
"""Decorator to convert a function which takes a single value and returns
a key into one which takes a list of values and returns a dict of key-group
mappings.
:param function: A function which takes a value and returns a hash key.
:type function: ``function(value) -> key``
... | python | {
"resource": ""
} |
q259849 | sizeClassifier | validation | def sizeClassifier(path, min_size=DEFAULTS['min_size']):
"""Sort a file into a group based on on-disk size.
:param paths: See :func:`fastdupes.groupify`
:param min_size: Files smaller than this size (in bytes) will be ignored.
:type min_size: :class:`__builtins__.int`
:returns: See :func:`fastdup... | python | {
"resource": ""
} |
q259850 | groupByContent | validation | def groupByContent(paths):
"""Byte-for-byte comparison on an arbitrary number of files in parallel.
This operates by opening all files in parallel and comparing
chunk-by-chunk. This has the following implications:
- Reads the same total amount of data as hash comparison.
- Performs a *lot*... | python | {
"resource": ""
} |
q259851 | compareChunks | validation | def compareChunks(handles, chunk_size=CHUNK_SIZE):
"""Group a list of file handles based on equality of the next chunk of
data read from them.
:param handles: A list of open handles for file-like objects with
otentially-identical contents.
:param chunk_size: The amount of data to read from each... | python | {
"resource": ""
} |
q259852 | pruneUI | validation | def pruneUI(dupeList, mainPos=1, mainLen=1):
"""Display a list of files and prompt for ones to be kept.
The user may enter ``all`` or one or more numbers separated by spaces
and/or commas.
.. note:: It is impossible to accidentally choose to keep none of the
displayed files.
:param dupeLi... | python | {
"resource": ""
} |
q259853 | find_dupes | validation | def find_dupes(paths, exact=False, ignores=None, min_size=0):
"""High-level code to walk a set of paths and find duplicate groups.
:param exact: Whether to compare file contents by hash or by reading
chunks in parallel.
:type exact: :class:`~__builtins__.bool`
:param paths: See :meth... | python | {
"resource": ""
} |
q259854 | OverWriter.write | validation | def write(self, text, newline=False):
"""Use ``\\r`` to overdraw the current line with the given text.
This function transparently handles tracking how much overdrawing is
necessary to erase the previous line when used consistently.
:param text: The text to be outputted
:param ... | python | {
"resource": ""
} |
q259855 | summarize | validation | def summarize(text, char_limit, sentence_filter=None, debug=False):
'''
select sentences in terms of maximum coverage problem
Args:
text: text to be summarized (unicode string)
char_limit: summary length (the number of characters)
Returns:
list of extracted sentences
Reference:
... | python | {
"resource": ""
} |
q259856 | lexrank | validation | def lexrank(sentences, continuous=False, sim_threshold=0.1, alpha=0.9,
use_divrank=False, divrank_alpha=0.25):
'''
compute centrality score of sentences.
Args:
sentences: [u'こんにちは.', u'私の名前は飯沼です.', ... ]
continuous: if True, apply continuous LexRank. (see reference)
sim_thresh... | python | {
"resource": ""
} |
q259857 | Summarizer.get_summarizer | validation | def get_summarizer(self, name):
'''
import summarizers on-demand
'''
if name in self.summarizers:
pass
elif name == 'lexrank':
from . import lexrank
self.summarizers[name] = lexrank.summarize
elif name == 'mcp':
from . impor... | python | {
"resource": ""
} |
q259858 | code_mapping | validation | def code_mapping(level, msg, default=99):
"""Return an error code between 0 and 99."""
try:
return code_mappings_by_level[level][msg]
except KeyError:
pass
# Following assumes any variable messages take the format
# of 'Fixed text "variable text".' only:
# e.g. 'Unknown directive... | python | {
"resource": ""
} |
q259859 | Function.is_public | validation | def is_public(self):
"""Return True iff this function should be considered public."""
if self.all is not None:
return self.name in self.all
else:
return not self.name.startswith("_") | python | {
"resource": ""
} |
q259860 | Method.is_public | validation | def is_public(self):
"""Return True iff this method should be considered public."""
# Check if we are a setter/deleter method, and mark as private if so.
for decorator in self.decorators:
# Given 'foo', match 'foo.bar' but not 'foobar' or 'sfoo'
if re.compile(r"^{}\.".for... | python | {
"resource": ""
} |
q259861 | NestedClass.is_public | validation | def is_public(self):
"""Return True iff this class should be considered public."""
return (
not self.name.startswith("_")
and self.parent.is_class
and self.parent.is_public
) | python | {
"resource": ""
} |
q259862 | Parser.parse | validation | def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = "".join(self.source)
# This may raise a SyntaxError:
compile(src, filename, "exec")
self.stream = Toke... | python | {
"resource": ""
} |
q259863 | Parser.consume | validation | def consume(self, kind):
"""Consume one token and verify it is of the expected kind."""
next_token = self.stream.move()
assert next_token.kind == kind | python | {
"resource": ""
} |
q259864 | Parser.leapfrog | validation | def leapfrog(self, kind, value=None):
"""Skip tokens in the stream until a certain token kind is reached.
If `value` is specified, tokens whose values are different will also
be skipped.
"""
while self.current is not None:
if self.current.kind == kind and (
... | python | {
"resource": ""
} |
q259865 | Parser.parse_docstring | validation | def parse_docstring(self):
"""Parse a single docstring and return its value."""
self.log.debug(
"parsing docstring, token is %r (%s)", self.current.kind, self.current.value
)
while self.current.kind in (tk.COMMENT, tk.NEWLINE, tk.NL):
self.stream.move()
... | python | {
"resource": ""
} |
q259866 | Parser.parse_definitions | validation | def parse_definitions(self, class_, all=False):
"""Parse multiple definitions and yield them."""
while self.current is not None:
self.log.debug(
"parsing definition list, current token is %r (%s)",
self.current.kind,
self.current.value,
... | python | {
"resource": ""
} |
q259867 | Parser.parse_from_import_statement | validation | def parse_from_import_statement(self):
"""Parse a 'from x import y' statement.
The purpose is to find __future__ statements.
"""
self.log.debug("parsing from/import statement.")
is_future_import = self._parse_from_import_source()
self._parse_from_import_names(is_future_i... | python | {
"resource": ""
} |
q259868 | Parser._parse_from_import_names | validation | def _parse_from_import_names(self, is_future_import):
"""Parse the 'y' part in a 'from x import y' statement."""
if self.current.value == "(":
self.consume(tk.OP)
expected_end_kinds = (tk.OP,)
else:
expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER)
while... | python | {
"resource": ""
} |
q259869 | reStructuredTextChecker.run | validation | def run(self):
"""Use docutils to check docstrings are valid RST."""
# Is there any reason not to call load_source here?
if self.err is not None:
assert self.source is None
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_load,
"F... | python | {
"resource": ""
} |
q259870 | reStructuredTextChecker.load_source | validation | def load_source(self):
"""Load the source for the specified file."""
if self.filename in self.STDIN_NAMES:
self.filename = "stdin"
if sys.version_info[0] < 3:
self.source = sys.stdin.read()
else:
self.source = TextIOWrapper(sys.stdin.bu... | python | {
"resource": ""
} |
q259871 | KulerTheme._darkest | validation | def _darkest(self):
""" Returns the darkest swatch.
Knowing the contract between a light and a dark swatch
can help us decide how to display readable typography.
"""
rgb, n = (1.0, 1.0, 1.0), 3.0
for r,g,b in self:
if r+g+b ... | python | {
"resource": ""
} |
q259872 | Kuler.parse_theme | validation | def parse_theme(self, xml):
""" Parses a theme from XML returned by Kuler.
Gets the theme's id, label and swatches.
All of the swatches are converted to RGB.
If we have a full description for a theme id in cache,
parse that to get tags associated with the theme.... | python | {
"resource": ""
} |
q259873 | SocketServer.listener | validation | def listener(self, sock, *args):
'''Asynchronous connection listener. Starts a handler for each connection.'''
conn, addr = sock.accept()
f = conn.makefile(conn)
self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)
print(_("Connected"))
GObject.io_add_watch(... | python | {
"resource": ""
} |
q259874 | SocketServer.handler | validation | def handler(self, conn, *args):
'''
Asynchronous connection handler. Processes each line from the socket.
'''
# lines from cmd.Cmd
self.shell.stdout.write(self.shell.prompt)
line = self.shell.stdin.readline()
if not len(line):
line = 'EOF'
... | python | {
"resource": ""
} |
q259875 | trusted_cmd | validation | def trusted_cmd(f):
"""
Trusted commands cannot be run remotely
:param f:
:return:
"""
def run_cmd(self, line):
if self.trusted:
f(self, line)
else:
print("Sorry cannot do %s here." % f.__name__[3:])
global trusted_cmds
trusted_cmds.add(f.__name_... | python | {
"resource": ""
} |
q259876 | ShoebotCmd.do_escape_nl | validation | def do_escape_nl(self, arg):
"""
Escape newlines in any responses
"""
if arg.lower() == 'off':
self.escape_nl = False
else:
self.escape_nl = True | python | {
"resource": ""
} |
q259877 | ShoebotCmd.do_restart | validation | def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
self.bot._namespace.clear()
self.bot._namespace.update(self.bot._initial_namespace) | python | {
"resource": ""
} |
q259878 | ShoebotCmd.do_play | validation | def do_play(self, line):
"""
Resume playback if bot is paused
"""
if self.pause_speed is None:
self.bot._speed = self.pause_speed
self.pause_speed = None
self.print_response("Play") | python | {
"resource": ""
} |
q259879 | ShoebotCmd.do_vars | validation | def do_vars(self, line):
"""
List bot variables and values
"""
if self.bot._vars:
max_name_len = max([len(name) for name in self.bot._vars])
for i, (name, v) in enumerate(self.bot._vars.items()):
keep = i < len(self.bot._vars) - 1
s... | python | {
"resource": ""
} |
q259880 | ShoebotCmd.do_fullscreen | validation | def do_fullscreen(self, line):
"""
Make the current window fullscreen
"""
self.bot.canvas.sink.trigger_fullscreen_action(True)
print(self.response_prompt, file=self.stdout) | python | {
"resource": ""
} |
q259881 | ShoebotCmd.do_windowed | validation | def do_windowed(self, line):
"""
Un-fullscreen the current window
"""
self.bot.canvas.sink.trigger_fullscreen_action(False)
print(self.response_prompt, file=self.stdout) | python | {
"resource": ""
} |
q259882 | ShoebotCmd.do_help | validation | def do_help(self, arg):
"""
Show help on all commands.
"""
print(self.response_prompt, file=self.stdout)
return cmd.Cmd.do_help(self, arg) | python | {
"resource": ""
} |
q259883 | ShoebotCmd.do_set | validation | def do_set(self, line):
"""
Set a variable.
"""
try:
name, value = [part.strip() for part in line.split('=')]
if name not in self.bot._vars:
self.print_response('No such variable %s enter vars to see available vars' % name)
return
... | python | {
"resource": ""
} |
q259884 | ShoebotCmd.precmd | validation | def precmd(self, line):
"""
Allow commands to have a last parameter of 'cookie=somevalue'
TODO somevalue will be prepended onto any output lines so
that editors can distinguish output from certain kinds
of events they have sent.
:param line:
:return:
"""... | python | {
"resource": ""
} |
q259885 | drawdaisy | validation | def drawdaisy(x, y, color='#fefefe'):
"""
Draw a daisy at x, y
"""
# save location, size etc
_ctx.push()
# save fill and stroke
_fill =_ctx.fill()
_stroke = _ctx.stroke()
sc = (1.0 / _ctx.HEIGHT) * float(y * 0.5) * 4.0
# draw stalk
_ctx.strokewidth(sc * 2.0)
_ctx.s... | python | {
"resource": ""
} |
q259886 | ShoebotWindowHelper.get_source | validation | def get_source(self, doc):
"""
Grab contents of 'doc' and return it
:param doc: The active document
:return:
"""
start_iter = doc.get_start_iter()
end_iter = doc.get_end_iter()
source = doc.get_text(start_iter, end_iter, False)
return source | python | {
"resource": ""
} |
q259887 | KantGenerator.loadGrammar | validation | def loadGrammar(self, grammar, searchpaths=None):
"""load context-free grammar"""
self.grammar = self._load(grammar, searchpaths=searchpaths)
self.refs = {}
for ref in self.grammar.getElementsByTagName("ref"):
self.refs[ref.attributes["id"].value] = ref | python | {
"resource": ""
} |
q259888 | KantGenerator.refresh | validation | def refresh(self):
"""reset output buffer, re-parse entire source file, and return output
Since parsing involves a good deal of randomness, this is an
easy way to get new output without having to reload a grammar file
each time.
"""
self.reset()
s... | python | {
"resource": ""
} |
q259889 | KantGenerator.randomChildElement | validation | def randomChildElement(self, node):
"""choose a random child element of a node
This is a utility method used by do_xref and do_choice.
"""
choices = [e for e in node.childNodes
if e.nodeType == e.ELEMENT_NODE]
chosen = random.choice(choices)
... | python | {
"resource": ""
} |
q259890 | replace_entities | validation | def replace_entities(ustring, placeholder=" "):
"""Replaces HTML special characters by readable characters.
As taken from Leif K-Brooks algorithm on:
http://groups-beta.google.com/group/comp.lang.python
"""
def _repl_func(match):
try:
if match.group(1): # Numeric characte... | python | {
"resource": ""
} |
q259891 | not_found | validation | def not_found(url, wait=10):
""" Returns True when the url generates a "404 Not Found" error.
"""
try: connection = open(url, wait)
except HTTP404NotFound:
return True
except:
return False
return False | python | {
"resource": ""
} |
q259892 | is_type | validation | def is_type(url, types=[], wait=10):
""" Determine the MIME-type of the document behind the url.
MIME is more reliable than simply checking the document extension.
Returns True when the MIME-type starts with anything in the list of types.
"""
# Types can also be a single string for convenience.
... | python | {
"resource": ""
} |
q259893 | requirements | validation | def requirements(debug=True, with_examples=True, with_pgi=None):
"""
Build requirements based on flags
:param with_pgi: Use 'pgi' instead of 'gi' - False on CPython, True elsewhere
:param with_examples:
:return:
"""
reqs = list(BASE_REQUIREMENTS)
if with_pgi is None:
with_pgi = ... | python | {
"resource": ""
} |
q259894 | NodeBot.image | validation | def image(self, path, x, y, width=None, height=None, alpha=1.0, data=None, draw=True, **kwargs):
'''Draws a image form path, in x,y and resize it to width, height dimensions.
'''
return self.Image(path, x, y, width, height, alpha, data, **kwargs) | python | {
"resource": ""
} |
q259895 | NodeBot.rect | validation | def rect(self, x, y, width, height, roundness=0.0, draw=True, **kwargs):
'''
Draw a rectangle from x, y of width, height.
:param startx: top left x-coordinate
:param starty: top left y-coordinate
:param width: height Size of rectangle.
:roundness: Corner roundness defa... | python | {
"resource": ""
} |
q259896 | NodeBot.rectmode | validation | def rectmode(self, mode=None):
'''
Set the current rectmode.
:param mode: CORNER, CENTER, CORNERS
:return: rectmode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.rectmode = mode
return self.rectmode
... | python | {
"resource": ""
} |
q259897 | NodeBot.ellipsemode | validation | def ellipsemode(self, mode=None):
'''
Set the current ellipse drawing mode.
:param mode: CORNER, CENTER, CORNERS
:return: ellipsemode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.ellipsemode = mode
return... | python | {
"resource": ""
} |
q259898 | NodeBot.arrow | validation | def arrow(self, x, y, width, type=NORMAL, draw=True, **kwargs):
'''Draw an arrow.
Arrows can be two types: NORMAL or FORTYFIVE.
:param x: top left x-coordinate
:param y: top left y-coordinate
:param width: width of arrow
:param type: NORMAL or FORTYFIVE
:draw: ... | python | {
"resource": ""
} |
q259899 | NodeBot.star | validation | def star(self, startx, starty, points=20, outer=100, inner=50, draw=True, **kwargs):
'''Draws a star.
'''
# Taken from Nodebox.
self.beginpath(**kwargs)
self.moveto(startx, starty + outer)
for i in range(1, int(2 * points)):
angle = i * pi / points
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.