Search is not available for this dataset
text stringlengths 75 104k |
|---|
def divide(cls, divisions, problem_data):
"""divide
:type problem_data: dict
"""
tspp = TSPProblem(**problem_data)
def routes_for_subgroup(cs):
for city in cs:
if city == tspp.start_city:
continue
cities = tspp.cit... |
def _defaults(self, keys=None):
"""create an empty record"""
d = {}
keys = self._keys if keys is None else keys
for key in keys:
d[key] = None
return d |
def _check_table(self):
"""Ensure that an incorrect table doesn't exist
If a bad (old) table does exist, return False
"""
cursor = self._db.execute("PRAGMA table_info(%s)"%self.table)
lines = cursor.fetchall()
if not lines:
# table does not exist
... |
def _init_db(self):
"""Connect to the database and get new session number."""
# register adapters
sqlite3.register_adapter(dict, _adapt_dict)
sqlite3.register_converter('dict', _convert_dict)
sqlite3.register_adapter(list, _adapt_bufs)
sqlite3.register_converter('bufs', _... |
def _list_to_dict(self, line, keys=None):
"""Inverse of dict_to_list"""
keys = self._keys if keys is None else keys
d = self._defaults(keys)
for key,value in zip(keys, line):
d[key] = value
return d |
def _render_expression(self, check):
"""Turn a mongodb-style search dict into an SQL query."""
expressions = []
args = []
skeys = set(check.keys())
skeys.difference_update(set(self._keys))
skeys.difference_update(set(['buffers', 'result_buffers']))
if skeys:
... |
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
d = self._defaults()
d.update(rec)
d['msg_id'] = msg_id
line = self._dict_to_list(d)
tups = '(%s)'%(','.join(['?']*len(line)))
self._db.execute("INSERT INTO %s VALUES %s"%(self.table, tups)... |
def get_record(self, msg_id):
"""Get a specific Task Record, by msg_id."""
cursor = self._db.execute("""SELECT * FROM %s WHERE msg_id==?"""%self.table, (msg_id,))
line = cursor.fetchone()
if line is None:
raise KeyError("No such msg: %r"%msg_id)
return self._list_to_d... |
def update_record(self, msg_id, rec):
"""Update the data in an existing record."""
query = "UPDATE %s SET "%self.table
sets = []
keys = sorted(rec.keys())
values = []
for key in keys:
sets.append('%s = ?'%key)
values.append(rec[key])
query ... |
def drop_matching_records(self, check):
"""Remove a record from the DB."""
expr,args = self._render_expression(check)
query = "DELETE FROM %s WHERE %s"%(self.table, expr)
self._db.execute(query,args) |
def find_records(self, check, keys=None):
"""Find records matching a query dict, optionally extracting subset of keys.
Returns list of matching records.
Parameters
----------
check: dict
mongodb-style query argument
keys: list of strs [optional]
... |
def get_history(self):
"""get all msg_ids, ordered by time submitted."""
query = """SELECT msg_id FROM %s ORDER by submitted ASC"""%self.table
cursor = self._db.execute(query)
# will be a list of length 1 tuples
return [ tup[0] for tup in cursor.fetchall()] |
def warn(msg,level=2,exit_val=1):
"""Standard warning printer. Gives formatting consistency.
Output is sent to io.stderr (sys.stderr by default).
Options:
-level(2): allows finer control:
0 -> Do nothing, dummy function.
1 -> Print message.
2 -> Print 'WARNING:' + message. (Default ... |
def parse(self, config_file=None, specs=None, default_file=None):
"""Read a config_file, check the validity with a JSON Schema as specs
and get default values from default_file if asked.
All parameters are optionnal.
If there is no config_file defined, read the venv base
dir an... |
def table(rows):
'''
Output a simple table with several columns.
'''
output = '<table>'
for row in rows:
output += '<tr>'
for column in row:
output += '<td>{s}</td>'.format(s=column)
output += '</tr>'
output += '</table>'
return output |
def link(url, text='', classes='', target='', get="", **kwargs):
'''
Output a link tag.
'''
if not (url.startswith('http') or url.startswith('/')):
# Handle additional reverse args.
urlargs = {}
for arg, val in kwargs.items():
if arg[:4] == "url_":
u... |
def jsfile(url):
'''
Output a script tag to a js file.
'''
if not url.startswith('http://') and not url[:1] == '/':
#add media_url for relative paths
url = settings.STATIC_URL + url
return '<script type="text/javascript" src="{src}"></script>'.format(
src=url) |
def cssfile(url):
'''
Output a link tag to a css stylesheet.
'''
if not url.startswith('http://') and not url[:1] == '/':
#add media_url for relative paths
url = settings.STATIC_URL + url
return '<link href="{src}" rel="stylesheet">'.format(src=url) |
def img(url, alt='', classes='', style=''):
'''
Image tag helper.
'''
if not url.startswith('http://') and not url[:1] == '/':
#add media_url for relative paths
url = settings.STATIC_URL + url
attr = {
'class': classes,
'alt': alt,
'style': style,
's... |
def sub(value, arg):
"""Subtract the arg from the value."""
try:
return valid_numeric(value) - valid_numeric(arg)
except (ValueError, TypeError):
try:
return value - arg
except Exception:
return '' |
def mul(value, arg):
"""Multiply the arg with the value."""
try:
return valid_numeric(value) * valid_numeric(arg)
except (ValueError, TypeError):
try:
return value * arg
except Exception:
return '' |
def div(value, arg):
"""Divide the arg by the value."""
try:
return valid_numeric(value) / valid_numeric(arg)
except (ValueError, TypeError):
try:
return value / arg
except Exception:
return '' |
def mod(value, arg):
"""Return the modulo value."""
try:
return valid_numeric(value) % valid_numeric(arg)
except (ValueError, TypeError):
try:
return value % arg
except Exception:
return '' |
def model_verbose(obj, capitalize=True):
"""
Return the verbose name of a model.
The obj argument can be either a Model instance, or a ModelForm instance.
This allows to retrieve the verbose name of the model of a ModelForm
easily, without adding extra context vars.
"""
if isinstance(obj, M... |
def extendManager(mixinClass):
'''
Use as a class decorator to add extra methods to your model manager.
Example usage:
class Article(django.db.models.Model):
published = models.DateTimeField()
...
@extendManager
class objects(object):
def getPublished(self):
return self.filter(published__lte... |
def run():
"""Main method where all logic is defined"""
config_option_help="'show' - displays configured options, 'set [section] [name] [value]' - sets config under a section,'set [name] [value]' - sets configuration globally"
parser = OptionParser()
parser.add_option("-a", "--add", action="... |
def split_user_input(line, pattern=None):
"""Split user input into initial whitespace, escape character, function part
and the rest.
"""
# We need to ensure that the rest of this routine deals only with unicode
encoding = get_stream_enc(sys.stdin, 'utf-8')
line = py3compat.cast_unicode(line, enc... |
def current(context, urlName, className = 'active', **kwargs):
'''
Return a class name (string) if the current URL matches the route name specified in ``className``.
If any URL keyword arguments are provided, they must be matched as well.
:param urlName: The route name that the current URL should match. Example: '... |
def pathMatches(path, urlName, **kwargs):
'''
:param path: str
:param urlName: str
:returns: bool.
'''
resolved = urlresolvers.resolve(path)
# Different URL name => the current URL cannot match.
resolvedName = '{r.namespace}:{r.url_name}'.format(r = resolved) if resolved.namespace else resolved.url_name
if ur... |
def options(self, parser, env):
"""
Register command-line options.
"""
parser.add_option("--processes", action="store",
default=env.get('NOSE_PROCESSES', 0),
dest="multiprocess_workers",
metavar="NUM",
... |
def configure(self, options, config):
"""
Configure plugin.
"""
try:
self.status.pop('active')
except KeyError:
pass
if not hasattr(options, 'multiprocess_workers'):
self.enabled = False
return
# don't start inside o... |
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)
if self.resultProxy:
result, orig = self.resultProxy(result, self),... |
def add_builtin(self, key, value):
"""Add a builtin and save the original."""
bdict = __builtin__.__dict__
orig = bdict.get(key, BuiltinUndefined)
if value is HideBuiltin:
if orig is not BuiltinUndefined: #same as 'key in bdict'
self._orig_builtins[key] = orig... |
def remove_builtin(self, key, orig):
"""Remove an added builtin and re-set the original."""
if orig is BuiltinUndefined:
del __builtin__.__dict__[key]
else:
__builtin__.__dict__[key] = orig |
def activate(self):
"""Store ipython references in the __builtin__ namespace."""
add_builtin = self.add_builtin
for name, func in self.auto_builtins.iteritems():
add_builtin(name, func) |
def deactivate(self):
"""Remove any builtins which might have been added by add_builtins, or
restore overwritten ones to their previous values."""
remove_builtin = self.remove_builtin
for key, val in self._orig_builtins.iteritems():
remove_builtin(key, val)
self._orig... |
def _find_url_name(self, index_url, url_name, req):
"""
Finds the true URL name of a package, when the given name isn't quite
correct.
This is usually used to implement case-insensitivity.
"""
if not index_url.url.endswith('/'):
# Vaguely part of the PyPI API.... |
def _link_package_versions(self, link, search_name):
"""
Return an iterable of triples (pkg_resources_version_key,
link, python_version) that can be extracted from the given
link.
Meant to be overridden by subclasses, not called by clients.
"""
platform = get_pla... |
def explicit_rel_links(self, rels=('homepage', 'download')):
"""Yields all links with the given relations"""
rels = set(rels)
for anchor in self.parsed.findall(".//a"):
if anchor.get("rel") and anchor.get("href"):
found_rels = set(anchor.get("rel").split())
... |
def send_multi_alt_email(
subject, # single line with no line-breaks
text_content,
to_emails,
html_content=None,
from_email=DEFAULT_FROM_EMAIL,
fail_silently=True
):
"""
Send a message to one more email address(s).
With text content as primary and html content as alternative.
... |
def send_html_email(
subject, # single line with no line-breaks
html_content,
to_emails,
from_email=DEFAULT_FROM_EMAIL,
fail_silently=True
):
"""
Send a message to one more email address(s).
With html content as primary.
"""
messenger = EmailMessage(subject, html_content, f... |
def trim_form(parser, token):
"""
Returns a form that only contains a subset of the original fields (opcode: incude/exclude fields)
Exampel:
<fieldset>
<legend>Business Info</legend>
<ul>
{% trim_form orig_form fields biz_name,biz_city,biz_... |
def unshell_list(s):
"""Turn a command-line argument into a list."""
if not s:
return None
if sys.platform == 'win32':
# When running coverage as coverage.exe, some of the behavior
# of the shell is emulated: wildcards are expanded into a list of
# filenames. So you have to ... |
def main(argv=None):
"""The main entry point to Coverage.
This is installed as the script entry point.
"""
if argv is None:
argv = sys.argv[1:]
try:
start = time.clock()
status = CoverageScript().command_line(argv)
end = time.clock()
if 0:
print(... |
def parse_args(self, args=None, options=None):
"""Call optparse.parse_args, but return a triple:
(ok, options, args)
"""
try:
options, args = \
super(CoverageOptionParser, self).parse_args(args, options)
except self.OptionParserError:
ret... |
def add_action(self, dash, dashdash, action_code):
"""Add a specialized option that is the action to execute."""
option = self.add_option(dash, dashdash, action='callback',
callback=self._append_action
)
option.action_code = action_code |
def _append_action(self, option, opt_unused, value_unused, parser):
"""Callback for an option that adds to the `actions` list."""
parser.values.actions.append(option.action_code) |
def command_line(self, argv):
"""The bulk of the command line interface to Coverage.
`argv` is the argument list to process.
Returns 0 if all is well, 1 if something went wrong.
"""
# Collect the command-line options.
if not argv:
self.help_fn(topic='minimu... |
def help(self, error=None, topic=None, parser=None):
"""Display an error message, or the named topic."""
assert error or topic or parser
if error:
print(error)
print("Use 'coverage help' for help.")
elif parser:
print(parser.format_help().strip())
... |
def do_help(self, options, args, parser):
"""Deal with help requests.
Return True if it handled the request, False if not.
"""
# Handle help.
if options.help:
if self.classic:
self.help_fn(topic='help')
else:
self.help_fn(... |
def args_ok(self, options, args):
"""Check for conflicts and problems in the options.
Returns True if everything is ok, or False if not.
"""
for i in ['erase', 'execute']:
for j in ['annotate', 'html', 'report', 'combine']:
if (i in options.actions) and (j i... |
def do_execute(self, options, args):
"""Implementation of 'coverage run'."""
# Set the first path element properly.
old_path0 = sys.path[0]
# Run the script.
self.coverage.start()
code_ran = True
try:
try:
if options.module:
... |
def do_debug(self, args):
"""Implementation of 'coverage debug'."""
if not args:
self.help_fn("What information would you like: data, sys?")
return ERR
for info in args:
if info == 'sys':
print("-- sys ----------------------------------------"... |
def serialize_object(obj, threshold=64e-6):
"""Serialize an object into a list of sendable buffers.
Parameters
----------
obj : object
The object to be serialized
threshold : float
The threshold for not double-pickling the content.
Returns
-------
... |
def unserialize_object(bufs):
"""reconstruct an object serialized by serialize_object from data buffers."""
bufs = list(bufs)
sobj = pickle.loads(bufs.pop(0))
if isinstance(sobj, (list, tuple)):
for s in sobj:
if s.data is None:
s.data = bufs.pop(0)
return unc... |
def pack_apply_message(f, args, kwargs, threshold=64e-6):
"""pack up a function, args, and kwargs to be sent over the wire
as a series of buffers. Any object whose data is larger than `threshold`
will not have their data copied (currently only numpy arrays support zero-copy)"""
msg = [pickle.dumps(can(f... |
def unpack_apply_message(bufs, g=None, copy=True):
"""unpack f,args,kwargs from buffers packed by pack_apply_message()
Returns: original f,args,kwargs"""
bufs = list(bufs) # allow us to pop
assert len(bufs) >= 3, "not enough buffers!"
if not copy:
for i in range(3):
bufs[i] = buf... |
def set(self):
"""Set the hook."""
if sys.displayhook is not self.hook:
self.old_hook = sys.displayhook
sys.displayhook = self.hook |
def log_errors(f, self, *args, **kwargs):
"""decorator to log unhandled exceptions raised in a method.
For use wrapping on_recv callbacks, so that exceptions
do not cause the stream to be closed.
"""
try:
return f(self, *args, **kwargs)
except Exception:
self.log.error("Unca... |
def is_url(url):
"""boolean check for whether a string is a zmq url"""
if '://' not in url:
return False
proto, addr = url.split('://', 1)
if proto.lower() not in ['tcp','pgm','epgm','ipc','inproc']:
return False
return True |
def validate_url(url):
"""validate a url for zeromq"""
if not isinstance(url, basestring):
raise TypeError("url must be a string, not %r"%type(url))
url = url.lower()
proto_addr = url.split('://')
assert len(proto_addr) == 2, 'Invalid url: %r'%url
proto, addr = proto_addr
assert... |
def validate_url_container(container):
"""validate a potentially nested collection of urls."""
if isinstance(container, basestring):
url = container
return validate_url(url)
elif isinstance(container, dict):
container = container.itervalues()
for element in container:
... |
def split_url(url):
"""split a zmq url (tcp://ip:port) into ('tcp','ip','port')."""
proto_addr = url.split('://')
assert len(proto_addr) == 2, 'Invalid url: %r'%url
proto, addr = proto_addr
lis = addr.split(':')
assert len(lis) == 2, 'Invalid url: %r'%url
addr,s_port = lis
return proto,a... |
def disambiguate_ip_address(ip, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation of location is localhost)."""
if ip in ('0.0.0.0', '*'):
try:
external_ips = socket.gethostbyname_ex(socket.gethostname())[2]... |
def disambiguate_url(url, location=None):
"""turn multi-ip interfaces '0.0.0.0' and '*' into connectable
ones, based on the location (default interpretation is localhost).
This is for zeromq urls, such as tcp://*:10101."""
try:
proto,ip,port = split_url(url)
except AssertionError:
... |
def _pull(keys):
"""helper method for implementing `client.pull` via `client.apply`"""
user_ns = globals()
if isinstance(keys, (list,tuple, set)):
for key in keys:
if not user_ns.has_key(key):
raise NameError("name '%s' is not defined"%key)
return map(user_ns.get,... |
def select_random_ports(n):
"""Selects and return n random ports that are available."""
ports = []
for i in xrange(n):
sock = socket.socket()
sock.bind(('', 0))
while sock.getsockname()[1] in _random_ports:
sock.close()
sock = socket.socket()
sock.... |
def signal_children(children):
"""Relay interupt/term signals to children, for more solid process cleanup."""
def terminate_children(sig, frame):
log = Application.instance().log
log.critical("Got signal %i, terminating children..."%sig)
for child in children:
child.terminate... |
def remote(view, block=None, **flags):
"""Turn a function into a remote function.
This method can be used for map:
In [1]: @remote(view,block=True)
...: def func(a):
...: pass
"""
def remote_function(f):
return RemoteFunction(view, f, block=block, **flags)
return remo... |
def parallel(view, dist='b', block=None, ordered=True, **flags):
"""Turn a function into a parallel remote function.
This method can be used for map:
In [1]: @parallel(view, block=True)
...: def func(a):
...: pass
"""
def parallel_function(f):
return ParallelFunction(view... |
def map(self, *sequences):
"""call a function on each element of a sequence remotely.
This should behave very much like the builtin map, but return an AsyncMapResult
if self.block is False.
"""
# set _map as a flag for use inside self.__call__
self._map = True
try... |
def get_readline_tail(self, n=10):
"""Get the last n items in readline history."""
end = self.shell.readline.get_current_history_length() + 1
start = max(end-n, 1)
ghi = self.shell.readline.get_history_item
return [ghi(x) for x in range(start, end)] |
def set_autoindent(self,value=None):
"""Set the autoindent flag, checking for readline support.
If called with no arguments, it acts as a toggle."""
if value != 0 and not self.has_readline:
if os.name == 'posix':
warn("The auto-indent feature requires the readline l... |
def init_logstart(self):
"""Initialize logging in case it was requested at the command line.
"""
if self.logappend:
self.magic('logstart %s append' % self.logappend)
elif self.logfile:
self.magic('logstart %s' % self.logfile)
elif self.logstart:
... |
def init_virtualenv(self):
"""Add a virtualenv to sys.path so the user can import modules from it.
This isn't perfect: it doesn't use the Python interpreter with which the
virtualenv was built, and it ignores the --no-site-packages option. A
warning will appear suggesting the user instal... |
def save_sys_module_state(self):
"""Save the state of hooks in the sys module.
This has to be called after self.user_module is created.
"""
self._orig_sys_module_state = {}
self._orig_sys_module_state['stdin'] = sys.stdin
self._orig_sys_module_state['stdout'] = sys.stdou... |
def restore_sys_module_state(self):
"""Restore the state of the sys module."""
try:
for k, v in self._orig_sys_module_state.iteritems():
setattr(sys, k, v)
except AttributeError:
pass
# Reset what what done in self.init_sys_modules
if self.... |
def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
"""set_hook(name,hook) -> sets an internal IPython hook.
IPython exposes some of its internal API as user-modifiable hooks. By
adding your function to one of these hooks, you can modify IPython's
behavior to ca... |
def register_post_execute(self, func):
"""Register a function for calling after code execution.
"""
if not callable(func):
raise ValueError('argument %s must be callable' % func)
self._post_execute[func] = True |
def new_main_mod(self,ns=None):
"""Return a new 'main' module object for user code execution.
"""
main_mod = self._user_main_module
init_fakemod_dict(main_mod,ns)
return main_mod |
def cache_main_mod(self,ns,fname):
"""Cache a main module's namespace.
When scripts are executed via %run, we must keep a reference to the
namespace of their __main__ module (a FakeModule instance) around so
that Python doesn't clear it, rendering objects defined therein
useless... |
def debugger(self,force=False):
"""Call the pydb/pdb debugger.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if t... |
def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
... |
def init_user_ns(self):
"""Initialize all user-visible namespaces to their minimum defaults.
Certain history lists are also initialized here, as they effectively
act as user namespaces.
Notes
-----
All data structures here are only filled in, they are NOT reset by this
... |
def all_ns_refs(self):
"""Get a list of references to all the namespace dictionaries in which
IPython might store a user-created object.
Note that this does not include the displayhook, which also caches
objects from the output."""
return [self.user_ns, self.user_global_... |
def reset(self, new_session=True):
"""Clear all internal namespaces, and attempt to release references to
user objects.
If new_session is True, a new history session will be opened.
"""
# Clear histories
self.history_manager.reset(new_session)
# Reset counter use... |
def del_var(self, varname, by_name=False):
"""Delete a variable from the various namespaces, so that, as
far as possible, we're not keeping any hidden references to it.
Parameters
----------
varname : str
The name of the variable to delete.
by_name : bool
... |
def reset_selective(self, regex=None):
"""Clear selective variables from internal namespaces based on a
specified regular expression.
Parameters
----------
regex : string or compiled pattern, optional
A regular expression pattern that will be used in searching
... |
def push(self, variables, interactive=True):
"""Inject a group of variables into the IPython user namespace.
Parameters
----------
variables : dict, str or list/tuple of str
The variables to inject into the user's namespace. If a dict, a
simple update is done. ... |
def drop_by_id(self, variables):
"""Remove a dict of variables from the user namespace, if they are the
same as the values in the dictionary.
This is intended for use by extensions: variables that they've added can
be taken back out if they are unloaded, without removing any tha... |
def _ofind(self, oname, namespaces=None):
"""Find an object in the available namespaces.
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
Has special code to detect magic functions.
"""
oname = oname.strip()
#print '1- oname: <%r>' % oname # dbg
i... |
def _ofind_property(self, oname, info):
"""Second part of object finding, to look for property details."""
if info.found:
# Get the docstring of the class property if it exists.
path = oname.split('.')
root = '.'.join(path[:-1])
if info.parent is not None:... |
def _object_find(self, oname, namespaces=None):
"""Find an object and return a struct with info about it."""
inf = Struct(self._ofind(oname, namespaces))
return Struct(self._ofind_property(oname, inf)) |
def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
This function is meant to be called by pdef, pdoc & friends."""
info = self._object_find(oname, namespaces)
if info.found:
pmethod = getattr(self.inspector, meth)
... |
def init_history(self):
"""Sets up the command history, and starts regular autosaves."""
self.history_manager = HistoryManager(shell=self, config=self.config)
self.configurables.append(self.history_manager) |
def set_custom_exc(self, exc_tuple, handler):
"""set_custom_exc(exc_tuple,handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
run_code() method).
Parameters
----------
e... |
def excepthook(self, etype, value, tb):
"""One more defense for GUI apps that call sys.excepthook.
GUI frameworks like wxPython trap exceptions and call
sys.excepthook themselves. I guess this is a feature that
enables them to keep running after exceptions that would
otherwise kill their... |
def _get_exc_info(self, exc_tuple=None):
"""get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
raises ValueError if none of these contain any information
... |
def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
exception_only=False):
"""Display the exception that just occurred.
If nothing is known about the exception, this is the method which
should be used throughout the code for presenting user tracebacks,
... |
def _showtraceback(self, etype, evalue, stb):
"""Actually show a traceback.
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
print >> io.stdout, self.InteractiveTB.stb2text(stb) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.