_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 31 13.1k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q280000 | interpret_distro_name | test | def interpret_distro_name(location, basename, metadata,
py_version=None, precedence=SOURCE_DIST, platform=None
):
"""Generate alternative interpretations of a source distro name
Note: if `location` is a filesystem filename, you should call
``pkg_resources.normalize_path()`` on it before passing it to this
routine!
"""
# Generate alternative interpretations of a source distro name
# Because some packages are ambiguous as to name/versions split
# e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
# So, we generate each possible interepretation (e.g. "adns, python-1.1.0"
# "adns-python, 1.1.0", and "adns-python-1.1.0, no version"). In practice,
# the spurious interpretations should be ignored, because in the event
# there's also an "adns" package, the spurious "python-1.1.0" version will
# compare lower than any numeric version number, and is therefore unlikely
# to match a request for it. It's still a potential problem, though, and
| python | {
"resource": ""
} |
q280001 | open_with_auth | test | def open_with_auth(url):
"""Open a urllib2 request, handling HTTP authentication"""
scheme, netloc, path, params, query, frag = urlparse.urlparse(url)
# Double scheme does not raise on Mac OS X as revealed by a
# failing test. We would expect "nonnumeric port". Refs #20.
if netloc.endswith(':'):
raise httplib.InvalidURL("nonnumeric port: ''")
if scheme in ('http', 'https'):
auth, host = urllib2.splituser(netloc)
else:
auth = None
if auth:
auth = "Basic " + _encode_auth(auth)
new_url = urlparse.urlunparse((scheme,host,path,params,query,frag))
request = urllib2.Request(new_url)
request.add_header("Authorization", auth)
else:
request = urllib2.Request(url) | python | {
"resource": ""
} |
q280002 | PackageIndex.fetch_distribution | test | def fetch_distribution(self,
requirement, tmpdir, force_scan=False, source=False, develop_ok=False,
local_index=None
):
"""Obtain a distribution suitable for fulfilling `requirement`
`requirement` must be a ``pkg_resources.Requirement`` instance.
If necessary, or if the `force_scan` flag is set, the requirement is
searched for in the (online) package index as well as the locally
installed packages. If a distribution matching `requirement` is found,
the returned distribution's ``location`` is the value you would have
gotten from calling the ``download()`` method with the matching
distribution's URL or filename. If no matching distribution is found,
``None`` is returned.
If the `source` flag is set, only source distributions and source
checkout links will be considered. Unless the `develop_ok` flag is
set, development and system eggs (i.e., those using the ``.egg-info``
format) will be ignored.
"""
# process a Requirement
self.info("Searching for %s", requirement)
skipped = {}
dist = None
def find(req, env=None):
if env is None:
env = self
# Find a matching distribution; may be called more than once
for dist in env[req.key]:
if dist.precedence==DEVELOP_DIST and not develop_ok:
if dist not in skipped:
self.warn("Skipping development or system egg: %s",dist)
skipped[dist] = 1
continue
if dist in req and (dist.precedence<=SOURCE_DIST or not source):
| python | {
"resource": ""
} |
q280003 | get_parent | test | def get_parent(obj):
'''
get parent from obj.
'''
names = obj.__qualname__.split('.')[:-1]
if '<locals>' in names: # locals function
raise ValueError('cannot get parent from locals object.')
| python | {
"resource": ""
} |
q280004 | EnginePUBHandler.root_topic | test | def root_topic(self):
"""this is a property, in case the handler is created
before the engine gets registered with | python | {
"resource": ""
} |
q280005 | render_template | test | def render_template(content, context):
""" renders context aware | python | {
"resource": ""
} |
q280006 | Capture.configure | test | def configure(self, options, conf):
"""Configure plugin. Plugin is enabled by default.
"""
| python | {
"resource": ""
} |
q280007 | Capture.formatError | test | def formatError(self, test, err):
"""Add captured output to error report.
"""
test.capturedOutput = output = self.buffer
self._buf = None
if not output:
# Don't return None as that will prevent other
# formatters from | python | {
"resource": ""
} |
q280008 | splitBy | test | def splitBy(data, num):
""" Turn a list to list of list """
return [data[i:i | python | {
"resource": ""
} |
q280009 | convert_to_this_nbformat | test | def convert_to_this_nbformat(nb, orig_version=2, orig_minor=0):
"""Convert a notebook to the v3 format.
Parameters
----------
nb : NotebookNode
The Python representation of the notebook to convert.
orig_version : int
The original version of the notebook to convert.
orig_minor : int
The original minor version of the notebook to convert (only relevant for v >= 3).
"""
if orig_version == 1:
nb = v2.convert_to_this_nbformat(nb)
orig_version = 2
if orig_version == 2:
# Mark the original nbformat so consumers know it has been converted.
nb.nbformat | python | {
"resource": ""
} |
q280010 | hex_to_rgb | test | def hex_to_rgb(color):
"""Convert a hex color to rgb integer tuple."""
if color.startswith('#'):
color = color[1:]
if len(color) == 3:
color = ''.join([c*2 for c in color])
if len(color) != 6:
return False
try:
| python | {
"resource": ""
} |
q280011 | get_colors | test | def get_colors(stylename):
"""Construct the keys to be used building the base stylesheet
from a templatee."""
style = get_style_by_name(stylename)
fgcolor = style.style_for_token(Token.Text)['color'] or ''
if len(fgcolor) in (3,6):
| python | {
"resource": ""
} |
q280012 | get_font | test | def get_font(family, fallback=None):
"""Return a font of the requested family, using fallback as alternative.
If a fallback is provided, it is used in case the requested family isn't
found. If no fallback is given, no alternative is chosen and Qt's internal
algorithms may automatically choose a fallback font.
Parameters
----------
family : str
A font name.
fallback : str
A font name.
Returns
-------
font : QFont object
"""
font = | python | {
"resource": ""
} |
q280013 | IPythonWidget._handle_execute_reply | test | def _handle_execute_reply(self, msg):
""" Reimplemented to support prompt requests.
"""
msg_id = msg['parent_header'].get('msg_id')
info = self._request_info['execute'].get(msg_id)
if info and info.kind == 'prompt':
number = msg['content']['execution_count'] + 1
| python | {
"resource": ""
} |
q280014 | IPythonWidget._handle_history_reply | test | def _handle_history_reply(self, msg):
""" Implemented to handle history tail replies, which are only supported
by the IPython kernel.
"""
content = msg['content']
if 'history' not in content:
self.log.error("History request failed: %r"%content)
if content.get('status', '') == 'aborted' and \
not self._retrying_history_request:
# a *different* action caused this request to be aborted, so
# we should try again.
self.log.error("Retrying aborted history request")
# prevent multiple retries of aborted requests:
self._retrying_history_request = True
# wait out the kernel's queue flush, which is currently timed at 0.1s
time.sleep(0.25)
self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000)
else:
self._retrying_history_request = False
| python | {
"resource": ""
} |
q280015 | IPythonWidget._handle_pyout | test | def _handle_pyout(self, msg):
""" Reimplemented for IPython-style "display hook".
"""
self.log.debug("pyout: %s", msg.get('content', ''))
if not self._hidden and self._is_from_this_session(msg):
content = msg['content']
prompt_number = content.get('execution_count', 0)
data = content['data']
if data.has_key('text/html'):
self._append_plain_text(self.output_sep, True)
self._append_html(self._make_out_prompt(prompt_number), True)
html = data['text/html']
self._append_plain_text('\n', True)
self._append_html(html + self.output_sep2, True)
elif data.has_key('text/plain'):
| python | {
"resource": ""
} |
q280016 | IPythonWidget._handle_display_data | test | def _handle_display_data(self, msg):
""" The base handler for the ``display_data`` message.
"""
self.log.debug("display: %s", msg.get('content', ''))
# For now, we don't display data from other frontends, but we
# eventually will as this allows all frontends to monitor the display
# data. But we need to figure out how to handle this in the GUI.
if not self._hidden and self._is_from_this_session(msg):
source = msg['content']['source']
data = msg['content']['data']
metadata = msg['content']['metadata']
# In the regular IPythonWidget, we simply print the plain text
| python | {
"resource": ""
} |
q280017 | IPythonWidget._started_channels | test | def _started_channels(self):
"""Reimplemented to make a history request and load %guiref."""
super(IPythonWidget, self)._started_channels()
self._load_guiref_magic()
| python | {
"resource": ""
} |
q280018 | IPythonWidget.execute_file | test | def execute_file(self, path, hidden=False):
""" Reimplemented to use the 'run' magic.
"""
# Use forward slashes on Windows to avoid escaping each separator.
if sys.platform == 'win32':
path = os.path.normpath(path).replace('\\', '/')
# Perhaps we should not be using %run directly, but while we
# are, it is necessary to quote or escape filenames containing spaces
# or quotes.
# In earlier code here, to minimize escaping, we sometimes quoted the
# filename with single quotes. But to do this, this code must be
# platform-aware, because run uses shlex rather than python string
# parsing, so that:
# * In Win: single quotes can be used in the filename | python | {
"resource": ""
} |
q280019 | IPythonWidget._process_execute_error | test | def _process_execute_error(self, msg):
""" Reimplemented for IPython-style traceback formatting.
"""
content = msg['content']
traceback = '\n'.join(content['traceback']) + '\n'
if False:
# FIXME: For now, tracebacks come as plain text, so we can't use
# the html renderer yet. Once we refactor ultratb to produce
# properly styled tracebacks, this branch should be the default
traceback = traceback.replace(' ', ' ')
traceback = traceback.replace('\n', '<br/>')
ename = content['ename'] | python | {
"resource": ""
} |
q280020 | IPythonWidget._process_execute_payload | test | def _process_execute_payload(self, item):
""" Reimplemented to dispatch payloads to handler methods.
"""
handler = self._payload_handlers.get(item['source'])
| python | {
"resource": ""
} |
q280021 | IPythonWidget.set_default_style | test | def set_default_style(self, colors='lightbg'):
""" Sets the widget style to the class defaults.
Parameters:
-----------
colors : str, optional (default lightbg)
Whether to use the default IPython light background or dark
background or B&W style.
"""
colors = colors.lower()
if colors=='lightbg':
| python | {
"resource": ""
} |
q280022 | IPythonWidget._edit | test | def _edit(self, filename, line=None):
""" Opens a Python script for editing.
Parameters:
-----------
filename : str
A path to a local system file.
line : int, optional
A line of interest in the file.
"""
if self.custom_edit:
self.custom_edit_requested.emit(filename, line)
elif not self.editor:
self._append_plain_text('No default editor available.\n'
'Specify a GUI text editor in the `IPythonWidget.editor` '
'configurable to enable the %edit magic')
else:
try:
filename = '"%s"' % filename
if line and self.editor_line:
command = self.editor_line.format(filename=filename,
line=line)
| python | {
"resource": ""
} |
q280023 | IPythonWidget._make_in_prompt | test | def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
try:
body = self.in_prompt | python | {
"resource": ""
} |
q280024 | IPythonWidget._make_continuation_prompt | test | def _make_continuation_prompt(self, prompt):
""" Given a plain text version of an In prompt, returns an HTML
continuation prompt.
| python | {
"resource": ""
} |
q280025 | IPythonWidget._style_sheet_changed | test | def _style_sheet_changed(self):
""" Set the style sheets of the underlying widgets.
"""
self.setStyleSheet(self.style_sheet)
if self._control is not None:
self._control.document().setDefaultStyleSheet(self.style_sheet)
bg_color = self._control.palette().window().color()
| python | {
"resource": ""
} |
q280026 | IPythonWidget._syntax_style_changed | test | def _syntax_style_changed(self):
""" Set the style for the syntax highlighter.
"""
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
| python | {
"resource": ""
} |
q280027 | CloudStack._handle_response | test | async def _handle_response(self, response: aiohttp.client_reqrep.ClientResponse, await_final_result: bool) -> dict:
"""
Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
means that the API call returns just a job id. The actually expected API response is postponed and a specific
asyncJobResults API has to be polled using the job id to get the final result once the API call has been
processed.
:param response: The response returned by the aiohttp call.
:type response: aiohttp.client_reqrep.ClientResponse
:param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API
until the asynchronous API call has been processed
:type await_final_result: bool
:return: Dictionary containing the JSON response of the API call
:rtype: dict
"""
try:
data = await response.json()
except aiohttp.client_exceptions.ContentTypeError:
text = await response.text()
logging.debug('Content returned by server not of type "application/json"\n Content: {}'.format(text))
raise CloudStackClientException(message="Could not decode content. Server did not return json content!")
else:
data = self._transform_data(data)
if response.status != 200:
raise CloudStackClientException(message="Async CloudStack call failed!",
error_code=data.get("errorcode", response.status),
error_text=data.get("errortext"),
response=data)
while await_final_result and ('jobid' in data):
| python | {
"resource": ""
} |
q280028 | CloudStack._sign | test | def _sign(self, url_parameters: dict) -> dict:
"""
According to the CloudStack documentation, each request needs to be signed in order to authenticate the user
account executing the API command. The signature is generated using a combination of the api secret and a SHA-1
hash of the url parameters including the command string. In order to generate a unique identifier, the url
parameters have to be transformed to lower case and ordered alphabetically.
:param url_parameters: The url parameters of the API call including the command string
:type url_parameters: dict
:return: The url parameters including a new key, which contains the signature
:rtype: dict
"""
| python | {
"resource": ""
} |
q280029 | CloudStack._transform_data | test | def _transform_data(data: dict) -> dict:
"""
Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating
the API that originated the response. This function removes that first level from the data returned to the
caller.
:param data: Response of the API call
:type | python | {
"resource": ""
} |
q280030 | virtual_memory | test | def virtual_memory():
"""System virtual memory as a namedutple."""
mem = _psutil_bsd.get_virtual_mem()
total, free, active, inactive, wired, cached, buffers, shared = mem
| python | {
"resource": ""
} |
q280031 | get_system_cpu_times | test | def get_system_cpu_times():
"""Return system per-CPU times as a named tuple"""
| python | {
"resource": ""
} |
q280032 | Process.get_process_uids | test | def get_process_uids(self):
"""Return real, effective and saved user ids."""
real, | python | {
"resource": ""
} |
q280033 | Process.get_process_gids | test | def get_process_gids(self):
"""Return real, effective and saved group ids."""
real, | python | {
"resource": ""
} |
q280034 | Process.get_process_threads | test | def get_process_threads(self):
"""Return the number of threads belonging to the process."""
rawlist = _psutil_bsd.get_process_threads(self.pid)
retlist = []
for thread_id, utime, stime in rawlist:
| python | {
"resource": ""
} |
q280035 | Process.get_open_files | test | def get_open_files(self):
"""Return files opened by process as a list of namedtuples."""
# XXX - C implementation available on FreeBSD >= 8 only
# else fallback on lsof parser
if hasattr(_psutil_bsd, "get_process_open_files"): | python | {
"resource": ""
} |
q280036 | pkg_commit_hash | test | def pkg_commit_hash(pkg_path):
"""Get short form of commit hash given directory `pkg_path`
We get the commit hash from (in order of preference):
* IPython.utils._sysinfo.commit
* git output, if we are in a git repository
If these fail, we return a not-found placeholder tuple
Parameters
----------
pkg_path : str
directory containing package
only used for getting commit from active repo
Returns
-------
hash_from : str
Where we got the hash from - description
hash_str : str
short form of hash
"""
# Try and get commit from written commit text file
if _sysinfo.commit:
| python | {
"resource": ""
} |
q280037 | pkg_info | test | def pkg_info(pkg_path):
"""Return dict describing the context of this package
Parameters
----------
pkg_path : str
path containing __init__.py for package
Returns
-------
context : dict
with named parameters of interest
"""
src, hsh = pkg_commit_hash(pkg_path)
return dict(
ipython_version=release.version,
ipython_path=pkg_path,
| python | {
"resource": ""
} |
q280038 | sys_info | test | def sys_info():
"""Return useful information about IPython and the system, as a string.
Example
-------
In [2]: print sys_info()
{'commit_hash': '144fdae', # random
'commit_source': 'repository',
'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
| python | {
"resource": ""
} |
q280039 | _num_cpus_darwin | test | def _num_cpus_darwin():
"""Return the number of active CPUs on a Darwin | python | {
"resource": ""
} |
q280040 | num_cpus | test | def num_cpus():
"""Return the effective number of CPUs in the system as an integer.
This cross-platform function makes an attempt at finding the total number of
available CPUs in the system, as returned by various underlying system and
python calls.
If it can't find a sensible answer, it returns 1 (though an error *may* make
it return a large positive number that's actually incorrect).
"""
# Many thanks to the Parallel Python project (http://www.parallelpython.com)
# for the names of the keys we needed to look up for this function. This
# code was inspired by their equivalent function.
ncpufuncs = {'Linux':_num_cpus_unix,
'Darwin':_num_cpus_darwin,
'Windows':_num_cpus_windows,
| python | {
"resource": ""
} |
q280041 | BaseCursor.nextset | test | def nextset(self):
"""Advance to the next result set.
Returns None if there are no more result sets.
"""
if self._executed:
self.fetchall()
del self.messages[:]
db = self._get_db()
| python | {
"resource": ""
} |
q280042 | CursorUseResultMixIn.fetchone | test | def fetchone(self):
"""Fetches a single row from the cursor."""
self._check_executed()
r | python | {
"resource": ""
} |
q280043 | CursorUseResultMixIn.fetchmany | test | def fetchmany(self, size=None):
"""Fetch up to size rows from the cursor. Result set may be smaller
than size. If size is not defined, cursor.arraysize is used."""
self._check_executed()
| python | {
"resource": ""
} |
q280044 | CursorUseResultMixIn.fetchall | test | def fetchall(self):
"""Fetchs all available rows from the cursor."""
self._check_executed()
r = self._fetch_row(0)
| python | {
"resource": ""
} |
q280045 | connect | test | def connect(com, peers, tree, pub_url, root_id):
"""this function will be called on the engines"""
| python | {
"resource": ""
} |
q280046 | reads_json | test | def reads_json(s, **kwargs):
"""Read a JSON notebook from a string and return the NotebookNode object."""
nbf, minor, d = parse_json(s, **kwargs)
if nbf == 1:
nb = v1.to_notebook_json(d, **kwargs)
nb = v3.convert_to_this_nbformat(nb, orig_version=1)
elif nbf == 2:
nb = v2.to_notebook_json(d, **kwargs)
nb = v3.convert_to_this_nbformat(nb, orig_version=2)
| python | {
"resource": ""
} |
q280047 | reads_py | test | def reads_py(s, **kwargs):
"""Read a .py notebook from a string and return the NotebookNode object."""
nbf, nbm, s = parse_py(s, **kwargs)
if nbf == 2:
nb = v2.to_notebook_py(s, **kwargs)
elif nbf == 3:
| python | {
"resource": ""
} |
q280048 | reads | test | def reads(s, format, **kwargs):
"""Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
returned will always be in the current version's format.
Parameters
----------
s : unicode
The raw unicode string to read the | python | {
"resource": ""
} |
q280049 | writes | test | def writes(nb, format, **kwargs):
"""Write a notebook to a string in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
| python | {
"resource": ""
} |
q280050 | write | test | def write(nb, fp, format, **kwargs):
"""Write a notebook to a file in a given format in the current nbformat version.
This function always writes the notebook in the current nbformat version.
Parameters
----------
nb : NotebookNode
The notebook to write.
fp : file
Any file-like | python | {
"resource": ""
} |
q280051 | _convert_to_metadata | test | def _convert_to_metadata():
"""Convert to a notebook having notebook metadata."""
import glob
for fname in glob.glob('*.ipynb'):
print('Converting file:',fname)
with open(fname,'r') as f:
nb = read(f,u'json')
md = new_metadata()
| python | {
"resource": ""
} |
q280052 | Box.load_from_dict | test | def load_from_dict(self, src: dict, key):
'''
try load value from dict.
if key is not exists, mark as state unset.
'''
| python | {
"resource": ""
} |
q280053 | Selector.matches | test | def matches(self, name):
"""Does the name match my requirements?
To match, a name must match config.testMatch OR config.include
and it must not match config.exclude
"""
return ((self.match.search(name)
or (self.include and
filter(None,
[inc.search(name) for inc | python | {
"resource": ""
} |
q280054 | Selector.wantClass | test | def wantClass(self, cls):
"""Is the class a wanted test class?
A class must be a unittest.TestCase subclass, or match test name
requirements. Classes that start with _ are always excluded.
"""
declared = getattr(cls, '__test__', None)
if declared is not None:
wanted = declared
else:
wanted = (not cls.__name__.startswith('_')
and (issubclass(cls, unittest.TestCase)
| python | {
"resource": ""
} |
q280055 | Selector.wantDirectory | test | def wantDirectory(self, dirname):
"""Is the directory a wanted test directory?
All package directories match, so long as they do not match exclude.
All other directories must match test requirements.
"""
tail = op_basename(dirname)
if ispackage(dirname):
wanted = (not self.exclude
or not filter(None,
[exc.search(tail) for exc in self.exclude]
))
else:
wanted = (self.matches(tail)
or (self.config.srcDirs
| python | {
"resource": ""
} |
q280056 | Selector.wantFile | test | def wantFile(self, file):
"""Is the file a wanted test file?
The file must be a python source file and match testMatch or
include, and not match exclude. Files that match ignore are *never*
wanted, regardless of plugin, testMatch, include or exclude settings.
"""
# never, ever load files that match anything in ignore
# (.* _* and *setup*.py by default)
base = op_basename(file)
ignore_matches = [ ignore_this for ignore_this in self.ignoreFiles
| python | {
"resource": ""
} |
q280057 | Selector.wantFunction | test | def wantFunction(self, function):
"""Is the function a test function?
"""
try:
if hasattr(function, 'compat_func_name'):
funcname = function.compat_func_name
else:
funcname = function.__name__
except AttributeError:
# not a function
return False
declared = getattr(function, '__test__', None)
if declared is not None:
wanted = declared
| python | {
"resource": ""
} |
q280058 | Selector.wantMethod | test | def wantMethod(self, method):
"""Is the method a test method?
"""
try:
method_name = method.__name__
except AttributeError:
# not a method
return False
if method_name.startswith('_'):
# never collect 'private' methods
return False
declared = getattr(method, '__test__', None)
if declared is not None:
wanted = declared
else:
| python | {
"resource": ""
} |
q280059 | Selector.wantModule | test | def wantModule(self, module):
"""Is the module a test module?
The tail of the module name must match test requirements. One exception:
we always want __main__.
"""
declared = getattr(module, '__test__', None)
if declared is not None: | python | {
"resource": ""
} |
q280060 | _file_lines | test | def _file_lines(fname):
"""Return the contents of a named file as a list of lines.
This function never raises an IOError exception: if the file can't be | python | {
"resource": ""
} |
q280061 | Pdb.list_command_pydb | test | def list_command_pydb(self, arg):
"""List command to use if we have a newer pydb installed"""
filename, first, last = OldPdb.parse_list_cmd(self, arg)
| python | {
"resource": ""
} |
q280062 | Pdb.print_list_lines | test | def print_list_lines(self, filename, first, last):
"""The printing (as opposed to the parsing part of a 'list'
command."""
try:
Colors = self.color_scheme_table.active_colors
ColorsNormal = Colors.Normal
tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
| python | {
"resource": ""
} |
q280063 | Pdb.do_pdef | test | def do_pdef(self, arg):
"""The debugger interface to magic_pdef"""
namespaces = [('Locals', self.curframe.f_locals),
| python | {
"resource": ""
} |
q280064 | conversion_factor | test | def conversion_factor(from_symbol, to_symbol, date):
"""
Generates a multiplying factor used to convert two currencies
"""
from_currency = Currency.objects.get(symbol=from_symbol)
try:
from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price
except CurrencyPrice.DoesNotExist:
print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date))
return None
to_currency = | python | {
"resource": ""
} |
q280065 | convert_currency | test | def convert_currency(from_symbol, to_symbol, value, date):
"""
Converts an amount of money from one currency to another on a specified date.
"""
if from_symbol == to_symbol:
return value
factor = conversion_factor(from_symbol, to_symbol, date)
if type(value) == float:
output = value * float(factor)
elif type(value) == Decimal:
| python | {
"resource": ""
} |
q280066 | Currency.compute_return | test | def compute_return(self, start_date, end_date, rate="MID"):
"""
Compute the return of the currency between two dates
"""
if rate not in ["MID", "ASK", "BID"]:
raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate))
if end_date <= start_date:
raise ValueError("End date must be on or | python | {
"resource": ""
} |
q280067 | get_stream_enc | test | def get_stream_enc(stream, default=None):
"""Return the given stream's encoding or a default.
There are cases where sys.std* might not actually be a stream, so
check for the encoding attribute prior to returning it, and return
a default if it doesn't exist or | python | {
"resource": ""
} |
q280068 | getdefaultencoding | test | def getdefaultencoding():
"""Return IPython's guess for the default encoding for bytes as text.
Asks for stdin.encoding first, to match the calling Terminal, but that
is often None for subprocesses. Fall back on locale.getpreferredencoding()
which should be a sensible platform default (that respects LANG environment),
| python | {
"resource": ""
} |
q280069 | KernelApp.write_connection_file | test | def write_connection_file(self):
"""write connection info to JSON file"""
if os.path.basename(self.connection_file) == self.connection_file:
cf = os.path.join(self.profile_dir.security_dir, self.connection_file)
else:
cf = self.connection_file
write_connection_file(cf, ip=self.ip, key=self.session.key, | python | {
"resource": ""
} |
q280070 | KernelApp.init_heartbeat | test | def init_heartbeat(self):
"""start the heart beating"""
# heartbeat doesn't share context, because it mustn't be blocked
# by the GIL, which is accessed by libzmq when freeing zero-copy messages
hb_ctx = zmq.Context()
self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port))
self.hb_port = self.heartbeat.port
self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port)
| python | {
"resource": ""
} |
q280071 | KernelApp.log_connection_info | test | def log_connection_info(self):
"""display connection info, and store ports"""
basename = os.path.basename(self.connection_file)
if basename == self.connection_file or \
os.path.dirname(self.connection_file) == self.profile_dir.security_dir:
# use shortname
tail = basename
if self.profile != 'default':
tail += " --profile %s" % self.profile
| python | {
"resource": ""
} |
q280072 | KernelApp.init_session | test | def init_session(self):
"""create our session object"""
default_secure(self.config)
| python | {
"resource": ""
} |
q280073 | KernelApp.init_io | test | def init_io(self):
"""Redirect input streams and set a display hook."""
if self.outstream_class:
outstream_factory = import_item(str(self.outstream_class))
sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout')
sys.stderr = outstream_factory(self.session, self.iopub_socket, | python | {
"resource": ""
} |
q280074 | KernelApp.init_kernel | test | def init_kernel(self):
"""Create the Kernel object itself"""
kernel_factory = import_item(str(self.kernel_class))
self.kernel = kernel_factory(config=self.config, session=self.session,
shell_socket=self.shell_socket,
iopub_socket=self.iopub_socket,
| python | {
"resource": ""
} |
q280075 | EngineFactory.init_connector | test | def init_connector(self):
"""construct connection function, which handles tunnels."""
self.using_ssh = bool(self.sshkey or self.sshserver)
if self.sshkey and not self.sshserver:
# We are using ssh directly to the controller, tunneling localhost to localhost
self.sshserver = self.url.split('://')[1].split(':')[0]
if self.using_ssh:
if tunnel.try_passwordless_ssh(self.sshserver, self.sshkey, self.paramiko):
password=False
else:
password = getpass("SSH Password for %s: "%self.sshserver)
else:
password = False
def connect(s, url):
url = disambiguate_url(url, self.location)
if self.using_ssh:
self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver))
return tunnel.tunnel_connection(s, url, self.sshserver,
keyfile=self.sshkey, paramiko=self.paramiko,
password=password,
| python | {
"resource": ""
} |
q280076 | EngineFactory.register | test | def register(self):
"""send the registration_request"""
self.log.info("Registering with controller at %s"%self.url)
ctx = self.context
connect,maybe_tunnel = self.init_connector()
reg = ctx.socket(zmq.DEALER)
reg.setsockopt(zmq.IDENTITY, self.bident)
connect(reg, self.url)
self.registrar = zmqstream.ZMQStream(reg, self.loop)
content = dict(queue=self.ident, | python | {
"resource": ""
} |
q280077 | html_to_text | test | def html_to_text(content):
""" Converts html content to plain text """
text = None
h2t = html2text.HTML2Text() | python | {
"resource": ""
} |
q280078 | md_to_text | test | def md_to_text(content):
""" Converts markdown content to text """
text = None
html = markdown.markdown(content) | python | {
"resource": ""
} |
q280079 | domain_to_fqdn | test | def domain_to_fqdn(domain, proto=None):
""" returns a fully qualified app domain name """
from .generic | python | {
"resource": ""
} |
q280080 | NoseExclude.options | test | def options(self, parser, env=os.environ):
"""Define the command line options for the plugin."""
super(NoseExclude, self).options(parser, env)
env_dirs = []
if 'NOSE_EXCLUDE_DIRS' in env:
exclude_dirs = env.get('NOSE_EXCLUDE_DIRS','')
env_dirs.extend(exclude_dirs.split(';'))
parser.add_option(
"--exclude-dir", action="append",
dest="exclude_dirs",
default=env_dirs,
help="Directory to exclude from test discovery. \
Path can be relative to current working directory \
or an absolute path. May be specified multiple \
| python | {
"resource": ""
} |
q280081 | NoseExclude.configure | test | def configure(self, options, conf):
"""Configure plugin based on command line options"""
super(NoseExclude, self).configure(options, conf)
self.exclude_dirs = {}
# preload directories from file
if options.exclude_dir_file:
if not options.exclude_dirs:
options.exclude_dirs = []
new_dirs = self._load_from_file(options.exclude_dir_file)
options.exclude_dirs.extend(new_dirs)
if not options.exclude_dirs:
self.enabled = False
return
self.enabled = True
root = os.getcwd()
log.debug('cwd: %s' % root)
# | python | {
"resource": ""
} |
q280082 | NoseExclude.wantDirectory | test | def wantDirectory(self, dirname):
"""Check if directory is eligible for test discovery"""
if dirname in self.exclude_dirs:
| python | {
"resource": ""
} |
q280083 | build_ext.links_to_dynamic | test | def links_to_dynamic(self, ext):
"""Return true if 'ext' links to a dynamic lib in the same package"""
# XXX this should check to ensure the lib is actually being built
# XXX as dynamic, and not just using a locally-found version or a
# XXX static-compiled version
libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
| python | {
"resource": ""
} |
q280084 | call_each | test | def call_each(funcs: list, *args, **kwargs):
'''
call each func from func list.
return the last func value or None if func list is empty.
'''
| python | {
"resource": ""
} |
q280085 | call_each_reversed | test | def call_each_reversed(funcs: list, *args, **kwargs):
'''
call each func from reversed func list.
return the last func value or None if func list is empty.
'''
| python | {
"resource": ""
} |
q280086 | CallableList.append_func | test | def append_func(self, func, *args, **kwargs):
'''
append func with given arguments and keywords.
'''
| python | {
"resource": ""
} |
q280087 | CallableList.insert_func | test | def insert_func(self, index, func, *args, **kwargs):
'''
insert func with given arguments and keywords.
'''
| python | {
"resource": ""
} |
q280088 | PrettyHelpFormatter.format_usage | test | def format_usage(self, usage):
"""
ensure there is only one newline between usage and the first heading
if there is no description
"""
msg = 'Usage: %s' % | python | {
"resource": ""
} |
q280089 | BaseParallelApplication.initialize | test | def initialize(self, argv=None):
"""initialize the app"""
| python | {
"resource": ""
} |
q280090 | BaseParallelApplication.write_pid_file | test | def write_pid_file(self, overwrite=False):
"""Create a .pid file in the pid_dir with my pid.
This must be called after pre_construct, which sets `self.pid_dir`.
This raises :exc:`PIDFileError` if the pid file exists already.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if os.path.isfile(pid_file):
pid = self.get_pid_from_file()
if not overwrite:
raise PIDFileError(
| python | {
"resource": ""
} |
q280091 | BaseParallelApplication.remove_pid_file | test | def remove_pid_file(self):
"""Remove the pid file.
This should be called at shutdown by registering a callback with
:func:`reactor.addSystemEventTrigger`. This needs to return
``None``.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if os.path.isfile(pid_file):
| python | {
"resource": ""
} |
q280092 | BaseParallelApplication.get_pid_from_file | test | def get_pid_from_file(self):
"""Get the pid from the pid file.
If the pid file doesn't exist a :exc:`PIDFileError` is raised.
"""
pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
if os.path.isfile(pid_file):
with open(pid_file, 'r') as f:
s = f.read().strip()
try:
| python | {
"resource": ""
} |
q280093 | construct_parser | test | def construct_parser(magic_func):
""" Construct an argument parser using the function decorations.
"""
kwds = getattr(magic_func, 'argcmd_kwds', {})
if 'description' not in kwds:
kwds['description'] = getattr(magic_func, '__doc__', None)
arg_name = real_name(magic_func)
parser = MagicArgumentParser(arg_name, **kwds)
# Reverse the list of decorators in order to apply them in the
# order in which they appear in the source.
group = None
for deco in magic_func.decorators[::-1]:
result = deco.add_to_parser(parser, group)
if result is not None:
group = result
| python | {
"resource": ""
} |
q280094 | real_name | test | def real_name(magic_func):
""" Find the real name of the magic.
"""
magic_name = magic_func.__name__
| python | {
"resource": ""
} |
q280095 | FrontendHighlighter.highlightBlock | test | def highlightBlock(self, string):
""" Highlight a block of text. Reimplemented to highlight selectively.
"""
if not self.highlighting_on:
return
# The input to this function is a unicode string that may contain
# paragraph break characters, non-breaking spaces, etc. Here we acquire
# the string as plain text so we can compare it.
current_block = self.currentBlock()
string = self._frontend._get_block_plain_text(current_block)
# Decide whether to check for the regular or continuation prompt.
if current_block.contains(self._frontend._prompt_pos):
prompt = self._frontend._prompt
else:
| python | {
"resource": ""
} |
q280096 | FrontendHighlighter.rehighlightBlock | test | def rehighlightBlock(self, block):
""" Reimplemented to temporarily enable highlighting if disabled.
"""
| python | {
"resource": ""
} |
q280097 | FrontendHighlighter.setFormat | test | def setFormat(self, start, count, format):
""" Reimplemented to highlight selectively.
"""
start | python | {
"resource": ""
} |
q280098 | FrontendWidget.copy | test | def copy(self):
""" Copy the currently selected text to the clipboard, removing prompts.
"""
if self._page_control is not None and self._page_control.hasFocus():
self._page_control.copy()
elif self._control.hasFocus():
text = self._control.textCursor().selection().toPlainText()
if text:
| python | {
"resource": ""
} |
q280099 | FrontendWidget._execute | test | def _execute(self, source, hidden):
""" Execute 'source'. If 'hidden', do not show any output.
See parent class :meth:`execute` docstring for full details.
"""
msg_id = self.kernel_manager.shell_channel.execute(source, hidden) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.