INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Query the metamodel for a set of instances of some * kind *. Query operators such as where_eq () order_by () or filter functions may be passed as optional arguments. Usage example: >>> m = xtuml. load_metamodel ( db. sql ) >>> inst_set = m. select_many ( My_Class lambda sel: sel. number > 5 ) | def select_many(self, kind, *args):
'''
Query the metamodel for a set of instances of some *kind*. Query
operators such as where_eq(), order_by() or filter functions may be
passed as optional arguments.
Usage example:
>>> m = xtuml.load_metamodel('db.sql... |
Query the metamodel for a single instance of some * kind *. Query operators such as where_eq () order_by () or filter functions may be passed as optional arguments. Usage example: >>> m = xtuml. load_metamodel ( db. sql ) >>> inst = m. select_one ( My_Class lambda sel: sel. name == Test ) | def select_one(self, kind, *args):
'''
Query the metamodel for a single instance of some *kind*. Query
operators such as where_eq(), order_by() or filter functions may be
passed as optional arguments.
Usage example:
>>> m = xtuml.load_metamodel('db.sql')... |
Gets the twitter feed from a given handle.: return: The feed in json format. | async def api_twitter(request):
"""
Gets the twitter feed from a given handle.
:return: The feed in json format.
"""
handle = request.match_info.get('handle', None)
if handle is None:
raise web.HTTPNotFound(body="Not found.")
try:
posts = await fetch_twitter(handle)
exce... |
Sends header payload and topics through a ZeroMQ socket. | def send(socket, header, payload, topics=(), flags=0):
"""Sends header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param header: a list of byte strings which represent a message header.
:param payload: the serialized byte string of a payload.
:param topics: a chain o... |
Receives header payload and topics through a ZeroMQ socket. | def recv(socket, flags=0, capture=(lambda msgs: None)):
"""Receives header, payload, and topics through a ZeroMQ socket.
:param socket: a zmq socket.
:param flags: zmq flags to receive messages.
:param capture: a function to capture received messages.
"""
msgs = eintr_retry_zmq(socket.recv_mul... |
This also finds code you are working on today! | def dead_code():
"""
This also finds code you are working on today!
"""
with safe_cd(SRC):
if IS_TRAVIS:
command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split()
else:
command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
... |
Take a string or list of strings and try to extract all the emails | def parse_emails(values):
'''
Take a string or list of strings and try to extract all the emails
'''
emails = []
if isinstance(values, str):
values = [values]
# now we know we have a list of strings
for value in values:
matches = re_emails.findall(value)
emails.extend... |
Marks a method as RPC. | def rpc(f=None, **kwargs):
"""Marks a method as RPC."""
if f is not None:
if isinstance(f, six.string_types):
if 'name' in kwargs:
raise ValueError('name option duplicated')
kwargs['name'] = f
else:
return rpc(**kwargs)(f)
return functools.... |
Collects methods which are speced as RPC. | def rpc_spec_table(app):
"""Collects methods which are speced as RPC."""
table = {}
for attr, value in inspect.getmembers(app):
rpc_spec = get_rpc_spec(value, default=None)
if rpc_spec is None:
continue
table[rpc_spec.name] = (value, rpc_spec)
return table |
If there is a postcode in the url it validates and normalizes it. | async def normalize_postcode_middleware(request, handler):
"""
If there is a postcode in the url it validates and normalizes it.
"""
postcode: Optional[str] = request.match_info.get('postcode', None)
if postcode is None or postcode == "random":
return await handler(request)
elif not is_... |
Generates a string of object initialization code style. It is useful for custom __repr__ methods:: | def make_repr(obj, params=None, keywords=None, data=None, name=None,
reprs=None):
"""Generates a string of object initialization code style. It is useful
for custom __repr__ methods::
class Example(object):
def __init__(self, param, keyword=None):
self.param = p... |
Calls a function. If an error of the given exception type with interrupted system call ( EINTR ) occurs calls the function again. | def eintr_retry(exc_type, f, *args, **kwargs):
"""Calls a function. If an error of the given exception type with
interrupted system call (EINTR) occurs calls the function again.
"""
while True:
try:
return f(*args, **kwargs)
except exc_type as exc:
if exc.errno !... |
The specialization of: func: eintr_retry by: exc: zmq. ZMQError. | def eintr_retry_zmq(f, *args, **kwargs):
"""The specialization of :func:`eintr_retry` by :exc:`zmq.ZMQError`."""
return eintr_retry(zmq.ZMQError, f, *args, **kwargs) |
Progress to the next identifier and return the current one. | def next(self):
'''
Progress to the next identifier, and return the current one.
'''
val = self._current
self._current = self.readfunc()
return val |
Tries to invoke a method matching the pattern * enter_<type name > * where <type name > is the name of the type of the * node *. | def enter(self, node):
'''
Tries to invoke a method matching the pattern *enter_<type name>*, where
<type name> is the name of the type of the *node*.
'''
name = 'enter_' + node.__class__.__name__
fn = getattr(self, name, self.default_enter)
fn(node) |
Tries to invoke a method matching the pattern * leave_<type name > * where <type name > is the name of the type of the * node *. | def leave(self, node):
'''
Tries to invoke a method matching the pattern *leave_<type name>*, where
<type name> is the name of the type of the *node*.
'''
name = 'leave_' + node.__class__.__name__
fn = getattr(self, name, self.default_leave)
fn(node) |
Invoke the visitors before and after decending down the tree. The walker will also try to invoke a method matching the pattern * accept_<type name > * where <type name > is the name of the accepted * node *. | def accept(self, node, **kwargs):
'''
Invoke the visitors before and after decending down the tree.
The walker will also try to invoke a method matching the pattern
*accept_<type name>*, where <type name> is the name of the accepted
*node*.
'''
if node is None:
... |
The default accept behaviour is to decend into the iterable member * node. children * ( if available ). | def default_accept(self, node, **kwargs):
'''
The default accept behaviour is to decend into the iterable member
*node.children* (if available).
'''
if not hasattr(node, 'children'):
return
for child in node.children:
self.accept(child, **... |
Try to invoke a method matching the pattern * render_<type name > * where <type name > is the name of the rendering * node *. | def render(self, node):
'''
Try to invoke a method matching the pattern *render_<type name>*, where
<type name> is the name of the rendering *node*.
'''
name = 'render_' + type(node).__name__
fn = getattr(self, name, self.default_render)
return fn(node) |
A System Model contains top - level packages | def accept_S_SYS(self, inst):
'''
A System Model contains top-level packages
'''
for child in many(inst).EP_PKG[1401]():
self.accept(child) |
A Component contains packageable elements | def accept_C_C(self, inst):
'''
A Component contains packageable elements
'''
for child in many(inst).PE_PE[8003]():
self.accept(child) |
A Package contains packageable elements | def accept_EP_PKG(self, inst):
'''
A Package contains packageable elements
'''
for child in many(inst).PE_PE[8000]():
self.accept(child) |
A background task that retrieves bike data.: param delta: The amount of time to wait between checks. | async def update_bikes(delta: Optional[timedelta] = None):
"""
A background task that retrieves bike data.
:param delta: The amount of time to wait between checks.
"""
async def update(delta: timedelta):
logger.info("Fetching bike data.")
if await should_update_bikes(delta):
... |
Checks the most recently cached bike and returns true if it either doesn t exist or: return: Whether the cache should be updated. | async def should_update_bikes(delta: timedelta):
"""
Checks the most recently cached bike and returns true if
it either doesn't exist or
:return: Whether the cache should be updated.
todo what if there are no bikes added for a week? ... every request will be triggered.
"""
bike = Bike.get_m... |
Gets stolen bikes from the database within a certain radius ( km ) of a given postcode. Selects a square from the database and then filters out the corners of the square.: param postcode: The postcode to look up.: param kilometers: The radius ( km ) of the search.: return: The bikes in that radius or None if the postco... | async def get_bikes(postcode: PostCodeLike, kilometers=1) -> Optional[List[Bike]]:
"""
Gets stolen bikes from the database within a
certain radius (km) of a given postcode. Selects
a square from the database and then filters out
the corners of the square.
:param postcode: The postcode to look up... |
Gets a random postcode object.. Acts as a middleware between us and the API caching results.: return: The PostCode object else None if the postcode does not exist. | async def get_postcode_random() -> Postcode:
"""
Gets a random postcode object..
Acts as a middleware between us and the API, caching results.
:return: The PostCode object else None if the postcode does not exist.
"""
try:
postcode = await fetch_postcode_random()
except (ApiError, Ci... |
Gets the postcode object for a given postcode string. Acts as a middleware between us and the API caching results.: param postcode_like: The either a string postcode or PostCode object.: return: The PostCode object else None if the postcode does not exist..: raises CachingError: When the postcode is not in cache and th... | async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]:
"""
Gets the postcode object for a given postcode string.
Acts as a middleware between us and the API, caching results.
:param postcode_like: The either a string postcode or PostCode object.
:return: The PostCode object else ... |
Gets a police neighbourhood from the database. Acts as a middleware between us and the API caching results.: param postcode_like: The UK postcode to look up.: return: The Neighbourhood or None if the postcode does not exist.: raises CachingError: If the needed neighbourhood is not in cache and the fetch isn t respondin... | async def get_neighbourhood(postcode_like: PostCodeLike) -> Optional[Neighbourhood]:
"""
Gets a police neighbourhood from the database.
Acts as a middleware between us and the API, caching results.
:param postcode_like: The UK postcode to look up.
:return: The Neighbourhood or None if the postcode d... |
all args -- > _cffi_backend. buffer Returns -- > cdata ( if a SINGLE argument was provided ) LIST of cdata ( if a args was a tuple or list ) | def get_cdata(self, *args):
'''
all args-->_cffi_backend.buffer
Returns-->cdata (if a SINGLE argument was provided)
LIST of cdata (if a args was a tuple or list)
'''
res = tuple([
self.from_buffer(x) for x in args
])
if len(res) == 0... |
all args -- > _cffi_backend. CDataOwn Must be a pointer or an array Returns -- > buffer ( if a SINGLE argument was provided ) LIST of buffer ( if a args was a tuple or list ) | def get_buffer(self, *args):
'''
all args-->_cffi_backend.CDataOwn
Must be a pointer or an array
Returns-->buffer (if a SINGLE argument was provided)
LIST of buffer (if a args was a tuple or list)
'''
res = tuple([
self.buffer(x) for x in arg... |
all args -- > _cffi_backend. CDataOwn Must be a pointer or an array Returns -- > bytes ( if a SINGLE argument was provided ) LIST of bytes ( if a args was a tuple or list ) | def get_bytes(self, *args):
'''
all args-->_cffi_backend.CDataOwn
Must be a pointer or an array
Returns-->bytes (if a SINGLE argument was provided)
LIST of bytes (if a args was a tuple or list)
'''
res = tuple([
bytes(self.buffer(x)) for x in... |
Return the average brightness of the image. | def get_brightness(self):
"""
Return the average brightness of the image.
"""
# Only download the image if it has changed
if not self.connection.has_changed():
return self.image_brightness
image_path = self.connection.download_image()
converted_image... |
Create a file with the specified name and write contents ( a sequence of strings without line terminators ) to it. | def write_file (filename, contents):
"""Create a file with the specified name and write 'contents' (a
sequence of strings without line terminators) to it.
"""
contents = "\n".join(contents)
if sys.version_info >= (3,):
contents = contents.encode("utf-8")
f = open(filename, "wb") #... |
Write data to filename ( if not a dry run ) after announcing it | def write_file(self, what, filename, data):
"""Write `data` to `filename` (if not a dry run) after announcing it
`what` is used in a log message to identify what is being written
to the file.
"""
log.info("writing %s to %s", what, filename)
if sys.version_info >= (3,):
... |
Write the file list in self. filelist ( presumably as filled in by add_defaults () and read_template () ) to the manifest file named by self. manifest. | def write_manifest (self):
"""Write the file list in 'self.filelist' (presumably as filled in
by 'add_defaults()' and 'read_template()') to the manifest file
named by 'self.manifest'.
"""
# The manifest must be UTF-8 encodable. See #303.
if sys.version_info >= (3,):
... |
Indicate whether or not to enter a case suite. | def match(self, *args):
"""
Indicate whether or not to enter a case suite.
usage:
``` py
for case in switch(value):
if case('A'):
pass
elif case(1, 3):
pass # for mulit-match.
else:
pass # for d... |
Given a valid position in the text document try to find the position of the matching bracket. Returns - 1 if unsuccessful. | def _find_match(self, position):
""" Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful.
"""
# Decide what character to search for and what direction to search in.
document = self._text_edit.document()
... |
Convenience method for selecting a character. | def _selection_for_character(self, position):
""" Convenience method for selecting a character.
"""
selection = QtGui.QTextEdit.ExtraSelection()
cursor = self._text_edit.textCursor()
cursor.setPosition(position)
cursor.movePosition(QtGui.QTextCursor.NextCharacter,
... |
Updates the document formatting based on the new cursor position. | def _cursor_position_changed(self):
""" Updates the document formatting based on the new cursor position.
"""
# Clear out the old formatting.
self._text_edit.setExtraSelections([])
# Attempt to match a bracket for the new cursor position.
cursor = self._text_edit.textCur... |
Bottleneck to fix up IronPython string exceptions | def _exc_info(self):
"""Bottleneck to fix up IronPython string exceptions
"""
e = self.exc_info()
if sys.platform == 'cli':
if isinstance(e[0], StringException):
# IronPython throws these StringExceptions, but
# traceback checks type(etype) == ... |
Run tests in suite inside of suite fixtures. | def run(self, result):
"""Run tests in suite inside of suite fixtures.
"""
# proxy the result for myself
log.debug("suite %s (%s) run called, tests: %s", id(self), self, self._tests)
#import pdb
#pdb.set_trace()
if self.resultProxy:
result, orig = self... |
Return the ancestry of the context ( that is all of the packages and modules containing the context ) in order of descent with the outermost ancestor last. This method is a generator. | def ancestry(self, context):
"""Return the ancestry of the context (that is, all of the
packages and modules containing the context), in order of
descent with the outermost ancestor last.
This method is a generator.
"""
log.debug("get ancestry %s", context)
if con... |
The complex case where there are tests that don t all share the same context. Groups tests into suites with common ancestors according to the following ( essentially tail - recursive ) procedure: | def mixedSuites(self, tests):
"""The complex case where there are tests that don't all share
the same context. Groups tests into suites with common ancestors,
according to the following (essentially tail-recursive) procedure:
Starting with the context of the first test, if it is not
... |
Register commandline options. | def options(self, parser, env):
"""Register commandline options.
"""
parser.add_option('--collect-only',
action='store_true',
dest=self.enableOpt,
default=env.get('NOSE_COLLECT_ONLY'),
help="E... |
Create an input hook for running the Qt4 application event loop. | def create_inputhook_qt4(mgr, app=None):
"""Create an input hook for running the Qt4 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, an... |
Return a Mapper instance with the given name. If the name already exist return its instance. | def get(cls, name=__name__):
"""Return a Mapper instance with the given name.
If the name already exist return its instance.
Does not work if a Mapper was created via its constructor.
Using `Mapper.get()`_ is the prefered way.
Args:
name (str, optional): N... |
Decorator for registering a path pattern. | def url(self, pattern, method=None, type_cast=None):
"""Decorator for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits yo... |
Decorator for registering a simple path. | def s_url(self, path, method=None, type_cast=None):
"""Decorator for registering a simple path.
Args:
path (str): Path to be matched.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
... |
Function for registering a path pattern. | def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to d... |
Function for registering a simple path. | def s_add(self, path, function, method=None, type_cast=None):
"""Function for registering a simple path.
Args:
path (str): Path to be matched.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
... |
Calls the first function matching the urls pattern and method. | def call(self, url, method=None, args=None):
"""Calls the first function matching the urls pattern and method.
Args:
url (str): Url for which to call a matching function.
method (str, optional): The method used while registering a
function.
Defaul... |
Reimplemented to the store history. | def execute(self, source=None, hidden=False, interactive=False):
""" Reimplemented to the store history.
"""
if not hidden:
history = self.input_buffer if source is None else source
executed = super(HistoryConsoleWidget, self).execute(
source, hidden, interactive... |
Called when the up key is pressed. Returns whether to continue processing the event. | def _up_pressed(self, shift_modifier):
""" Called when the up key is pressed. Returns whether to continue
processing the event.
"""
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():
# Bail out if we're lo... |
Called when the down key is pressed. Returns whether to continue processing the event. | def _down_pressed(self, shift_modifier):
""" Called when the down key is pressed. Returns whether to continue
processing the event.
"""
end_cursor = self._get_end_cursor()
if self._get_cursor().blockNumber() == end_cursor.blockNumber():
# Bail out if we're locked.... |
If possible set the input buffer to a previous history item. | def history_previous(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a previous history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
... |
If possible set the input buffer to a subsequent history item. | def history_next(self, substring='', as_prefix=True):
""" If possible, set the input buffer to a subsequent history item.
Parameters:
-----------
substring : str, optional
If specified, search for an item with this substring.
as_prefix : bool, optional
If... |
Handles replies for code execution here only session history length | def _handle_execute_reply(self, msg):
""" Handles replies for code execution, here only session history length
"""
msg_id = msg['parent_header']['msg_id']
info = self._request_info['execute'].pop(msg_id,None)
if info and info.kind == 'save_magic' and not self._hidden:
... |
Returns whether history movement is locked. | def _history_locked(self):
""" Returns whether history movement is locked.
"""
return (self.history_lock and
(self._get_edited_history(self._history_index) !=
self.input_buffer) and
(self._get_prompt_cursor().blockNumber() !=
self... |
Retrieves a history item possibly with temporary edits. | def _get_edited_history(self, index):
""" Retrieves a history item, possibly with temporary edits.
"""
if index in self._history_edits:
return self._history_edits[index]
elif index == len(self._history):
return unicode()
return self._history[index] |
Replace the current history with a sequence of history items. | def _set_history(self, history):
""" Replace the current history with a sequence of history items.
"""
self._history = list(history)
self._history_edits = {}
self._history_index = len(self._history) |
If there are edits to the current input buffer store them. | def _store_edits(self):
""" If there are edits to the current input buffer, store them.
"""
current = self.input_buffer
if self._history_index == len(self._history) or \
self._history[self._history_index] != current:
self._history_edits[self._history_index] = ... |
r [ A - Za - z_ ] [ A - Za - z0 - 9_ ] * | def t_NAME(t):
r'[A-Za-z_][A-Za-z0-9_]*'
# to simplify lexing, we match identifiers and keywords as a single thing
# if it's a keyword, we change the type to the name of that keyword
if t.value.upper() in reserved:
t.type = t.value.upper()
t.value = t.value.upper()
return t |
r ( [ ^ \\ ] + | \\ | \\\\ ) * | def t_STRING(t):
r"'([^'\\]+|\\'|\\\\)*'"
t.value = t.value.replace(r'\\', chr(92)).replace(r"\'", r"'")[1:-1]
return t |
postpositions: LIMIT NUMBER postpositions | ORDER BY colspec postpositions | empty | def p_postpositions(p):
'''
postpositions : LIMIT NUMBER postpositions
| ORDER BY colspec postpositions
| empty
'''
if len(p) > 2:
if p[1] == "LIMIT":
postposition = {
"limit": p[2]
}
rest = p[3] if p[3] else... |
colspec: STAR | NAME | function | NAME COMMA colspec | function COMMA colspec | def p_colspec(p):
'''
colspec : STAR
| NAME
| function
| NAME COMMA colspec
| function COMMA colspec
'''
rest = p[3] if len(p) > 3 else []
if p[1] == "*":
p[0] = [{"type": "star"}]
elif isinstance(p[1], dict) and p[1].get("type") == "functi... |
expression: value | expression AND expression | expression OR expression | expression EQUALS expression | NOT expression | LPAREN expression RPAREN | def p_expression(p):
'''
expression : value
| expression AND expression
| expression OR expression
| expression EQUALS expression
| NOT expression
| LPAREN expression RPAREN
'''
if len(p) < 3:
p[0] = p[1]
elif len(p) ... |
Event handler for the button click. | def OnTimeToClose(self, evt):
"""Event handler for the button click."""
print("See ya later!")
sys.stdout.flush()
self.cleanup_consoles(evt)
self.Close()
# Not sure why, but our IPython kernel seems to prevent normal WX
# shutdown, so an explicit exit() call is ne... |
Copy over all files in srcdir to tgtdir w/ native line endings | def upgrade_dir(srcdir, tgtdir):
""" Copy over all files in srcdir to tgtdir w/ native line endings
Creates .upgrade_report in tgtdir that stores md5sums of all files
to notice changed files b/w upgrades.
"""
def pr(s):
print s
junk = ['.svn','ipythonrc*','*.pyc', '*.pyo', '*~', '.hg']... |
Prepare process. Create temp directories download and/ or unpack files. | def prepare_files(self, finder):
"""
Prepare process. Create temp directories, download and/or unpack files.
"""
from pip.index import Link
unnamed = list(self.unnamed_requirements)
reqs = list(self.requirements.values())
while reqs or unnamed:
if unn... |
Clean up files remove builds. | def cleanup_files(self):
"""Clean up files, remove builds."""
logger.debug('Cleaning up...')
with indent_log():
for req in self.reqs_to_cleanup:
req.remove_temporary_source()
if self._pip_has_created_build_dir():
logger.debug('Removing tem... |
Install everything in this set ( after having downloaded and unpacked the packages ) | def install(self, install_options, global_options=(), *args, **kwargs):
"""
Install everything in this set (after having downloaded and unpacked
the packages)
"""
to_install = [r for r in self.requirements.values()[::-1]
if not r.satisfied_by]
# DIS... |
Generates an instance of Record () from a tuple of the form ( index pandas. Series ) with associated parameters kwargs | def load_record(index_series_tuple, kwargs):
'''
Generates an instance of Record() from a tuple of the form (index, pandas.Series)
with associated parameters kwargs
Paremeters
----------
index_series_tuple : tuple
tuple consisting of (index, pandas.Series)
kwargs : dict
adi... |
Generates a list of Record objects given a DataFrame. Each Record instance has a series attribute which is a pandas. Series of the same attributes in the DataFrame. Optional data can be passed in through kwargs which will be included by the name of each object. | def build_collection(df, **kwargs):
'''
Generates a list of Record objects given a DataFrame.
Each Record instance has a series attribute which is a pandas.Series of the same attributes
in the DataFrame.
Optional data can be passed in through kwargs which will be included by the name of each object... |
Converts a collection back into a pandas DataFrame | def collection_to_df(collection):
'''
Converts a collection back into a pandas DataFrame
parameters
----------
collection : list
list of Record objects where each Record represents one row from a dataframe
Returns
-------
df : pandas.DataFrame
DataFrame of length=len(c... |
Runs the full turntable process on a pandas DataFrame | def spin_frame(df, method):
'''
Runs the full turntable process on a pandas DataFrame
parameters
----------
df : pandas.DataFrame
each row represents a record
method : def method(record)
function used to process each row
Returns
-------
df : pandas.DataFrame
... |
Initalizes the given argument structure as properties of the class to be used by name in specific method execution. | def set_attributes(self, kwargs):
'''
Initalizes the given argument structure as properties of the class
to be used by name in specific method execution.
Parameters
----------
kwargs : dictionary
Dictionary of extra attributes,
where keys are attr... |
Update our SUB socket s subscriptions. | def subscribe(self):
"""Update our SUB socket's subscriptions."""
self.stream.setsockopt(zmq.UNSUBSCRIBE, '')
if '' in self.topics:
self.log.debug("Subscribing to: everything")
self.stream.setsockopt(zmq.SUBSCRIBE, '')
else:
for topic in self.topics:
... |
Turn engine. 0. INFO. extra into ( logging. INFO engine. 0. extra ) | def _extract_level(self, topic_str):
"""Turn 'engine.0.INFO.extra' into (logging.INFO, 'engine.0.extra')"""
topics = topic_str.split('.')
for idx,t in enumerate(topics):
level = getattr(logging, t, None)
if level is not None:
break
if leve... |
receive and parse a message then log it. | def log_message(self, raw):
"""receive and parse a message, then log it."""
if len(raw) != 2 or '.' not in raw[0]:
self.log.error("Invalid log message: %s"%raw)
return
else:
topic, msg = raw
# don't newline, since log messages always newline:
... |
Perform an N - way merge operation on sorted lists. | def mergesort(list_of_lists, key=None):
""" Perform an N-way merge operation on sorted lists.
@param list_of_lists: (really iterable of iterable) of sorted elements
(either by naturally or by C{key})
@param key: specify sort key function (like C{sort()}, C{sorted()})
Yields tuples of the form C{(i... |
Return an iterator on an object living on a remote engine. | def remote_iterator(view,name):
"""Return an iterator on an object living on a remote engine.
"""
view.execute('it%s=iter(%s)'%(name,name), block=True)
while True:
try:
result = view.apply_sync(lambda x: x.next(), Reference('it'+name))
# This causes the StopIteration exceptio... |
Convert a notebook to the v2 format. | def convert_to_this_nbformat(nb, orig_version=1):
"""Convert a notebook to the v2 format.
Parameters
----------
nb : NotebookNode
The Python representation of the notebook to convert.
orig_version : int
The original version of the notebook to convert.
"""
if orig_version == ... |
Return this platform s maximum compatible version. | def get_supported_platform():
"""Return this platform's maximum compatible version.
distutils.util.get_platform() normally reports the minimum version
of Mac OS X that would be required to *use* extensions produced by
distutils. But what we want when checking compatibility is to know the
version o... |
Retrieve a PEP 302 importer for the given path item | def get_importer(path_item):
"""Retrieve a PEP 302 "importer" for the given path item
If there is no importer, this returns a wrapper around the builtin import
machinery. The returned importer is only cached if it was created by a
path hook.
"""
try:
importer = sys.path_importer_cache[... |
Thunk to load the real StringIO on demand | def StringIO(*args, **kw):
"""Thunk to load the real StringIO on demand"""
global StringIO
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
return StringIO(*args,**kw) |
Convert a version string to a chronologically - sortable key | def parse_version(s):
"""Convert a version string to a chronologically-sortable key
This is a rough cross between distutils' StrictVersion and LooseVersion;
if you give it versions that would work with StrictVersion, then it behaves
the same; otherwise it acts like a slightly-smarter LooseVersion. It i... |
Return True when distribute wants to override a setuptools dependency. | def _override_setuptools(req):
"""Return True when distribute wants to override a setuptools dependency.
We want to override when the requirement is setuptools and the version is
a variant of 0.6.
"""
if req.project_name == 'setuptools':
if not len(req.specs):
# Just setuptools... |
Add dist to working set associated with entry | def add(self, dist, entry=None, insert=True, replace=False):
"""Add `dist` to working set, associated with `entry`
If `entry` is unspecified, it defaults to the ``.location`` of `dist`.
On exit from this routine, `entry` is added to the end of the working
set's ``.entries`` (if it wasn'... |
List all distributions needed to ( recursively ) meet requirements | def resolve(self, requirements, env=None, installer=None,
replacement=True, replace_conflicting=False):
"""List all distributions needed to (recursively) meet `requirements`
`requirements` must be a sequence of ``Requirement`` objects. `env`,
if supplied, should be an ``Environ... |
Find all activatable distributions in plugin_env | def find_plugins(self,
plugin_env, full_env=None, installer=None, fallback=True
):
"""Find all activatable distributions in `plugin_env`
Example usage::
distributions, errors = working_set.find_plugins(
Environment(plugin_dirlist)
)
map(w... |
Add dist if we can_add () it and it isn t already added | def add(self,dist):
"""Add `dist` if we ``can_add()`` it and it isn't already added"""
if self.can_add(dist) and dist.has_version():
dists = self._distmap.setdefault(dist.key,[])
if dist not in dists:
dists.append(dist)
if dist.key in self._cache:
... |
Return absolute location in cache for archive_name and names | def get_cache_path(self, archive_name, names=()):
"""Return absolute location in cache for `archive_name` and `names`
The parent directory of the resulting path will be created if it does
not already exist. `archive_name` should be the base filename of the
enclosing egg (which may not ... |
Parse a single entry point from string src | def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
""... |
Ensure distribution is importable on path ( default = sys. path ) | def activate(self,path=None):
"""Ensure distribution is importable on `path` (default=sys.path)"""
if path is None: path = sys.path
self.insert_on(path)
if path is sys.path:
fixup_namespace_packages(self.location)
map(declare_namespace, self._get_metadata('namespa... |
Insert self. location in path before its nearest parent directory | def insert_on(self, path, loc = None):
"""Insert self.location in path before its nearest parent directory"""
loc = loc or self.location
if self.project_name == 'setuptools':
try:
version = self.version
except ValueError:
version = ''
... |
Parse and cache metadata | def _parsed_pkg_info(self):
"""Parse and cache metadata"""
try:
return self._pkg_info
except AttributeError:
from email.parser import Parser
self._pkg_info = Parser().parsestr(self.get_metadata(self.PKG_INFO))
return self._pkg_info |
Recompute this distribution s dependencies. | def _compute_dependencies(self):
"""Recompute this distribution's dependencies."""
from _markerlib import compile as compile_marker
dm = self.__dep_map = {None: []}
reqs = []
# Including any condition expressions
for req in self._parsed_pkg_info.get_all('Requires-Dist') ... |
Parse a notebook filename. | def parse_filename(fname):
"""Parse a notebook filename.
This function takes a notebook filename and returns the notebook
format (json/py) and the notebook name. This logic can be
summarized as follows:
* notebook.ipynb -> (notebook.ipynb, notebook, json)
* notebook.json -> (notebook.json, no... |
Description header must preserve newlines ; all others need not | def _collapse_leading_ws(header, txt):
"""
``Description`` header must preserve newlines; all others need not
"""
if header.lower() == 'description': # preserve newlines
return '\n'.join([x[8:] if x.startswith(' ' * 8) else x
for x in txt.strip().splitlines()])
els... |
Return map of named refs ( branches or tags ) to commit hashes. | def get_refs(self, location):
"""Return map of named refs (branches or tags) to commit hashes."""
output = call_subprocess([self.cmd, 'show-ref'],
show_stdout=False, cwd=location)
rv = {}
for line in output.strip().splitlines():
commit, ref = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.