_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | 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")
| 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"})
| 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
| 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:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
| 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:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`"""
self.lock.acquire() | 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.dataforms.Form`"""
self.lock.acquire()
try:
if form and form.type!="cancel":
self.registration_form = form
iq = Iq(stanza_type = | 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`: `pyxmpp.iq.Iq`"""
_unused = stanza
self.lock.acquire()
try:
self.state_change("registered", self.registration_form)
if ('FORM_TYPE' in self.registration_form
and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register'):
if 'username' in self.registration_form:
| 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 its only argument. The object will
provide the requested infromation.
In case of error stanza received or invalid response the `error_callback`
(if provided) will be called with the offending stanza (which can
be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.
The same function will be called on timeout, with the argument set to
`None`.
:Parameters:
| 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
if self.initiator:
mode = "initiator"
else:
mode = "receiver"
self._element_handlers = {}
for handler in self.handlers:
if not isinstance(handler, StreamFeatureHandler):
continue
for _unused, meth in inspect.getmembers(handler, callable):
| 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
| python | {
"resource": ""
} |
q259810 | StreamBase.transport_connected | validation | def transport_connected(self):
"""Called when transport has been connected.
Send the stream head if initiator. | 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:
stream_to = unicode(stream_to)
elif self.peer and self.initiator:
stream_to = unicode(self.peer)
stream_from = None
if self.me and (self.tls_established or not self.initiator):
stream_from = unicode(self.me)
if stream_id:
| 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 = | 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" | python | {
"resource": ""
} |
q259814 | StreamBase._send | validation | def _send(self, stanza):
"""Same as `send` but assume `lock` is acquired."""
| 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:
| 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
| 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 authentication)
:Types:
- `peer`: `JID`
- `restart_stream`: `bool`
"""
| 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:
- `me`: `JID`
- `restart_stream`: `bool`
"""
| 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.
""" | 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:
| 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)
| 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 xmlnode.type!="element":
raise ValueError("XML node is not a jabber:iq:register element (not an element)")
ns=get_node_ns_uri(xmlnode)
if ns and ns!=REGISTER_NS or xmlnode.name!="query":
raise ValueError("XML node is not a jabber:iq:register element")
for element in xml_element_iter(xmlnode.children):
ns = get_node_ns_uri(element)
if ns == DATAFORM_NS and element.name == "x" and not self.form:
self.form = Form(element)
elif ns != REGISTER_NS:
continue
name = element.name
if name == "instructions" and not self.instructions:
| 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 "sumbit", then a form with submitted data.
:Types:
- `form_type`: `unicode`
:return: `self.form` or a form created from the legacy fields
:returntype: `pyxmpp.jabber.dataforms.Form`"""
if self.form:
if self.form.type != form_type:
raise ValueError("Bad form type in the jabber:iq:register element")
return self.form
form = Form(form_type, instructions = self.instructions)
| 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 here), so it could be the form
obtained from `get_form` just with the data entered.
:return: new registration element
:returntype: `Register`"""
result = Register()
if self.form:
result.form = form.make_submit()
return result
if "FORM_TYPE" not in form or "jabber:iq:register" not in form["FORM_TYPE"].values:
| 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 element (not an element)")
ns=get_node_ns_uri(xmlnode)
if ns and ns!=DELAY_NS or xmlnode.name!="x":
raise ValueError("XML node is not a jabber:x:delay element")
stamp=xmlnode.prop("stamp")
if stamp.endswith("Z"):
stamp=stamp[:-1]
if "-" in stamp:
stamp=stamp.split("-",1)[0]
try:
tm = time.strptime(stamp, | 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()
except socket.error, err:
if err.args[0] in BLOCKING_ERRORS: | 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: `Presence`
"""
if self.stanza_type == "error":
raise ValueError("Errors may not be generated in response"
| 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 | 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()
| 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)
>>> # Multiple events supported
>>> @webhook_handler("billing.subscription.suspended", "billing.subscription.cancelled")
>>> def on_subscription_stop(event):
>>> subscription = event.get_resource()
>>> print("Stopping subscription:", subscription)
>>> # Using a wildcard works as well
>>> @webhook_handler("billing.subscription.*")
>>> def on_subscription_update(event):
>>> subscription = event.get_resource()
>>> print("Updated subscription:", subscription)
"""
# First expand all wildcards and verify the event types are valid
event_types_to_register = set()
for event_type in event_types:
# Always convert to lowercase
event_type = event_type.lower()
if "*" in event_type: | 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.
The process is three-fold:
1. Create a WebhookEventTrigger object from a Django request.
2. Verify the WebhookEventTrigger as a Paypal webhook using the SDK.
3. If valid, process it into a WebhookEvent object (and child resource).
"""
headers = fix_django_headers(request.META)
assert headers
try:
body = request.body.decode(request.encoding or "utf-8")
| 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 {}".format(", ".join(repr(k) for k in VALID_MODES))
messages.append(checks.Critical(msg, hint=hint, id="djpaypal.C001"))
for setting in | 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()
self.application_streams[steam_name] = upstream_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:
for steam_queue in self.application_streams.values():
await steam_queue.put(message)
return
| 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 steam, not the same loop as used for upstream messages
in the de-multiplexer.
""" | 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["stream"]
payload = content["payload"]
# block upstream frames
if steam_name not in self.applications_accepting_frames:
raise ValueError("Invalid multiplexed frame received (stream not mapped)")
# send it on to the application that handles this stream
| 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 | 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,
| 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 = | 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
| 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`.
"""
if stream_name in self.applications_accepting_frames:
# remove from set of upsteams steams than can receive new messages
| 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_retries: Maximum number of retries to have, if
set to -1 the decorator will loop forever
:param function success: Function to indicate success criteria
:param int timeout: Timeout interval in seconds, if -1 will retry forever
:raises MaximumRetriesExceeded: Maximum number of retries hit without
reaching the success criteria
:raises TypeError: Both exceptions and success were left None causing the
decorator to have no valid exit criteria.
Example:
Use it to decorate a function!
.. sourcecode:: python
from retry import retry
@retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)
def foo(bar):
if bar < 0:
raise ArithmeticError('testing this')
return bar
foo(5)
# Should return 5
foo(-1)
# Should raise ArithmeticError
| 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 = []
self.__p2chars = []
options = Namespace()
self.__history.append(self.__save_form())
options.ename = self._ename.value
if self._ename_min.value:
options.ename_min = self._ename_min.value
else:
options.ename_min = options.ename
options.pID = self._pID.value
options.mtype = self._mtype.value
options.mmid = options.mtype
options.p1 = self._p1.value
options.p2 = self._p2.value
options.p1char = self._p1char.value
| 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
perform prefix matching rather than exact string matching.
:type prefix: :class:`~__builtins__.bool`
:rtype: :class:`re.RegexObject`
""" | 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 avoid walking and
omit from results
:type ignores: :class:`~__builtins__.list` of :class:`~__builtins__.str`
:returns: Absolute paths to only files.
:rtype: :class:`~__builtins__.list` of :class:`~__builtins__.str`
.. todo:: Try to optimize the ignores matching. Running a regex on every
filename is a fairly significant percentage of the time taken according
to the profiler.
"""
paths, count, ignores = [], 0, ignores or []
# Prepare the ignores list for most efficient use
ignore_re = multiglob_compile(ignores, prefix=False)
for root in roots:
# For safety, only use absolute, real paths.
root = os.path.realpath(root)
# Handle directly-referenced filenames properly
# (And override ignores to "do as I mean, not as I say")
if os.path.isfile(root):
paths.append(root)
continue
for fldr in os.walk(root):
| 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 paths by some attribute.
:type classifier: ``function(list, *args, **kwargs) -> str``
:param fun_desc: Human-readable term for what the classifier operates on.
(Used in log messages)
:type fun_desc: :class:`~__builtins__.str`
:param keep_uniques: If ``False``, discard groups with only one member.
:type keep_uniques: :class:`~__builtins__.bool`
:returns: A dict mapping classifier keys to groups of matches.
:rtype: :class:`~__builtins__.dict`
:attention: Grouping | 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:`fastdupes.groupify`
.. todo:: Rework the calling of :func:`~os.stat` to minimize the number of
calls. It's a fairly significant percentage of the time | 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* of disk seeks. (Best suited for SSDs)
- Vulnerable to file handle exhaustion if used on its own.
:param paths: List of potentially identical files.
:type paths: iterable
:returns: A dict mapping one path to a list of all paths (self included)
with the same contents.
.. todo:: Start examining the ``while handles:`` block to figure out how to
| 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 handle every time
this function is called.
:returns: Two lists of lists:
* Lists to be fed back into this function individually
* Finished groups of duplicate paths. (including unique files as
single-file lists)
:rtype: ``(list, list)``
.. attention:: File handles will be closed when no longer needed
.. todo:: Discard chunk contents immediately once they're no longer needed
"""
chunks = [(path, fh, fh.read(chunk_size)) for path, fh, _ in handles]
more, done = [], []
# While there are combinations not yet tried...
| 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 dupeList: A list duplicate file paths
:param mainPos: Used to display "set X of Y"
:param mainLen: Used to display "set X of Y"
:type dupeList: :class:`~__builtins__.list`
:type mainPos: :class:`~__builtins__.int`
:type mainLen: :class:`~__builtins__.int`
:returns: A list of files to be deleted.
:rtype: :class:`~__builtins__.int`
"""
dupeList = sorted(dupeList)
print
for pos, val in enumerate(dupeList):
print "%d) %s" % (pos + 1, val)
while True:
| 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:`~fastdupes.getPaths`
:param ignores: See :meth:`~fastdupes.getPaths`
:param min_size: See :meth:`~fastdupes.sizeClassifier`
:returns: A list of groups | 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 newline: Whether to start a new line and reset the length count.
:type text: :class:`~__builtins__.str`
:type newline: :class:`~__builtins__.bool`
"""
if not self.isatty:
self.fobj.write('%s\n' % text)
| 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:
Hiroya Takamura, Manabu Okumura.
Text summarization model based on maximum coverage problem and its
variant. (section 3)
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.222.6945
'''
debug_info = {}
sents = list(tools.sent_splitter_ja(text))
words_list = [
# pulp variables should be utf-8 encoded
w.encode('utf-8') for s in sents for w in tools.word_segmenter_ja(s)
]
tf = collections.Counter()
for words in words_list:
for w in words:
tf[w] += 1.0
if sentence_filter is not None:
valid_indices = [i for i, s in enumerate(sents) if sentence_filter(s)]
sents = [sents[i] for i in valid_indices]
words_list = [words_list[i] for i in valid_indices]
sent_ids = [str(i) for i in range(len(sents))] # sentence id
sent_id2len = dict((id_, len(s)) for id_, s in zip(sent_ids, sents)) # c
word_contain = dict() # a
for id_, words in zip(sent_ids, words_list):
word_contain[id_] = collections.defaultdict(lambda: 0)
for w in words:
word_contain[id_][w] = 1
prob = pulp.LpProblem('summarize', pulp.LpMaximize)
# x
sent_vars = pulp.LpVariable.dicts('sents', sent_ids, 0, 1, pulp.LpBinary)
# z
| 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_threshold: if continuous is False and smilarity is greater or
equal to sim_threshold, link the sentences.
alpha: the damping factor of PageRank and DivRank
divrank: if True, apply DivRank instead of PageRank
divrank_alpha: strength of self-link [0.0-1.0]
(it's not the damping factor, see divrank.py)
Returns: tuple
(
{
# sentence index -> score
0: 0.003,
1: 0.002,
...
},
similarity_matrix
)
Reference:
Günes Erkan and Dragomir R. Radev.
LexRank: graph-based lexical centrality as salience in text
summarization. (section 3)
http://www.cs.cmu.edu/afs/cs/project/jair/pub/volume22/erkan04a-html/erkan04a.html
'''
# configure ranker
ranker_params = {'max_iter': 1000}
if use_divrank:
ranker = divrank_scipy
ranker_params['alpha'] = divrank_alpha
ranker_params['d'] = alpha
else:
ranker = networkx.pagerank_scipy
ranker_params['alpha'] = alpha
graph = networkx.DiGraph()
# sentence -> tf
sent_tf_list = []
for sent in sentences:
words | 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
| 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 type "req".'
# ---> 'Unknown directive type'
# e.g. 'Unknown interpreted text role "need".'
| 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:
| 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"^{}\.".format(self.name)).match(decorator.name):
| python | {
"resource": ""
} |
q259861 | NestedClass.is_public | validation | def is_public(self):
"""Return True iff this class should be considered 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 = TokenStream(StringIO(src)) | python | {
"resource": ""
} |
q259863 | Parser.consume | validation | def consume(self, kind):
"""Consume one token and verify it is of the expected 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
| 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()
self.log.debug(
"parsing docstring, token is %r (%s)",
self.current.kind,
| 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,
)
self.log.debug("got_newline: %s", self.stream.got_logical_newline)
if all and self.current.value == "__all__":
self.parse_all()
elif (
self.current.kind == tk.OP
| 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 | 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 self.current.kind not in expected_end_kinds and not (
self.current.kind == tk.OP and self.current.value == ";"
):
if self.current.kind != tk.NAME:
self.stream.move()
continue
self.log.debug(
"parsing import, token is %r (%s)",
self.current.kind,
self.current.value,
)
if is_future_import:
self.log.debug("found future import: %s", self.current.value)
self.future_imports.add(self.current.value)
self.consume(tk.NAME)
self.log.debug(
"parsing import, token | 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,
"Failed to load file: %s" % self.err,
)
yield 0, 0, msg, type(self)
module = []
try:
module = parse(StringIO(self.source), self.filename)
except SyntaxError as err:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_parse,
"Failed to parse file: %s" % err,
)
yield 0, 0, msg, type(self)
module = []
except AllError:
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_all,
"Failed to parse __all__ entry.",
)
yield 0, 0, msg, type(self)
module = []
for definition in module:
if not definition.docstring:
# People can use flake8-docstrings to report missing
# docstrings
continue
try:
# Note we use the PEP257 trim algorithm to remove the
# leading whitespace from each line - this avoids false
# positive severe error "Unexpected section title."
unindented = trim(dequote_docstring(definition.docstring))
# Off load RST validation to reStructuredText-lint
# which calls docutils internally.
# TODO: Should we pass the Python filename as filepath?
rst_errors = list(rst_lint.lint(unindented))
except Exception as err:
# e.g. UnicodeDecodeError
msg = "%s%03i %s" % (
rst_prefix,
rst_fail_lint,
"Failed to lint docstring: %s - %s" % (definition.name, err),
| 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:
| 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.
"""
| 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.
"""
kt = KulerTheme()
kt.author = xml.getElementsByTagName("author")[0]
kt.author = kt.author.childNodes[1].childNodes[0].nodeValue
kt.id = int(self.parse_tag(xml, "id"))
kt.label = self.parse_tag(xml, "label")
mode = self.parse_tag(xml, "mode")
for swatch in xml.getElementsByTagName("swatch"):
c1 = float(self.parse_tag(swatch, "c1"))
c2 = float(self.parse_tag(swatch, "c2"))
c3 = float(self.parse_tag(swatch, "c3"))
c4 = float(self.parse_tag(swatch, "c4"))
if mode == "rgb":
kt.append((c1,c2,c3))
if mode == "cmyk":
| 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"))
| 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'
return False
else:
line = line.rstrip('\r\n')
line = self.shell.precmd(line)
stop = self.shell.onecmd(line)
| 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 | python | {
"resource": ""
} |
q259876 | ShoebotCmd.do_escape_nl | validation | def do_escape_nl(self, arg):
"""
Escape newlines in any responses
| python | {
"resource": ""
} |
q259877 | ShoebotCmd.do_restart | validation | def do_restart(self, line):
"""
Attempt to restart the bot.
"""
self.bot._frame = 0
| python | {
"resource": ""
} |
q259878 | ShoebotCmd.do_play | validation | def do_play(self, line):
"""
Resume playback if bot is paused
"""
if self.pause_speed | 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 = | python | {
"resource": ""
} |
q259880 | ShoebotCmd.do_fullscreen | validation | def do_fullscreen(self, line):
"""
Make the current window fullscreen
| python | {
"resource": ""
} |
q259881 | ShoebotCmd.do_windowed | validation | def do_windowed(self, line):
"""
Un-fullscreen the current window
| python | {
"resource": ""
} |
q259882 | ShoebotCmd.do_help | validation | def do_help(self, arg):
"""
Show help on all commands.
| 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
variable = self.bot._vars[name]
variable.value = variable.sanitize(value.strip(';'))
success, msg = self.bot.canvas.sink.var_changed(name, variable.value)
if success:
| 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:
"""
args = shlex.split(line or "")
if args and 'cookie=' in args[-1]:
cookie_index = line.index('cookie=')
cookie = line[cookie_index + 7:]
| 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.stroke('#3B240B')
_ctx.line(x + (sin(x * 0.1) * 10.0), y + 80, x + sin(_ctx.FRAME * 0.1), y)
# draw flower
_ctx.translate(-20, 0)
_ctx.scale(sc)
# draw petals
_ctx.fill(color)
_ctx.nostroke()
for angle in xrange(0, 360, 45):
| 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()
| 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 = {}
| 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, | 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 character reference
return unichr( int(match.group(2)) )
else:
try: return cp1252[ unichr(int(match.group(3))) ].strip()
except: return unichr( name2codepoint[match.group(3)] )
except:
return placeholder
# Force to Unicode.
if not isinstance(ustring, unicode):
ustring | 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)
| 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.
if isinstance(types, str):
| 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 = is_jython
if debug:
print("setup options: ")
print("with_pgi: ", "yes" if with_pgi else "no")
print("with_examples: ", "yes" if with_examples else "no")
if with_pgi:
reqs.append("pgi")
if debug:
| 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.
| 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 defaults to 0.0 (a right-angle).
:draw: If True draws immediately.
| 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
| 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 | 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: If True draws arrow immediately
:return: Path object representing the arrow.
'''
# Taken from Nodebox
path = self.BezierPath(**kwargs)
if type == self.NORMAL:
head = width * .4
tail = width * .2
path.moveto(x, y)
path.lineto(x - head, y + head)
path.lineto(x - head, y + tail)
path.lineto(x - width, y + tail)
path.lineto(x - width, y - tail)
path.lineto(x - head, y - tail)
path.lineto(x - head, y - head)
path.lineto(x, y)
elif type == self.FORTYFIVE:
head = .3
tail = 1 + head
| 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
x = sin(angle)
y = cos(angle)
if i % 2:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.