_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q279300
|
ColorSchemeTable.add_scheme
|
test
|
def add_scheme(self,new_scheme):
"""Add a new color scheme to the table."""
if not isinstance(new_scheme,ColorScheme):
|
python
|
{
"resource": ""
}
|
q279301
|
ColorSchemeTable.set_active_scheme
|
test
|
def set_active_scheme(self,scheme,case_sensitive=0):
"""Set the currently active scheme.
Names are by default compared in a case-insensitive way, but this can
be changed by setting the parameter case_sensitive to true."""
scheme_names = self.keys()
if case_sensitive:
valid_schemes = scheme_names
scheme_test = scheme
else:
valid_schemes = [s.lower() for s in scheme_names]
scheme_test = scheme.lower()
try:
scheme_idx = valid_schemes.index(scheme_test)
except ValueError:
raise
|
python
|
{
"resource": ""
}
|
q279302
|
home_lib
|
test
|
def home_lib(home):
"""Return the lib dir under the 'home' installation scheme"""
if hasattr(sys, 'pypy_version_info'):
lib = 'site-packages'
else:
|
python
|
{
"resource": ""
}
|
q279303
|
ZMQTerminalInteractiveShell.handle_iopub
|
test
|
def handle_iopub(self):
""" Method to procces subscribe channel's messages
This method reads a message and processes the content in different
outputs like stdout, stderr, pyout and status
Arguments:
sub_msg: message receive from kernel in the sub socket channel
capture by kernel manager.
"""
while self.km.sub_channel.msg_ready():
sub_msg = self.km.sub_channel.get_msg()
msg_type = sub_msg['header']['msg_type']
parent = sub_msg["parent_header"]
if (not parent) or self.session_id == parent['session']:
if msg_type == 'status' :
if sub_msg["content"]["execution_state"] == "busy" :
pass
elif msg_type == 'stream' :
if sub_msg["content"]["name"] == "stdout":
print(sub_msg["content"]["data"], file=io.stdout, end="")
io.stdout.flush()
|
python
|
{
"resource": ""
}
|
q279304
|
ZMQTerminalInteractiveShell.handle_stdin_request
|
test
|
def handle_stdin_request(self, timeout=0.1):
""" Method to capture raw_input
"""
msg_rep = self.km.stdin_channel.get_msg(timeout=timeout)
# in case any iopub came while we were waiting:
self.handle_iopub()
if self.session_id == msg_rep["parent_header"].get("session"):
# wrap SIGINT handler
real_handler = signal.getsignal(signal.SIGINT)
def double_int(sig,frame):
# call real handler (forwards sigint to kernel),
# then raise local interrupt, stopping local raw_input
real_handler(sig,frame)
raise KeyboardInterrupt
signal.signal(signal.SIGINT, double_int)
try:
raw_data = raw_input(msg_rep["content"]["prompt"])
except EOFError:
# turn EOFError into EOF character
|
python
|
{
"resource": ""
}
|
q279305
|
ZMQTerminalInteractiveShell.wait_for_kernel
|
test
|
def wait_for_kernel(self, timeout=None):
"""method to wait for a kernel to be ready"""
tic = time.time()
self.km.hb_channel.unpause()
while True:
self.run_cell('1', False)
|
python
|
{
"resource": ""
}
|
q279306
|
PygmentsHighlighter.set_style
|
test
|
def set_style(self, style):
""" Sets the style to the specified Pygments style.
"""
if isinstance(style, basestring):
|
python
|
{
"resource": ""
}
|
q279307
|
PygmentsHighlighter._get_format
|
test
|
def _get_format(self, token):
""" Returns a QTextCharFormat for token or None.
"""
if token in self._formats:
return self._formats[token]
if self._style is None:
result = self._get_format_from_document(token, self._document)
|
python
|
{
"resource": ""
}
|
q279308
|
PygmentsHighlighter._get_format_from_document
|
test
|
def _get_format_from_document(self, token, document):
""" Returns a QTextCharFormat for token by
"""
code, html = self._formatter._format_lines([(token, u'dummy')]).next()
|
python
|
{
"resource": ""
}
|
q279309
|
PygmentsHighlighter._get_format_from_style
|
test
|
def _get_format_from_style(self, token, style):
""" Returns a QTextCharFormat for token by reading a Pygments style.
"""
result = QtGui.QTextCharFormat()
for key, value in style.style_for_token(token).items():
if value:
if key == 'color':
result.setForeground(self._get_brush(value))
elif key == 'bgcolor':
result.setBackground(self._get_brush(value))
elif key == 'bold':
result.setFontWeight(QtGui.QFont.Bold)
elif key == 'italic':
result.setFontItalic(True)
elif key == 'underline':
result.setUnderlineStyle(
|
python
|
{
"resource": ""
}
|
q279310
|
find_command
|
test
|
def find_command(cmd, paths=None, pathext=None):
"""Searches the PATH for the given command and returns its path"""
if paths is None:
paths = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(paths, six.string_types):
paths = [paths]
# check if there are funny path extensions for executables, e.g. Windows
if pathext is None:
pathext = get_pathext()
pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)]
# don't use extensions if the command ends with one of them
if os.path.splitext(cmd)[1].lower() in pathext:
pathext = ['']
# check if we find the command on PATH
for path in paths:
# try without extension first
|
python
|
{
"resource": ""
}
|
q279311
|
normalize_path
|
test
|
def normalize_path(path):
"""
Convert a path to its canonical, case-normalized, absolute version.
"""
|
python
|
{
"resource": ""
}
|
q279312
|
check_nsp
|
test
|
def check_nsp(dist, attr, value):
"""Verify that namespace packages are valid"""
assert_string_list(dist,attr,value)
for nsp in value:
if not dist.has_contents_for(nsp):
raise DistutilsSetupError(
"Distribution contains no modules or packages for " +
"namespace package %r" % nsp
)
if '.' in nsp:
parent = '.'.join(nsp.split('.')[:-1])
|
python
|
{
"resource": ""
}
|
q279313
|
check_entry_points
|
test
|
def check_entry_points(dist, attr, value):
"""Verify that entry_points map is parseable"""
try:
|
python
|
{
"resource": ""
}
|
q279314
|
last_blank
|
test
|
def last_blank(src):
"""Determine if the input source ends in a blank.
A blank is either a newline or a line consisting of whitespace.
|
python
|
{
"resource": ""
}
|
q279315
|
last_two_blanks
|
test
|
def last_two_blanks(src):
"""Determine if the input source ends in two blanks.
A blank is either a newline or a line consisting of whitespace.
Parameters
----------
src : string
A single or multiline string.
"""
if not src: return False
# The logic here is tricky: I couldn't get a regexp to work and pass all
# the tests, so I took a different approach: split the source by lines,
# grab the last two and prepend '###\n' as a stand-in for whatever was in
# the body before the
|
python
|
{
"resource": ""
}
|
q279316
|
transform_assign_system
|
test
|
def transform_assign_system(line):
"""Handle the `files = !ls` syntax."""
m = _assign_system_re.match(line)
if m is
|
python
|
{
"resource": ""
}
|
q279317
|
transform_assign_magic
|
test
|
def transform_assign_magic(line):
"""Handle the `a = %who` syntax."""
m = _assign_magic_re.match(line)
if m is
|
python
|
{
"resource": ""
}
|
q279318
|
transform_classic_prompt
|
test
|
def transform_classic_prompt(line):
"""Handle inputs that start with '>>> ' syntax."""
if not line or line.isspace():
return line
m =
|
python
|
{
"resource": ""
}
|
q279319
|
transform_ipy_prompt
|
test
|
def transform_ipy_prompt(line):
"""Handle inputs that start classic IPython prompt syntax."""
if not line or line.isspace():
return line
#print 'LINE: %r' % line # dbg
m = _ipy_prompt_re.match(line)
if m:
#print 'MATCH! %r
|
python
|
{
"resource": ""
}
|
q279320
|
InputSplitter.push
|
test
|
def push(self, lines):
"""Push one or more lines of input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not.
Any exceptions generated in compilation are swallowed, but if an
exception was produced, the method returns True.
Parameters
----------
lines : string
One or more lines of Python input.
Returns
-------
is_complete : boolean
True if the current input source (the result of the current input
plus prior inputs) forms a complete Python execution block. Note that
this value is also stored as a private attribute (``_is_complete``), so it
can be queried at any time.
"""
if self.input_mode == 'cell':
self.reset()
self._store(lines)
source = self.source
# Before calling _compile(), reset the code object to None so that if an
# exception is raised in compilation, we don't mislead by having
# inconsistent code/source attributes.
self.code, self._is_complete = None, None
# Honor termination lines properly
if source.rstrip().endswith('\\'):
return
|
python
|
{
"resource": ""
}
|
q279321
|
InputSplitter.push_accepts_more
|
test
|
def push_accepts_more(self):
"""Return whether a block of interactive input can accept more input.
This method is meant to be used by line-oriented frontends, who need to
guess whether a block is complete or not based solely on prior and
current input lines. The InputSplitter considers it has a complete
interactive block and will not accept more input only when either a
SyntaxError is raised, or *all* of the following are true:
1. The input compiles to a complete statement.
2. The indentation level is flush-left (because if we are indented,
like inside a function definition or for loop, we need to keep
reading new input).
3. There is one extra line consisting only of whitespace.
Because of condition #3, this method should be used only by
*line-oriented* frontends, since it means that intermediate blank lines
are not allowed in function definitions (or any other indented block).
If the current input produces a syntax error, this method immediately
returns False but does *not* raise the syntax error exception, as
typically clients will want to send invalid syntax to an execution
|
python
|
{
"resource": ""
}
|
q279322
|
InputSplitter._find_indent
|
test
|
def _find_indent(self, line):
"""Compute the new indentation level for a single line.
Parameters
----------
line : str
A single new line of non-whitespace, non-comment Python input.
Returns
-------
indent_spaces : int
New value for the indent level (it may be equal to self.indent_spaces
if indentation doesn't change.
full_dedent : boolean
Whether the new line causes a full flush-left dedent.
|
python
|
{
"resource": ""
}
|
q279323
|
InputSplitter._store
|
test
|
def _store(self, lines, buffer=None, store='source'):
"""Store one or more lines of input.
If input lines are not newline-terminated, a newline is automatically
|
python
|
{
"resource": ""
}
|
q279324
|
IPythonInputSplitter.source_raw_reset
|
test
|
def source_raw_reset(self):
"""Return input and raw source and perform a full reset.
|
python
|
{
"resource": ""
}
|
q279325
|
IPythonInputSplitter._handle_cell_magic
|
test
|
def _handle_cell_magic(self, lines):
"""Process lines when they start with %%, which marks cell magics.
"""
self.processing_cell_magic = True
first, _, body = lines.partition('\n')
magic_name, _, line = first.partition(' ')
magic_name = magic_name.lstrip(ESC_MAGIC)
# We store the body of the cell and create a call to a method that
# will use this stored value. This is ugly, but it's a first cut to
# get it all working, as right now changing the return API of our
# methods would require major refactoring.
self.cell_magic_parts = [body]
tpl = 'get_ipython()._run_cached_cell_magic(%r, %r)'
tlines = tpl % (magic_name, line)
self._store(tlines)
self._store(lines, self._buffer_raw, 'source_raw')
# We can actually choose whether to allow
|
python
|
{
"resource": ""
}
|
q279326
|
IPythonInputSplitter._line_mode_cell_append
|
test
|
def _line_mode_cell_append(self, lines):
"""Append new content for a cell magic in line mode.
"""
# Only store the raw input. Lines beyond the first one are only only
# stored for history purposes; for execution the caller will grab the
# magic pieces from cell_magic_parts and will assemble the cell body
self._store(lines, self._buffer_raw, 'source_raw')
self.cell_magic_parts.append(lines)
# Find out if the last stored block has a whitespace line as its
# last line and also this line is whitespace, case in which we're
# done (two contiguous blank lines signal termination). Note that
|
python
|
{
"resource": ""
}
|
q279327
|
IPythonInputSplitter.transform_cell
|
test
|
def transform_cell(self, cell):
"""Process and translate a cell of input.
"""
|
python
|
{
"resource": ""
}
|
q279328
|
IPythonInputSplitter.push
|
test
|
def push(self, lines):
"""Push one or more lines of IPython input.
This stores the given lines and returns a status code indicating
whether the code forms a complete Python block or not, after processing
all input lines for special IPython syntax.
Any exceptions generated in compilation are swallowed, but if an
exception was produced, the method returns True.
Parameters
----------
lines : string
One or more lines of Python input.
Returns
-------
is_complete : boolean
True if the current input source (the result of the current input
plus prior inputs) forms a complete Python execution block. Note that
this value is also stored as a private attribute (_is_complete), so it
can be queried at any time.
"""
if not lines:
return super(IPythonInputSplitter, self).push(lines)
# We must ensure all input is pure unicode
lines = cast_unicode(lines, self.encoding)
# If the entire input block is a cell magic, return after handling it
# as the rest of the transformation logic should be skipped.
if lines.startswith('%%') and not \
(len(lines.splitlines()) == 1 and lines.strip().endswith('?')):
return self._handle_cell_magic(lines)
# In line mode, a cell magic can arrive in separate pieces
if self.input_mode == 'line' and self.processing_cell_magic:
return self._line_mode_cell_append(lines)
# The rest of the processing is for 'normal' content, i.e. IPython
# source that we process through our transformations pipeline.
lines_list = lines.splitlines()
transforms = [transform_ipy_prompt, transform_classic_prompt,
transform_help_end, transform_escaped,
transform_assign_system, transform_assign_magic]
# Transform logic
#
# We only apply the line transformers to the input if we have either no
# input yet, or complete input, or if the last line of the buffer ends
# with ':' (opening an indented block). This prevents the accidental
# transformation of escapes inside multiline expressions like
# triple-quoted strings or parenthesized expressions.
#
# The last heuristic, while ugly, ensures that the first line of an
# indented block is correctly transformed.
#
# FIXME: try to
|
python
|
{
"resource": ""
}
|
q279329
|
NotificationCenter._init_observers
|
test
|
def _init_observers(self):
"""Initialize observer storage"""
self.registered_types =
|
python
|
{
"resource": ""
}
|
q279330
|
NotificationCenter.post_notification
|
test
|
def post_notification(self, ntype, sender, *args, **kwargs):
"""Post notification to all registered observers.
The registered callback will be called as::
callback(ntype, sender, *args, **kwargs)
Parameters
----------
ntype : hashable
The notification type.
sender : hashable
The object sending the notification.
*args : tuple
The positional arguments to be passed to the callback.
**kwargs : dict
The keyword argument to be passed to the callback.
|
python
|
{
"resource": ""
}
|
q279331
|
NotificationCenter._observers_for_notification
|
test
|
def _observers_for_notification(self, ntype, sender):
"""Find all registered observers that should recieve notification"""
keys = (
(ntype,sender),
|
python
|
{
"resource": ""
}
|
q279332
|
NotificationCenter.add_observer
|
test
|
def add_observer(self, callback, ntype, sender):
"""Add an observer callback to this notification center.
The given callback will be called upon posting of notifications of
the given type/sender and will receive any additional arguments passed
to post_notification.
Parameters
----------
callback : callable
The callable that will be called by :meth:`post_notification`
as ``callback(ntype, sender, *args, **kwargs)
ntype : hashable
The notification type. If None, all notifications from sender
will be posted.
|
python
|
{
"resource": ""
}
|
q279333
|
BackgroundJobManager.new
|
test
|
def new(self, func_or_exp, *args, **kwargs):
"""Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call.
The expression must be given as a string. For example:
job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
The given expression is passed to eval(), along with the optional
global/local dicts provided. If no dicts are given, they are
extracted automatically from the caller's frame.
A Python statement is NOT a valid eval() expression. Basically, you
can only use as an eval() argument something which can go on the right
of an '=' sign and be assigned to a variable.
For example,"print 'hello'" is not valid, but '2+3' is.
2. Jobs given a function object, optionally passing additional
positional arguments:
job_manager.new(myfunc, x, y)
The function is called with the given arguments.
If you need to pass keyword arguments to your function, you must
supply them as a dict named kw:
job_manager.new(myfunc, x, y, kw=dict(z=1))
The reason for this assymmetry is that the new() method needs to
maintain access to its own keywords, and this prevents name collisions
between arguments to new() and arguments to your own functions.
In both cases, the result is stored in the job.result field of the
background job object.
You can set `daemon` attribute of the thread by giving the keyword
argument `daemon`.
Notes and caveats:
1. All threads running share the same standard output. Thus, if your
background jobs generate output, it will come out on top of whatever
you are currently writing. For this reason, background jobs are best
used with silent functions which simply return their output.
2. Threads also all work within the same global namespace, and this
system does not lock interactive variables. So if you send job to the
background which operates on a mutable object for a long time, and
start modifying that same mutable object interactively (or in another
backgrounded job), all sorts of bizarre behaviour will occur.
3. If a background job is spending a lot of time inside a C extension
module which does not release the Python Global Interpreter Lock
(GIL), this will block the IPython prompt. This is simply because the
Python interpreter can only switch between threads at Python
|
python
|
{
"resource": ""
}
|
q279334
|
BackgroundJobManager._update_status
|
test
|
def _update_status(self):
"""Update the status of the job lists.
This method moves finished jobs to one of two lists:
- self.completed: jobs which completed successfully
- self.dead: jobs which finished but died.
It also copies those jobs to corresponding _report lists. These lists
are used to report jobs completed/dead since the last update, and are
then cleared by the reporting function after each call."""
# Status codes
srun, scomp, sdead = self._s_running, self._s_completed, self._s_dead
|
python
|
{
"resource": ""
}
|
q279335
|
BackgroundJobManager._group_report
|
test
|
def _group_report(self,group,name):
"""Report summary for a given job group.
Return True if the group had any elements."""
if group:
print '%s jobs:' % name
|
python
|
{
"resource": ""
}
|
q279336
|
BackgroundJobManager._group_flush
|
test
|
def _group_flush(self,group,name):
"""Flush a given job group
Return True if the group had any elements."""
njobs = len(group)
if njobs:
plural = {1:''}.setdefault(njobs,'s')
|
python
|
{
"resource": ""
}
|
q279337
|
BackgroundJobManager._status_new
|
test
|
def _status_new(self):
"""Print the status of newly finished jobs.
Return True if any new jobs are reported.
This call resets its own state every time, so it only reports jobs
which have finished since the last time it was called."""
self._update_status()
new_comp = self._group_report(self._comp_report, 'Completed')
new_dead =
|
python
|
{
"resource": ""
}
|
q279338
|
BackgroundJobManager.status
|
test
|
def status(self,verbose=0):
"""Print a status of all jobs currently being managed."""
self._update_status()
self._group_report(self.running,'Running')
|
python
|
{
"resource": ""
}
|
q279339
|
BackgroundJobBase._init
|
test
|
def _init(self):
"""Common initialization for all BackgroundJob objects"""
for attr in ['call','strform']:
assert hasattr(self,attr), "Missing attribute <%s>" % attr
# The num tag can be set by an external job manager
self.num = None
self.status = BackgroundJobBase.stat_created
self.stat_code = BackgroundJobBase.stat_created_c
self.finished = False
self.result = '<BackgroundJob has not completed>'
# reuse the ipython traceback handler if we can get to it, otherwise
# make a new one
try:
make_tb = get_ipython().InteractiveTB.text
except:
make_tb = AutoFormattedTB(mode = 'Context',
color_scheme='NoColor',
|
python
|
{
"resource": ""
}
|
q279340
|
ListVariable.insert
|
test
|
def insert(self, idx, value):
"""
Inserts a value in the ``ListVariable`` at an appropriate index.
:param idx: The index before which to insert the new value.
|
python
|
{
"resource": ""
}
|
q279341
|
Environment.copy
|
test
|
def copy(self):
"""
Retrieve a copy of the Environment. Note that this is a shallow
copy.
"""
|
python
|
{
"resource": ""
}
|
q279342
|
Environment._declare_special
|
test
|
def _declare_special(self, name, sep, klass):
"""
Declare an environment variable as a special variable. This can
be used even if the environment variable is not present.
:param name: The name of the environment variable that should
be considered special.
:param sep: The separator to be used.
:param klass: The subclass of ``SpecialVariable`` used to
represent the variable.
"""
# First, has it already been declared?
if name in self._special:
|
python
|
{
"resource": ""
}
|
q279343
|
Environment.declare_list
|
test
|
def declare_list(self, name, sep=os.pathsep):
"""
Declare an environment variable as a list-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
|
python
|
{
"resource": ""
}
|
q279344
|
Environment.declare_set
|
test
|
def declare_set(self, name, sep=os.pathsep):
"""
Declare an environment variable as a set-like special variable.
This can be used even if the environment variable is not
present.
:param name: The name of the environment variable that should
|
python
|
{
"resource": ""
}
|
q279345
|
Environment.cwd
|
test
|
def cwd(self, value):
"""
Change the working directory that processes should be executed in.
:param value: The new path to change to. If relative, will be
interpreted relative to the current working
|
python
|
{
"resource": ""
}
|
q279346
|
TSPProblem.move
|
test
|
def move(self, state=None):
"""Swaps two cities in the route.
:type state: TSPState
"""
state = self.state if state is None else state
route = state
|
python
|
{
"resource": ""
}
|
q279347
|
TSPProblem.energy
|
test
|
def energy(self, state=None):
"""Calculates the length of the route."""
state = self.state if state is None else state
route = state
e = 0
if self.distance_matrix:
for i in range(len(route)):
e += self.distance_matrix["{},{}".format(route[i-1], route[i])]
|
python
|
{
"resource": ""
}
|
q279348
|
SQLiteDB._defaults
|
test
|
def _defaults(self, keys=None):
"""create an empty record"""
d = {}
keys = self._keys if keys is None else keys
|
python
|
{
"resource": ""
}
|
q279349
|
SQLiteDB._check_table
|
test
|
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
return True
types = {}
keys = []
for line in lines:
keys.append(line[1])
types[line[1]] = line[2]
if self._keys != keys:
|
python
|
{
"resource": ""
}
|
q279350
|
SQLiteDB._list_to_dict
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q279351
|
SQLiteDB._render_expression
|
test
|
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:
raise KeyError("Illegal testing key(s): %s"%skeys)
for name,sub_check in check.iteritems():
if isinstance(sub_check, dict):
for test,value in sub_check.iteritems():
try:
op = operators[test]
except KeyError:
raise KeyError("Unsupported operator: %r"%test)
if isinstance(op, tuple):
op, join = op
|
python
|
{
"resource": ""
}
|
q279352
|
warn
|
test
|
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 level).
3 -> Print 'ERROR:' + message.
4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
-exit_val
|
python
|
{
"resource": ""
}
|
q279353
|
Reader.parse
|
test
|
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 and try to get config/app.yml.
|
python
|
{
"resource": ""
}
|
q279354
|
table
|
test
|
def table(rows):
'''
Output a simple table with several columns.
'''
output = '<table>'
for row in rows:
output += '<tr>'
for column in row:
output
|
python
|
{
"resource": ""
}
|
q279355
|
link
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279356
|
jsfile
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279357
|
cssfile
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279358
|
img
|
test
|
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 = {
|
python
|
{
"resource": ""
}
|
q279359
|
sub
|
test
|
def sub(value, arg):
"""Subtract the arg from the value."""
try:
return valid_numeric(value) - valid_numeric(arg)
except (ValueError, TypeError):
try:
|
python
|
{
"resource": ""
}
|
q279360
|
mul
|
test
|
def mul(value, arg):
"""Multiply the arg with the value."""
try:
return valid_numeric(value) * valid_numeric(arg)
except (ValueError, TypeError):
try:
|
python
|
{
"resource": ""
}
|
q279361
|
div
|
test
|
def div(value, arg):
"""Divide the arg by the value."""
try:
return valid_numeric(value) / valid_numeric(arg)
except (ValueError, TypeError):
try:
|
python
|
{
"resource": ""
}
|
q279362
|
mod
|
test
|
def mod(value, arg):
"""Return the modulo value."""
try:
return valid_numeric(value) % valid_numeric(arg)
except (ValueError, TypeError):
try:
|
python
|
{
"resource": ""
}
|
q279363
|
model_verbose
|
test
|
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, ModelForm):
name = obj._meta.model._meta.verbose_name
|
python
|
{
"resource": ""
}
|
q279364
|
split_user_input
|
test
|
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, encoding)
if pattern is None:
pattern = line_split
match = pattern.match(line)
if not match:
# print "match failed for line '%s'" % line
try:
ifun, the_rest = line.split(None,1)
except ValueError:
|
python
|
{
"resource": ""
}
|
q279365
|
MultiProcess.options
|
test
|
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",
help="Spread test run among this many processes. "
"Set a number equal to the number of processors "
"or cores in your machine for best results. "
"[NOSE_PROCESSES]")
parser.add_option("--process-timeout", action="store",
default=env.get('NOSE_PROCESS_TIMEOUT', 10),
dest="multiprocess_timeout",
metavar="SECONDS",
help="Set timeout for return of results from each "
|
python
|
{
"resource": ""
}
|
q279366
|
BuiltinTrap.add_builtin
|
test
|
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'
|
python
|
{
"resource": ""
}
|
q279367
|
BuiltinTrap.remove_builtin
|
test
|
def remove_builtin(self, key, orig):
"""Remove an added builtin and re-set the original."""
if orig is BuiltinUndefined:
|
python
|
{
"resource": ""
}
|
q279368
|
BuiltinTrap.deactivate
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279369
|
PackageFinder._find_url_name
|
test
|
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... weird but true.
# FIXME: bad to modify this?
index_url.url += '/'
page = self._get_page(index_url, req)
if page is None:
logger.critical('Cannot fetch index base URL %s', index_url)
return
|
python
|
{
"resource": ""
}
|
q279370
|
HTMLPage.explicit_rel_links
|
test
|
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())
# Determine the intersection between what rels were found and
# what rels were being looked for
if found_rels & rels:
|
python
|
{
"resource": ""
}
|
q279371
|
unshell_list
|
test
|
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 single-quote patterns on the command
|
python
|
{
"resource": ""
}
|
q279372
|
main
|
test
|
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("time: %.3fs" % (end - start))
except ExceptionDuringRun:
# An exception was caught while running the product code. The
# sys.exc_info() return tuple is packed into an ExceptionDuringRun
# exception.
_, err, _ = sys.exc_info()
traceback.print_exception(*err.args)
status = ERR
except CoverageException:
|
python
|
{
"resource": ""
}
|
q279373
|
ClassicOptionParser.add_action
|
test
|
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',
|
python
|
{
"resource": ""
}
|
q279374
|
ClassicOptionParser._append_action
|
test
|
def _append_action(self, option, opt_unused, value_unused, parser):
"""Callback
|
python
|
{
"resource": ""
}
|
q279375
|
CoverageScript.command_line
|
test
|
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='minimum_help')
return OK
# The command syntax we parse depends on the first argument. Classic
# syntax always starts with an option.
self.classic = argv[0].startswith('-')
if self.classic:
parser = ClassicOptionParser()
else:
parser = CMDS.get(argv[0])
if not parser:
self.help_fn("Unknown command: '%s'" % argv[0])
return ERR
argv = argv[1:]
parser.help_fn = self.help_fn
ok, options, args = parser.parse_args(argv)
if not ok:
return ERR
# Handle help and version.
if self.do_help(options, args, parser):
return OK
# Check for conflicts and problems in the options.
if not self.args_ok(options, args):
return ERR
# Listify the list options.
source = unshell_list(options.source)
omit = unshell_list(options.omit)
include = unshell_list(options.include)
debug = unshell_list(options.debug)
# Do something.
self.coverage = self.covpkg.coverage(
data_suffix = options.parallel_mode,
cover_pylib = options.pylib,
timid = options.timid,
branch = options.branch,
config_file = options.rcfile,
source = source,
omit = omit,
include = include,
debug = debug,
)
if 'debug' in options.actions:
return self.do_debug(args)
if 'erase' in options.actions or options.erase_first:
self.coverage.erase()
else:
self.coverage.load()
if 'execute' in options.actions:
self.do_execute(options, args)
|
python
|
{
"resource": ""
}
|
q279376
|
CoverageScript.help
|
test
|
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())
else:
|
python
|
{
"resource": ""
}
|
q279377
|
CoverageScript.do_help
|
test
|
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(parser=parser)
return True
if "help" in options.actions:
if args:
for a in args:
parser = CMDS.get(a)
if parser:
self.help_fn(parser=parser)
else:
|
python
|
{
"resource": ""
}
|
q279378
|
CoverageScript.args_ok
|
test
|
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 in options.actions):
self.help_fn("You can't specify the '%s' and '%s' "
"options at the same time." % (i, j))
return False
if not options.actions:
self.help_fn(
"You must specify at least one of -e, -x, -c, -r, -a, or -b."
)
return False
args_allowed = (
'execute' in options.actions or
'annotate' in options.actions or
'html' in options.actions or
|
python
|
{
"resource": ""
}
|
q279379
|
CoverageScript.do_execute
|
test
|
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:
sys.path[0] = ''
self.run_python_module(args[0], args)
else:
filename = args[0]
|
python
|
{
"resource": ""
}
|
q279380
|
CoverageScript.do_debug
|
test
|
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 ----------------------------------------")
for line in info_formatter(self.coverage.sysinfo()):
print(" %s" % line)
elif info == 'data':
print("-- data ---------------------------------------")
self.coverage.load()
print("path: %s" % self.coverage.data.filename)
print("has_arcs: %r" % self.coverage.data.has_arcs())
|
python
|
{
"resource": ""
}
|
q279381
|
unserialize_object
|
test
|
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 uncanSequence(map(unserialize, sobj)), bufs
elif isinstance(sobj, dict):
newobj = {}
for k in sorted(sobj.iterkeys()):
s = sobj[k]
if s.data is None:
|
python
|
{
"resource": ""
}
|
q279382
|
DisplayTrap.set
|
test
|
def set(self):
"""Set the hook."""
if sys.displayhook is
|
python
|
{
"resource": ""
}
|
q279383
|
log_errors
|
test
|
def log_errors(f, self, *args, **kwargs):
"""decorator to log unhandled exceptions raised in a method.
For use wrapping on_recv callbacks, so that
|
python
|
{
"resource": ""
}
|
q279384
|
is_url
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q279385
|
validate_url
|
test
|
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 proto in ['tcp','pgm','epgm','ipc','inproc'], "Invalid protocol: %r"%proto
# domain pattern adapted from http://www.regexlib.com/REDetails.aspx?regexp_id=391
# author: Remi Sabourin
pat = re.compile(r'^([\w\d]([\w\d\-]{0,61}[\w\d])?\.)*[\w\d]([\w\d\-]{0,61}[\w\d])?$')
if proto == 'tcp':
lis = addr.split(':')
assert len(lis) == 2, 'Invalid url: %r'%url
addr,s_port = lis
|
python
|
{
"resource": ""
}
|
q279386
|
validate_url_container
|
test
|
def validate_url_container(container):
"""validate a potentially nested collection of urls."""
if isinstance(container, basestring):
|
python
|
{
"resource": ""
}
|
q279387
|
_pull
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q279388
|
select_random_ports
|
test
|
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()
|
python
|
{
"resource": ""
}
|
q279389
|
remote
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q279390
|
parallel
|
test
|
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
"""
|
python
|
{
"resource": ""
}
|
q279391
|
ParallelFunction.map
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279392
|
ReadlineNoRecord.get_readline_tail
|
test
|
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)
|
python
|
{
"resource": ""
}
|
q279393
|
InteractiveShell.set_autoindent
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279394
|
InteractiveShell.init_logstart
|
test
|
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:
|
python
|
{
"resource": ""
}
|
q279395
|
InteractiveShell.save_sys_module_state
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279396
|
InteractiveShell.restore_sys_module_state
|
test
|
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
|
python
|
{
"resource": ""
}
|
q279397
|
InteractiveShell.register_post_execute
|
test
|
def register_post_execute(self, func):
"""Register a function for calling after code execution.
|
python
|
{
"resource": ""
}
|
q279398
|
InteractiveShell.new_main_mod
|
test
|
def new_main_mod(self,ns=None):
"""Return a new 'main' module object for user code execution.
"""
|
python
|
{
"resource": ""
}
|
q279399
|
InteractiveShell.cache_main_mod
|
test
|
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.
This method keeps said reference in a private dict, keyed by the
absolute path of the module object (which corresponds to the script
path). This way, for multiple executions of the same script we only
keep one copy of the namespace (the last one), thus preventing memory
leaks from old references while allowing the objects from the last
execution to be accessible.
Note: we can not allow the actual FakeModule instances to be deleted,
because of how Python tears down modules (it hard-sets all their
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.