_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q280200 | QtAnsiCodeProcessor.get_format | test | def get_format(self):
""" Returns a QTextCharFormat that encodes the current style attributes.
"""
format = QtGui.QTextCharFormat()
# Set foreground color
qcolor = self.get_color(self.foreground_color, self.intensity)
if qcolor is not None:
format.setForegrou... | python | {
"resource": ""
} |
q280201 | generate | test | def generate(secret, age, **payload):
"""Generate a one-time jwt with an age in seconds"""
jti = str(uuid.uuid1()) # random id
if not payload:
payload = {}
payload['exp'] = int(time.time() + age)
payload['jti'] = jti
return jwt.encode(payload, decode_secret(secret)) | python | {
"resource": ""
} |
q280202 | mutex | test | def mutex(func):
"""use a thread lock on current method, if self.lock is defined"""
def wrapper(*args, **kwargs):
"""Decorator Wrapper"""
lock = args[0].lock
lock.acquire(True)
try:
return func(*args, **kwargs)
except:
raise
finally:
... | python | {
"resource": ""
} |
q280203 | Manager._clean | test | def _clean(self):
"""Run by housekeeper thread"""
now = time.time()
for jwt in self.jwts.keys():
if (now - self.jwts[jwt]) > (self.age * 2):
del self.jwts[jwt] | python | {
"resource": ""
} |
q280204 | Manager.already_used | test | def already_used(self, tok):
"""has this jwt been used?"""
if tok in self.jwts:
return True
self.jwts[tok] = time.time()
return False | python | {
"resource": ""
} |
q280205 | Manager.valid | test | def valid(self, token):
"""is this token valid?"""
now = time.time()
if 'Bearer ' in token:
token = token[7:]
data = None
for secret in self.secrets:
try:
data = jwt.decode(token, secret)
break
except jwt.Decod... | python | {
"resource": ""
} |
q280206 | semaphore | test | def semaphore(count: int, bounded: bool=False):
'''
use `Semaphore` to keep func access thread-safety.
example:
``` py
@semaphore(3)
def func(): pass
```
'''
lock_type = threading.BoundedSemaphore if bounded else threading.Semaphore
lock_obj = lock_type(value=count)
retur... | python | {
"resource": ""
} |
q280207 | commonprefix | test | def commonprefix(items):
"""Get common prefix for completions
Return the longest common prefix of a list of strings, but with special
treatment of escape characters that might precede commands in IPython,
such as %magic functions. Used in tab completion.
For a more general function, see os.path.co... | python | {
"resource": ""
} |
q280208 | ConsoleWidget.eventFilter | test | def eventFilter(self, obj, event):
""" Reimplemented to ensure a console-like behavior in the underlying
text widgets.
"""
etype = event.type()
if etype == QtCore.QEvent.KeyPress:
# Re-map keys for all filtered widgets.
key = event.key()
i... | python | {
"resource": ""
} |
q280209 | ConsoleWidget.sizeHint | test | def sizeHint(self):
""" Reimplemented to suggest a size that is 80 characters wide and
25 lines high.
"""
font_metrics = QtGui.QFontMetrics(self.font)
margin = (self._control.frameWidth() +
self._control.document().documentMargin()) * 2
style = self.... | python | {
"resource": ""
} |
q280210 | ConsoleWidget.can_cut | test | def can_cut(self):
""" Returns whether text can be cut to the clipboard.
"""
cursor = self._control.textCursor()
return (cursor.hasSelection() and
self._in_buffer(cursor.anchor()) and
self._in_buffer(cursor.position())) | python | {
"resource": ""
} |
q280211 | ConsoleWidget.can_paste | test | def can_paste(self):
""" Returns whether text can be pasted from the clipboard.
"""
if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:
return bool(QtGui.QApplication.clipboard().text())
return False | python | {
"resource": ""
} |
q280212 | ConsoleWidget.clear | test | def clear(self, keep_input=True):
""" Clear the console.
Parameters:
-----------
keep_input : bool, optional (default True)
If set, restores the old input buffer if a new prompt is written.
"""
if self._executing:
self._control.clear()
els... | python | {
"resource": ""
} |
q280213 | ConsoleWidget.cut | test | def cut(self):
""" Copy the currently selected text to the clipboard and delete it
if it's inside the input buffer.
"""
self.copy()
if self.can_cut():
self._control.textCursor().removeSelectedText() | python | {
"resource": ""
} |
q280214 | ConsoleWidget.execute | test | def execute(self, source=None, hidden=False, interactive=False):
""" Executes source or the input buffer, possibly prompting for more
input.
Parameters:
-----------
source : str, optional
The source to execute. If not specified, the input buffer will be
... | python | {
"resource": ""
} |
q280215 | ConsoleWidget._get_input_buffer | test | def _get_input_buffer(self, force=False):
""" The text that the user has entered entered at the current prompt.
If the console is currently executing, the text that is executing will
always be returned.
"""
# If we're executing, the input buffer may not even exist anymore due to... | python | {
"resource": ""
} |
q280216 | ConsoleWidget._set_input_buffer | test | def _set_input_buffer(self, string):
""" Sets the text in the input buffer.
If the console is currently executing, this call has no *immediate*
effect. When the execution is finished, the input buffer will be updated
appropriately.
"""
# If we're executing, store the tex... | python | {
"resource": ""
} |
q280217 | ConsoleWidget._set_font | test | def _set_font(self, font):
""" Sets the base font for the ConsoleWidget to the specified QFont.
"""
font_metrics = QtGui.QFontMetrics(font)
self._control.setTabStopWidth(self.tab_width * font_metrics.width(' '))
self._completion_widget.setFont(font)
self._control.documen... | python | {
"resource": ""
} |
q280218 | ConsoleWidget.paste | test | def paste(self, mode=QtGui.QClipboard.Clipboard):
""" Paste the contents of the clipboard into the input region.
Parameters:
-----------
mode : QClipboard::Mode, optional [default QClipboard::Clipboard]
Controls which part of the system clipboard is used. This can be
... | python | {
"resource": ""
} |
q280219 | ConsoleWidget.print_ | test | def print_(self, printer = None):
""" Print the contents of the ConsoleWidget to the specified QPrinter.
"""
if (not printer):
printer = QtGui.QPrinter()
if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):
return
self._control.print_... | python | {
"resource": ""
} |
q280220 | ConsoleWidget.prompt_to_top | test | def prompt_to_top(self):
""" Moves the prompt to the top of the viewport.
"""
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
s... | python | {
"resource": ""
} |
q280221 | ConsoleWidget.reset_font | test | def reset_font(self):
""" Sets the font to the default fixed-width font for this platform.
"""
if sys.platform == 'win32':
# Consolas ships with Vista/Win7, fallback to Courier if needed
fallback = 'Courier'
elif sys.platform == 'darwin':
# OSX always ... | python | {
"resource": ""
} |
q280222 | ConsoleWidget._append_custom | test | def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the conten... | python | {
"resource": ""
} |
q280223 | ConsoleWidget._append_html | test | def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt) | python | {
"resource": ""
} |
q280224 | ConsoleWidget._append_html_fetching_plain_text | test | def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt) | python | {
"resource": ""
} |
q280225 | ConsoleWidget._append_plain_text | test | def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt) | python | {
"resource": ""
} |
q280226 | ConsoleWidget._clear_temporary_buffer | test | def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if... | python | {
"resource": ""
} |
q280227 | ConsoleWidget._complete_with_items | test | def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.... | python | {
"resource": ""
} |
q280228 | ConsoleWidget._fill_temporary_buffer | test | def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditB... | python | {
"resource": ""
} |
q280229 | ConsoleWidget._control_key_down | test | def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually ... | python | {
"resource": ""
} |
q280230 | ConsoleWidget._create_control | test | def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind ... | python | {
"resource": ""
} |
q280231 | ConsoleWidget._create_page_control | test | def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
c... | python | {
"resource": ""
} |
q280232 | ConsoleWidget._event_filter_page_keypress | test | def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctr... | python | {
"resource": ""
} |
q280233 | ConsoleWidget._get_block_plain_text | test | def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.K... | python | {
"resource": ""
} |
q280234 | ConsoleWidget._get_end_cursor | test | def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor | python | {
"resource": ""
} |
q280235 | ConsoleWidget._get_input_buffer_cursor_column | test | def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
... | python | {
"resource": ""
} |
q280236 | ConsoleWidget._get_input_buffer_cursor_line | test | def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
c... | python | {
"resource": ""
} |
q280237 | ConsoleWidget._get_prompt_cursor | test | def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor | python | {
"resource": ""
} |
q280238 | ConsoleWidget._get_selection_cursor | test | def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor... | python | {
"resource": ""
} |
q280239 | ConsoleWidget._insert_continuation_prompt | test | def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_... | python | {
"resource": ""
} |
q280240 | ConsoleWidget._insert_html | test | def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mod... | python | {
"resource": ""
} |
q280241 | ConsoleWidget._insert_html_fetching_plain_text | test | def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
... | python | {
"resource": ""
} |
q280242 | ConsoleWidget._insert_plain_text | test | def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in se... | python | {
"resource": ""
} |
q280243 | ConsoleWidget._keep_cursor_in_buffer | test | def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)... | python | {
"resource": ""
} |
q280244 | ConsoleWidget._keyboard_quit | test | def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = '' | python | {
"resource": ""
} |
q280245 | ConsoleWidget._page | test | def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_h... | python | {
"resource": ""
} |
q280246 | ConsoleWidget._prompt_started | test | def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
... | python | {
"resource": ""
} |
q280247 | ConsoleWidget._readline | test | def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If... | python | {
"resource": ""
} |
q280248 | ConsoleWidget._set_continuation_prompt | test | def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as format... | python | {
"resource": ""
} |
q280249 | ConsoleWidget._set_top_cursor | test | def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(curso... | python | {
"resource": ""
} |
q280250 | ConsoleWidget._show_prompt | test | def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
... | python | {
"resource": ""
} |
q280251 | ConsoleWidget._adjust_scrollbars | test | def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
... | python | {
"resource": ""
} |
q280252 | main | test | def main(args=None):
"""Entry point for pkginfo tool
"""
options, paths = _parse_options(args)
format = getattr(options, 'output', 'simple')
formatter = _FORMATTERS[format](options)
for path in paths:
meta = get_metadata(path, options.metadata_version)
if meta is None:
... | python | {
"resource": ""
} |
q280253 | ProfileDir.copy_config_file | test | def copy_config_file(self, config_file, path=None, overwrite=False):
"""Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory.
... | python | {
"resource": ""
} |
q280254 | ProfileDir.create_profile_dir_by_name | test | def create_profile_dir_by_name(cls, path, name=u'default', config=None):
"""Create a profile dir by profile name and path.
Parameters
----------
path : unicode
The path (directory) to put the profile directory in.
name : unicode
The name of the profile. ... | python | {
"resource": ""
} |
q280255 | ProfileDir.find_profile_dir_by_name | test | def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
"""Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
T... | python | {
"resource": ""
} |
q280256 | cmp_to_key | test | def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class Key(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) >... | python | {
"resource": ""
} |
q280257 | file_read | test | def file_read(filename):
"""Read a file and close it. Returns the file source."""
fobj = open(filename,'r');
source = fobj.read();
fobj.close()
return source | python | {
"resource": ""
} |
q280258 | raw_input_multi | test | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
"""Take multiple lines of input.
A list with each line of input as a separate element is returned when a
termination string is entered (defaults to a single '.'). Input can also
terminate via EOF (^D in Unix, ^Z-RET in Windows)... | python | {
"resource": ""
} |
q280259 | temp_pyfile | test | def temp_pyfile(src, ext='.py'):
"""Make a temporary python file, return filename and filehandle.
Parameters
----------
src : string or list of strings (no need for ending newlines if list)
Source code to be written to the file.
ext : optional, string
Extension for the generated file.
... | python | {
"resource": ""
} |
q280260 | Tee.close | test | def close(self):
"""Close the file and restore the channel."""
self.flush()
setattr(sys, self.channel, self.ostream)
self.file.close()
self._closed = True | python | {
"resource": ""
} |
q280261 | Tee.write | test | def write(self, data):
"""Write data to both channels."""
self.file.write(data)
self.ostream.write(data)
self.ostream.flush() | python | {
"resource": ""
} |
q280262 | HeartMonitor.add_new_heart_handler | test | def add_new_heart_handler(self, handler):
"""add a new handler for new hearts"""
self.log.debug("heartbeat::new_heart_handler: %s", handler)
self._new_handlers.add(handler) | python | {
"resource": ""
} |
q280263 | HeartMonitor.add_heart_failure_handler | test | def add_heart_failure_handler(self, handler):
"""add a new handler for heart failure"""
self.log.debug("heartbeat::new heart failure handler: %s", handler)
self._failure_handlers.add(handler) | python | {
"resource": ""
} |
q280264 | HeartMonitor.handle_pong | test | def handle_pong(self, msg):
"a heart just beat"
current = str_to_bytes(str(self.lifetime))
last = str_to_bytes(str(self.last_ping))
if msg[1] == current:
delta = time.time()-self.tic
# self.log.debug("heartbeat::heart %r took %.2f ms to respond"%(msg[0], 1000*delt... | python | {
"resource": ""
} |
q280265 | batch_list | test | def batch_list(sequence, batch_size, mod = 0, randomize = False):
'''
Converts a list into a list of lists with equal batch_size.
Parameters
----------
sequence : list
list of items to be placed in batches
batch_size : int
length of each sub list
mod : int
remainder ... | python | {
"resource": ""
} |
q280266 | path_to_filename | test | def path_to_filename(pathfile):
'''
Takes a path filename string and returns the split between the path and the filename
if filename is not given, filename = ''
if path is not given, path = './'
'''
path = pathfile[:pathfile.rfind('/') + 1]
if path == '':
path = './'
filename... | python | {
"resource": ""
} |
q280267 | Walk | test | def Walk(root='.', recurse=True, pattern='*'):
'''
Generator for walking a directory tree.
Starts at specified root folder, returning files that match our pattern.
Optionally will also recurse through sub-folders.
Parameters
----------
root : string (default is *'.'*)
Path for the... | python | {
"resource": ""
} |
q280268 | displayAll | test | def displayAll(elapsed, display_amt, est_end, nLoops, count, numPrints):
'''Displays time if verbose is true and count is within the display amount'''
if numPrints > nLoops:
display_amt = 1
else:
display_amt = round(nLoops / numPrints)
if count % display_amt == 0:
avg = elapse... | python | {
"resource": ""
} |
q280269 | timeUnit | test | def timeUnit(elapsed, avg, est_end):
'''calculates unit of time to display'''
minute = 60
hr = 3600
day = 86400
if elapsed <= 3 * minute:
unit_elapsed = (elapsed, "secs")
if elapsed > 3 * minute:
unit_elapsed = ((elapsed / 60), "mins")
if elapsed > 3 * hr:
unit_elaps... | python | {
"resource": ""
} |
q280270 | extract_wininst_cfg | test | def extract_wininst_cfg(dist_filename):
"""Extract configuration data from a bdist_wininst .exe
Returns a ConfigParser.RawConfigParser, or None
"""
f = open(dist_filename,'rb')
try:
endrec = zipfile._EndRecData(f)
if endrec is None:
return None
prepended = (endr... | python | {
"resource": ""
} |
q280271 | uncache_zipdir | test | def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache) | python | {
"resource": ""
} |
q280272 | nt_quote_arg | test | def nt_quote_arg(arg):
"""Quote a command line argument according to Windows parsing rules"""
result = []
needquote = False
nb = 0
needquote = (" " in arg) or ("\t" in arg)
if needquote:
result.append('"')
for c in arg:
if c == '\\':
nb += 1
elif c == '... | python | {
"resource": ""
} |
q280273 | easy_install.check_conflicts | test | def check_conflicts(self, dist):
"""Verify that there are no conflicting "old-style" packages"""
return dist # XXX temporarily disable until new strategy is stable
from imp import find_module, get_suffixes
from glob import glob
blockers = []
names = dict.fromkeys(di... | python | {
"resource": ""
} |
q280274 | easy_install._set_fetcher_options | test | def _set_fetcher_options(self, base):
"""
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
... | python | {
"resource": ""
} |
q280275 | easy_install.create_home_path | test | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.iteritems():
if path.startswith(home) and not os.path.isdir(path):
self.debug_pri... | python | {
"resource": ""
} |
q280276 | is_archive_file | test | def is_archive_file(name):
"""Return True if `name` is a considered as an archive file."""
archives = (
'.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl'
)
ext = splitext(name)[1].lower()
if ext in archives:
return True
return False | python | {
"resource": ""
} |
q280277 | mutable | test | def mutable(obj):
'''
return a mutable proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class Proxy(base_cls):
def __getattribute__(self, name):
try:
return super().__getattribute__(name)
exce... | python | {
"resource": ""
} |
q280278 | readonly | test | def readonly(obj, *, error_on_set = False):
'''
return a readonly proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class ReadonlyProxy(base_cls):
def __getattribute__(self, name):
return getattr(obj, name)
def _... | python | {
"resource": ""
} |
q280279 | new_heading_cell | test | def new_heading_cell(source=None, rendered=None, level=1, metadata=None):
"""Create a new section cell with a given integer level."""
cell = NotebookNode()
cell.cell_type = u'heading'
if source is not None:
cell.source = unicode(source)
if rendered is not None:
cell.rendered = unicod... | python | {
"resource": ""
} |
q280280 | new_metadata | test | def new_metadata(name=None, authors=None, license=None, created=None,
modified=None, gistid=None):
"""Create a new metadata node."""
metadata = NotebookNode()
if name is not None:
metadata.name = unicode(name)
if authors is not None:
metadata.authors = list(authors)
if created is... | python | {
"resource": ""
} |
q280281 | new_author | test | def new_author(name=None, email=None, affiliation=None, url=None):
"""Create a new author."""
author = NotebookNode()
if name is not None:
author.name = unicode(name)
if email is not None:
author.email = unicode(email)
if affiliation is not None:
author.affiliation = unicode(... | python | {
"resource": ""
} |
q280282 | _writable_dir | test | def _writable_dir(path):
"""Whether `path` is a directory, to which the user has write access."""
return os.path.isdir(path) and os.access(path, os.W_OK) | python | {
"resource": ""
} |
q280283 | unquote_filename | test | def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
"""
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name | python | {
"resource": ""
} |
q280284 | get_py_filename | test | def get_py_filename(name, force_win32=None):
"""Return a valid python filename in the current directory.
If the given name is not a file, it adds '.py' and searches again.
Raises IOError with an informative message if the file isn't found.
On Windows, apply Windows semantics to the filename. In partic... | python | {
"resource": ""
} |
q280285 | filefind | test | def filefind(filename, path_dirs=None):
"""Find a file by looking through a sequence of paths.
This iterates through a sequence of paths looking for a file and returns
the full, absolute path of the first occurence of the file. If no set of
path dirs is given, the filename is tested as is, after runni... | python | {
"resource": ""
} |
q280286 | get_home_dir | test | def get_home_dir(require_writable=False):
"""Return the 'home' directory, as a unicode string.
* First, check for frozen env in case of py2exe
* Otherwise, defer to os.path.expanduser('~')
See stdlib docs for how this is determined.
$HOME is first priority on *ALL* platforms.
Paramete... | python | {
"resource": ""
} |
q280287 | get_xdg_dir | test | def get_xdg_dir():
"""Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
This is only for non-OS X posix (Linux,Unix,etc.) systems.
"""
env = os.environ
if os.name == 'posix' and sys.platform != 'darwin':
# Linux, Unix, AIX, etc.
# use ~/.config if empty OR not se... | python | {
"resource": ""
} |
q280288 | get_ipython_dir | test | def get_ipython_dir():
"""Get the IPython directory for this platform and user.
This uses the logic in `get_home_dir` to find the home directory
and then adds .ipython to the end of the path.
"""
env = os.environ
pjoin = os.path.join
ipdir_def = '.ipython'
xdg_def = 'ipython'
ho... | python | {
"resource": ""
} |
q280289 | get_ipython_package_dir | test | def get_ipython_package_dir():
"""Get the base directory where IPython itself is installed."""
ipdir = os.path.dirname(IPython.__file__)
return py3compat.cast_unicode(ipdir, fs_encoding) | python | {
"resource": ""
} |
q280290 | get_ipython_module_path | test | def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPy... | python | {
"resource": ""
} |
q280291 | target_outdated | test | def target_outdated(target,deps):
"""Determine whether a target is out of date.
target_outdated(target,deps) -> 1/0
deps: list of filenames which MUST exist.
target: single filename which may or may not exist.
If target doesn't exist or is older than any file listed in deps, return
true, othe... | python | {
"resource": ""
} |
q280292 | filehash | test | def filehash(path):
"""Make an MD5 hash of a file, ignoring any differences in line
ending characters."""
with open(path, "rU") as f:
return md5(py3compat.str_to_bytes(f.read())).hexdigest() | python | {
"resource": ""
} |
q280293 | check_for_old_config | test | def check_for_old_config(ipython_dir=None):
"""Check for old config files, and present a warning if they exist.
A link to the docs of the new config is included in the message.
This should mitigate confusion with the transition to the new
config system in 0.11.
"""
if ipython_dir is None:
... | python | {
"resource": ""
} |
q280294 | update_suggestions_dictionary | test | def update_suggestions_dictionary(request, object):
"""
Updates the suggestions' dictionary for an object upon visiting its page
"""
if request.user.is_authenticated():
user = request.user
content_type = ContentType.objects.get_for_model(type(object))
try:
# Check if ... | python | {
"resource": ""
} |
q280295 | get_suggestions_with_size | test | def get_suggestions_with_size(object, size):
""" Gets a list with a certain size of suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
try:
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=... | python | {
"resource": ""
} |
q280296 | get_suggestions | test | def get_suggestions(object):
""" Gets a list of all suggestions for an object """
content_type = ContentType.objects.get_for_model(type(object))
return ObjectViewDictionary.objects.filter(
current_object_id=object.id,
current_content_type=content_type).extra(order_by=['-visits']) | python | {
"resource": ""
} |
q280297 | path.relpath | test | def relpath(self):
""" Return this path as a relative path,
based from the current working directory.
"""
cwd = self.__class__(os.getcwdu())
return cwd.relpathto(self) | python | {
"resource": ""
} |
q280298 | path.glob | test | def glob(self, pattern):
""" Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories.
"""
cls = sel... | python | {
"resource": ""
} |
q280299 | path.lines | test | def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.