id_within_dataset
int64 46
2.71M
| snippet
stringlengths 63
481k
| tokens
sequencelengths 20
15.6k
| language
stringclasses 2
values | nl
stringlengths 1
32.4k
| is_duplicated
bool 2
classes |
---|---|---|---|---|---|
2,700,504 | 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
read, it simply returns an empty list."""
try:
outfile = open(fname)
except IOError:
return []
else:
out = outfile.readlines()
outfile.close()
return out | [
"def",
"_file_lines",
"(",
"fname",
")",
":",
"try",
":",
"outfile",
"=",
"open",
"(",
"fname",
")",
"except",
"IOError",
":",
"return",
"[",
"]",
"else",
":",
"out",
"=",
"outfile",
".",
"readlines",
"(",
")",
"outfile",
".",
"close",
"(",
")",
"return",
"out"
] | python | 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
read, it simply returns an empty list. | true |
2,700,565 | def profile_fields(user):
"""
Returns profile fields as a dict for the given user. Used in the
profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED``
setting is set to ``True``, and also in the account approval emails
sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is set to ``True``.
"""
fields = OrderedDict()
try:
profile = get_profile_for_user(user)
user_fieldname = get_profile_user_fieldname()
exclude = tuple(settings.ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS)
for field in profile._meta.fields:
if field.name not in ("id", user_fieldname) + exclude:
value = getattr(profile, field.name)
fields[field.verbose_name.title()] = value
except ProfileNotConfigured:
pass
return list(fields.items()) | [
"def",
"profile_fields",
"(",
"user",
")",
":",
"fields",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"profile",
"=",
"get_profile_for_user",
"(",
"user",
")",
"user_fieldname",
"=",
"get_profile_user_fieldname",
"(",
")",
"exclude",
"=",
"tuple",
"(",
"settings",
".",
"ACCOUNTS_PROFILE_FORM_EXCLUDE_FIELDS",
")",
"for",
"field",
"in",
"profile",
".",
"_meta",
".",
"fields",
":",
"if",
"field",
".",
"name",
"not",
"in",
"(",
"\"id\"",
",",
"user_fieldname",
")",
"+",
"exclude",
":",
"value",
"=",
"getattr",
"(",
"profile",
",",
"field",
".",
"name",
")",
"fields",
"[",
"field",
".",
"verbose_name",
".",
"title",
"(",
")",
"]",
"=",
"value",
"except",
"ProfileNotConfigured",
":",
"pass",
"return",
"list",
"(",
"fields",
".",
"items",
"(",
")",
")"
] | python | Returns profile fields as a dict for the given user. Used in the
profile view template when the ``ACCOUNTS_PROFILE_VIEWS_ENABLED``
setting is set to ``True``, and also in the account approval emails
sent to administrators when the ``ACCOUNTS_APPROVAL_REQUIRED``
setting is set to ``True``. | true |
2,700,579 | 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 evaluates as False. `default'
is None if not provided.
"""
if not hasattr(stream, 'encoding') or not stream.encoding:
return default
else:
return stream.encoding | [
"def",
"get_stream_enc",
"(",
"stream",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"hasattr",
"(",
"stream",
",",
"'encoding'",
")",
"or",
"not",
"stream",
".",
"encoding",
":",
"return",
"default",
"else",
":",
"return",
"stream",
".",
"encoding"
] | python | 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 evaluates as False. `default'
is None if not provided. | true |
2,700,855 | def base_concrete_model(abstract, model):
"""
Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct concrete model.
Consider the following::
class Abstract(models.Model)
class Meta:
abstract = True
def concrete(self):
return base_concrete_model(Abstract, self)
class Super(Abstract):
pass
class Sub(Super):
pass
sub = Sub.objects.create()
sub.concrete() # returns Super
In actual yacms usage, this allows methods in the ``Displayable`` and
``Orderable`` abstract models to access the ``Page`` instance when
instances of custom content types, (eg: models that inherit from ``Page``)
need to query the ``Page`` model to determine correct values for ``slug``
and ``_order`` which are only relevant in the context of the ``Page``
model and not the model of the custom content type.
"""
if hasattr(model, 'objects'):
# "model" is a model class
return (model if model._meta.abstract else
_base_concrete_model(abstract, model))
# "model" is a model instance
return (
_base_concrete_model(abstract, model.__class__) or
model.__class__) | [
"def",
"base_concrete_model",
"(",
"abstract",
",",
"model",
")",
":",
"if",
"hasattr",
"(",
"model",
",",
"'objects'",
")",
":",
"return",
"(",
"model",
"if",
"model",
".",
"_meta",
".",
"abstract",
"else",
"_base_concrete_model",
"(",
"abstract",
",",
"model",
")",
")",
"return",
"(",
"_base_concrete_model",
"(",
"abstract",
",",
"model",
".",
"__class__",
")",
"or",
"model",
".",
"__class__",
")"
] | python | Used in methods of abstract models to find the super-most concrete
(non abstract) model in the inheritance chain that inherits from the
given abstract model. This is so the methods in the abstract model can
query data consistently across the correct concrete model.
Consider the following::
class Abstract(models.Model)
class Meta:
abstract = True
def concrete(self):
return base_concrete_model(Abstract, self)
class Super(Abstract):
pass
class Sub(Super):
pass
sub = Sub.objects.create()
sub.concrete() # returns Super
In actual yacms usage, this allows methods in the ``Displayable`` and
``Orderable`` abstract models to access the ``Page`` instance when
instances of custom content types, (eg: models that inherit from ``Page``)
need to query the ``Page`` model to determine correct values for ``slug``
and ``_order`` which are only relevant in the context of the ``Page``
model and not the model of the custom content type. | true |
2,700,856 | def upload_to(field_path, default):
"""
Used as the ``upload_to`` arg for file fields - allows for custom
handlers to be implemented on a per field basis defined by the
``UPLOAD_TO_HANDLERS`` setting.
"""
from yacms.conf import settings
for k, v in settings.UPLOAD_TO_HANDLERS.items():
if k.lower() == field_path.lower():
return import_dotted_path(v)
return default | [
"def",
"upload_to",
"(",
"field_path",
",",
"default",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"for",
"k",
",",
"v",
"in",
"settings",
".",
"UPLOAD_TO_HANDLERS",
".",
"items",
"(",
")",
":",
"if",
"k",
".",
"lower",
"(",
")",
"==",
"field_path",
".",
"lower",
"(",
")",
":",
"return",
"import_dotted_path",
"(",
"v",
")",
"return",
"default"
] | python | Used as the ``upload_to`` arg for file fields - allows for custom
handlers to be implemented on a per field basis defined by the
``UPLOAD_TO_HANDLERS`` setting. | true |
2,701,055 | def get_valid_filename(s):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = s.strip().replace(" ", "_")
return re.sub(r"(?u)[^-\w.]", "", s) | [
"def",
"get_valid_filename",
"(",
"s",
")",
":",
"s",
"=",
"s",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
"return",
"re",
".",
"sub",
"(",
"r\"(?u)[^-\\w.]\"",
",",
"\"\"",
",",
"s",
")"
] | python | Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg' | true |
2,701,190 | def get_timestamp(d):
"""
Returns a UTC timestamp for a C{datetime.datetime} object.
@type d: C{datetime.datetime}
@return: UTC timestamp.
@rtype: C{float}
@see: Inspiration taken from the U{Intertwingly blog
<http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}.
"""
if isinstance(d, datetime.date) and not isinstance(d, datetime.datetime):
d = datetime.datetime.combine(d, datetime.time(0, 0, 0, 0))
msec = str(d.microsecond).rjust(6).replace(' ', '0')
return float('%s.%s' % (calendar.timegm(d.utctimetuple()), msec)) | [
"def",
"get_timestamp",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"date",
")",
"and",
"not",
"isinstance",
"(",
"d",
",",
"datetime",
".",
"datetime",
")",
":",
"d",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"d",
",",
"datetime",
".",
"time",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"msec",
"=",
"str",
"(",
"d",
".",
"microsecond",
")",
".",
"rjust",
"(",
"6",
")",
".",
"replace",
"(",
"' '",
",",
"'0'",
")",
"return",
"float",
"(",
"'%s.%s'",
"%",
"(",
"calendar",
".",
"timegm",
"(",
"d",
".",
"utctimetuple",
"(",
")",
")",
",",
"msec",
")",
")"
] | python | Returns a UTC timestamp for a C{datetime.datetime} object.
@type d: C{datetime.datetime}
@return: UTC timestamp.
@rtype: C{float}
@see: Inspiration taken from the U{Intertwingly blog
<http://intertwingly.net/blog/2007/09/02/Dealing-With-Dates>}. | true |
2,701,192 | def get_properties(obj):
"""
Returns a list of properties for L{obj}
@since: 0.5
"""
if hasattr(obj, 'keys'):
return obj.keys()
elif hasattr(obj, '__dict__'):
return obj.__dict__.keys()
return [] | [
"def",
"get_properties",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'keys'",
")",
":",
"return",
"obj",
".",
"keys",
"(",
")",
"elif",
"hasattr",
"(",
"obj",
",",
"'__dict__'",
")",
":",
"return",
"obj",
".",
"__dict__",
".",
"keys",
"(",
")",
"return",
"[",
"]"
] | python | Returns a list of properties for L{obj}
@since: 0.5 | true |
2,701,193 | def set_attrs(obj, attrs):
"""
Applies a collection of attributes C{attrs} to object C{obj} in the most
generic way possible.
@param obj: An instance implementing C{__setattr__}, or C{__setitem__}
@param attrs: A collection implementing the C{iteritems} function
@type attrs: Usually a dict
"""
o = setattr
if hasattr(obj, '__setitem__'):
o = type(obj).__setitem__
[o(obj, k, v) for k, v in attrs.iteritems()] | [
"def",
"set_attrs",
"(",
"obj",
",",
"attrs",
")",
":",
"o",
"=",
"setattr",
"if",
"hasattr",
"(",
"obj",
",",
"'__setitem__'",
")",
":",
"o",
"=",
"type",
"(",
"obj",
")",
".",
"__setitem__",
"[",
"o",
"(",
"obj",
",",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attrs",
".",
"iteritems",
"(",
")",
"]"
] | python | Applies a collection of attributes C{attrs} to object C{obj} in the most
generic way possible.
@param obj: An instance implementing C{__setattr__}, or C{__setitem__}
@param attrs: A collection implementing the C{iteritems} function
@type attrs: Usually a dict | true |
2,701,195 | def is_class_sealed(klass):
"""
Whether or not the supplied class can accept dynamic properties.
@rtype: C{bool}
@since: 0.5
"""
mro = inspect.getmro(klass)
new = False
if mro[-1] is object:
mro = mro[:-1]
new = True
for kls in mro:
if new and '__dict__' in kls.__dict__:
return False
if not hasattr(kls, '__slots__'):
return False
return True | [
"def",
"is_class_sealed",
"(",
"klass",
")",
":",
"mro",
"=",
"inspect",
".",
"getmro",
"(",
"klass",
")",
"new",
"=",
"False",
"if",
"mro",
"[",
"-",
"1",
"]",
"is",
"object",
":",
"mro",
"=",
"mro",
"[",
":",
"-",
"1",
"]",
"new",
"=",
"True",
"for",
"kls",
"in",
"mro",
":",
"if",
"new",
"and",
"'__dict__'",
"in",
"kls",
".",
"__dict__",
":",
"return",
"False",
"if",
"not",
"hasattr",
"(",
"kls",
",",
"'__slots__'",
")",
":",
"return",
"False",
"return",
"True"
] | python | Whether or not the supplied class can accept dynamic properties.
@rtype: C{bool}
@since: 0.5 | true |
2,701,409 | 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
# Replace the starting 'usage: ' with IPython's %.
help_text = parser.format_help()
if help_text.startswith('usage: '):
help_text = help_text.replace('usage: ', '%', 1)
else:
help_text = '%' + help_text
# Replace the magic function's docstring with the full help text.
magic_func.__doc__ = help_text
return parser | [
"def",
"construct_parser",
"(",
"magic_func",
")",
":",
"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",
")",
"group",
"=",
"None",
"for",
"deco",
"in",
"magic_func",
".",
"decorators",
"[",
":",
":",
"-",
"1",
"]",
":",
"result",
"=",
"deco",
".",
"add_to_parser",
"(",
"parser",
",",
"group",
")",
"if",
"result",
"is",
"not",
"None",
":",
"group",
"=",
"result",
"help_text",
"=",
"parser",
".",
"format_help",
"(",
")",
"if",
"help_text",
".",
"startswith",
"(",
"'usage: '",
")",
":",
"help_text",
"=",
"help_text",
".",
"replace",
"(",
"'usage: '",
",",
"'%'",
",",
"1",
")",
"else",
":",
"help_text",
"=",
"'%'",
"+",
"help_text",
"magic_func",
".",
"__doc__",
"=",
"help_text",
"return",
"parser"
] | python | Construct an argument parser using the function decorations. | true |
2,701,410 | def real_name(magic_func):
""" Find the real name of the magic.
"""
magic_name = magic_func.__name__
if magic_name.startswith('magic_'):
magic_name = magic_name[len('magic_'):]
return getattr(magic_func, 'argcmd_name', magic_name) | [
"def",
"real_name",
"(",
"magic_func",
")",
":",
"magic_name",
"=",
"magic_func",
".",
"__name__",
"if",
"magic_name",
".",
"startswith",
"(",
"'magic_'",
")",
":",
"magic_name",
"=",
"magic_name",
"[",
"len",
"(",
"'magic_'",
")",
":",
"]",
"return",
"getattr",
"(",
"magic_func",
",",
"'argcmd_name'",
",",
"magic_name",
")"
] | python | Find the real name of the magic. | true |
2,701,577 | def latex_to_html(s, alt='image'):
"""Render LaTeX to HTML with embedded PNG data using data URIs.
Parameters
----------
s : str
The raw string containing valid inline LateX.
alt : str
The alt text to use for the HTML.
"""
base64_data = latex_to_png(s, encode=True)
if base64_data:
return _data_uri_template_png % (base64_data, alt) | [
"def",
"latex_to_html",
"(",
"s",
",",
"alt",
"=",
"'image'",
")",
":",
"base64_data",
"=",
"latex_to_png",
"(",
"s",
",",
"encode",
"=",
"True",
")",
"if",
"base64_data",
":",
"return",
"_data_uri_template_png",
"%",
"(",
"base64_data",
",",
"alt",
")"
] | python | Render LaTeX to HTML with embedded PNG data using data URIs.
Parameters
----------
s : str
The raw string containing valid inline LateX.
alt : str
The alt text to use for the HTML. | true |
2,701,578 | def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
"""
Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or writable file-like object to write the image data
to.
*prop*
If provided, a FontProperties() object describing the size and
style of the text.
*dpi*
Override the output dpi, otherwise use the default associated
with the output format.
*format*
The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not
provided, will be deduced from the filename.
"""
from matplotlib import figure
# backend_agg supports all of the core output formats
from matplotlib.backends import backend_agg
from matplotlib.font_manager import FontProperties
from matplotlib.mathtext import MathTextParser
if prop is None:
prop = FontProperties()
parser = MathTextParser('path')
width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)
fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
fig.text(0, depth/height, s, fontproperties=prop)
backend_agg.FigureCanvasAgg(fig)
fig.savefig(filename_or_obj, dpi=dpi, format=format)
return depth | [
"def",
"math_to_image",
"(",
"s",
",",
"filename_or_obj",
",",
"prop",
"=",
"None",
",",
"dpi",
"=",
"None",
",",
"format",
"=",
"None",
")",
":",
"from",
"matplotlib",
"import",
"figure",
"from",
"matplotlib",
".",
"backends",
"import",
"backend_agg",
"from",
"matplotlib",
".",
"font_manager",
"import",
"FontProperties",
"from",
"matplotlib",
".",
"mathtext",
"import",
"MathTextParser",
"if",
"prop",
"is",
"None",
":",
"prop",
"=",
"FontProperties",
"(",
")",
"parser",
"=",
"MathTextParser",
"(",
"'path'",
")",
"width",
",",
"height",
",",
"depth",
",",
"_",
",",
"_",
"=",
"parser",
".",
"parse",
"(",
"s",
",",
"dpi",
"=",
"72",
",",
"prop",
"=",
"prop",
")",
"fig",
"=",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"width",
"/",
"72.0",
",",
"height",
"/",
"72.0",
")",
")",
"fig",
".",
"text",
"(",
"0",
",",
"depth",
"/",
"height",
",",
"s",
",",
"fontproperties",
"=",
"prop",
")",
"backend_agg",
".",
"FigureCanvasAgg",
"(",
"fig",
")",
"fig",
".",
"savefig",
"(",
"filename_or_obj",
",",
"dpi",
"=",
"dpi",
",",
"format",
"=",
"format",
")",
"return",
"depth"
] | python | Given a math expression, renders it in a closely-clipped bounding
box to an image file.
*s*
A math expression. The math portion should be enclosed in
dollar signs.
*filename_or_obj*
A filepath or writable file-like object to write the image data
to.
*prop*
If provided, a FontProperties() object describing the size and
style of the text.
*dpi*
Override the output dpi, otherwise use the default associated
with the output format.
*format*
The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not
provided, will be deduced from the filename. | true |
2,701,761 | def process_iter():
"""Return a generator yielding a Process class instance for all
running processes on the local machine.
Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used.
The sorting order in which processes are yielded is based on
their PIDs.
"""
def add(pid):
proc = Process(pid)
_pmap[proc.pid] = proc
return proc
def remove(pid):
_pmap.pop(pid, None)
a = set(get_pid_list())
b = set(_pmap.keys())
new_pids = a - b
gone_pids = b - a
for pid in gone_pids:
remove(pid)
for pid, proc in sorted(list(_pmap.items()) + \
list(dict.fromkeys(new_pids).items())):
try:
if proc is None: # new process
yield add(pid)
else:
# use is_running() to check whether PID has been reused by
# another process in which case yield a new Process instance
if proc.is_running():
yield proc
else:
yield add(pid)
except NoSuchProcess:
remove(pid)
except AccessDenied:
# Process creation time can't be determined hence there's
# no way to tell whether the pid of the cached process
# has been reused. Just return the cached version.
yield proc | [
"def",
"process_iter",
"(",
")",
":",
"def",
"add",
"(",
"pid",
")",
":",
"proc",
"=",
"Process",
"(",
"pid",
")",
"_pmap",
"[",
"proc",
".",
"pid",
"]",
"=",
"proc",
"return",
"proc",
"def",
"remove",
"(",
"pid",
")",
":",
"_pmap",
".",
"pop",
"(",
"pid",
",",
"None",
")",
"a",
"=",
"set",
"(",
"get_pid_list",
"(",
")",
")",
"b",
"=",
"set",
"(",
"_pmap",
".",
"keys",
"(",
")",
")",
"new_pids",
"=",
"a",
"-",
"b",
"gone_pids",
"=",
"b",
"-",
"a",
"for",
"pid",
"in",
"gone_pids",
":",
"remove",
"(",
"pid",
")",
"for",
"pid",
",",
"proc",
"in",
"sorted",
"(",
"list",
"(",
"_pmap",
".",
"items",
"(",
")",
")",
"+",
"list",
"(",
"dict",
".",
"fromkeys",
"(",
"new_pids",
")",
".",
"items",
"(",
")",
")",
")",
":",
"try",
":",
"if",
"proc",
"is",
"None",
":",
"yield",
"add",
"(",
"pid",
")",
"else",
":",
"if",
"proc",
".",
"is_running",
"(",
")",
":",
"yield",
"proc",
"else",
":",
"yield",
"add",
"(",
"pid",
")",
"except",
"NoSuchProcess",
":",
"remove",
"(",
"pid",
")",
"except",
"AccessDenied",
":",
"yield",
"proc"
] | python | Return a generator yielding a Process class instance for all
running processes on the local machine.
Every new Process instance is only created once and then cached
into an internal table which is updated every time this is used.
The sorting order in which processes are yielded is based on
their PIDs. | true |
2,701,762 | def cpu_percent(interval=0.1, percpu=False):
"""Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When percpu is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls.
"""
global _last_cpu_times
global _last_per_cpu_times
blocking = interval is not None and interval > 0.0
def calculate(t1, t2):
t1_all = sum(t1)
t1_busy = t1_all - t1.idle
t2_all = sum(t2)
t2_busy = t2_all - t2.idle
# this usually indicates a float precision issue
if t2_busy <= t1_busy:
return 0.0
busy_delta = t2_busy - t1_busy
all_delta = t2_all - t1_all
busy_perc = (busy_delta / all_delta) * 100
return round(busy_perc, 1)
# system-wide usage
if not percpu:
if blocking:
t1 = cpu_times()
time.sleep(interval)
else:
t1 = _last_cpu_times
_last_cpu_times = cpu_times()
return calculate(t1, _last_cpu_times)
# per-cpu usage
else:
ret = []
if blocking:
tot1 = cpu_times(percpu=True)
time.sleep(interval)
else:
tot1 = _last_per_cpu_times
_last_per_cpu_times = cpu_times(percpu=True)
for t1, t2 in zip(tot1, _last_per_cpu_times):
ret.append(calculate(t1, t2))
return ret | [
"def",
"cpu_percent",
"(",
"interval",
"=",
"0.1",
",",
"percpu",
"=",
"False",
")",
":",
"global",
"_last_cpu_times",
"global",
"_last_per_cpu_times",
"blocking",
"=",
"interval",
"is",
"not",
"None",
"and",
"interval",
">",
"0.0",
"def",
"calculate",
"(",
"t1",
",",
"t2",
")",
":",
"t1_all",
"=",
"sum",
"(",
"t1",
")",
"t1_busy",
"=",
"t1_all",
"-",
"t1",
".",
"idle",
"t2_all",
"=",
"sum",
"(",
"t2",
")",
"t2_busy",
"=",
"t2_all",
"-",
"t2",
".",
"idle",
"if",
"t2_busy",
"<=",
"t1_busy",
":",
"return",
"0.0",
"busy_delta",
"=",
"t2_busy",
"-",
"t1_busy",
"all_delta",
"=",
"t2_all",
"-",
"t1_all",
"busy_perc",
"=",
"(",
"busy_delta",
"/",
"all_delta",
")",
"*",
"100",
"return",
"round",
"(",
"busy_perc",
",",
"1",
")",
"if",
"not",
"percpu",
":",
"if",
"blocking",
":",
"t1",
"=",
"cpu_times",
"(",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"else",
":",
"t1",
"=",
"_last_cpu_times",
"_last_cpu_times",
"=",
"cpu_times",
"(",
")",
"return",
"calculate",
"(",
"t1",
",",
"_last_cpu_times",
")",
"else",
":",
"ret",
"=",
"[",
"]",
"if",
"blocking",
":",
"tot1",
"=",
"cpu_times",
"(",
"percpu",
"=",
"True",
")",
"time",
".",
"sleep",
"(",
"interval",
")",
"else",
":",
"tot1",
"=",
"_last_per_cpu_times",
"_last_per_cpu_times",
"=",
"cpu_times",
"(",
"percpu",
"=",
"True",
")",
"for",
"t1",
",",
"t2",
"in",
"zip",
"(",
"tot1",
",",
"_last_per_cpu_times",
")",
":",
"ret",
".",
"append",
"(",
"calculate",
"(",
"t1",
",",
"t2",
")",
")",
"return",
"ret"
] | python | Return a float representing the current system-wide CPU
utilization as a percentage.
When interval is > 0.0 compares system CPU times elapsed before
and after the interval (blocking).
When interval is 0.0 or None compares system CPU times elapsed
since last call or module import, returning immediately.
In this case is recommended for accuracy that this function be
called with at least 0.1 seconds between calls.
When percpu is True returns a list of floats representing the
utilization as a percentage for each CPU.
First element of the list refers to first CPU, second element
to second CPU and so on.
The order of the list is consistent across calls. | true |
2,701,853 | def get_templates():
"""
Returns each of the templates with env vars injected.
"""
injected = {}
for name, data in templates.items():
injected[name] = dict([(k, v % env) for k, v in data.items()])
return injected | [
"def",
"get_templates",
"(",
")",
":",
"injected",
"=",
"{",
"}",
"for",
"name",
",",
"data",
"in",
"templates",
".",
"items",
"(",
")",
":",
"injected",
"[",
"name",
"]",
"=",
"dict",
"(",
"[",
"(",
"k",
",",
"v",
"%",
"env",
")",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
"]",
")",
"return",
"injected"
] | python | Returns each of the templates with env vars injected. | true |
2,702,026 | def is_shadowed(identifier, ip):
"""Is the given identifier defined in one of the namespaces which shadow
the alias and magic namespaces? Note that an identifier is different
than ifun, because it can not contain a '.' character."""
# This is much safer than calling ofind, which can change state
return (identifier in ip.user_ns \
or identifier in ip.user_global_ns \
or identifier in ip.ns_table['builtin']) | [
"def",
"is_shadowed",
"(",
"identifier",
",",
"ip",
")",
":",
"return",
"(",
"identifier",
"in",
"ip",
".",
"user_ns",
"or",
"identifier",
"in",
"ip",
".",
"user_global_ns",
"or",
"identifier",
"in",
"ip",
".",
"ns_table",
"[",
"'builtin'",
"]",
")"
] | python | Is the given identifier defined in one of the namespaces which shadow
the alias and magic namespaces? Note that an identifier is different
than ifun, because it can not contain a '.' character. | true |
2,702,104 | def proxied_attribute(local_attr, proxied_attr, doc):
"""Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``.
"""
def fget(self):
return getattr(getattr(self, local_attr), proxied_attr)
def fset(self, value):
setattr(getattr(self, local_attr), proxied_attr, value)
def fdel(self):
delattr(getattr(self, local_attr), proxied_attr)
return property(fget, fset, fdel, doc) | [
"def",
"proxied_attribute",
"(",
"local_attr",
",",
"proxied_attr",
",",
"doc",
")",
":",
"def",
"fget",
"(",
"self",
")",
":",
"return",
"getattr",
"(",
"getattr",
"(",
"self",
",",
"local_attr",
")",
",",
"proxied_attr",
")",
"def",
"fset",
"(",
"self",
",",
"value",
")",
":",
"setattr",
"(",
"getattr",
"(",
"self",
",",
"local_attr",
")",
",",
"proxied_attr",
",",
"value",
")",
"def",
"fdel",
"(",
"self",
")",
":",
"delattr",
"(",
"getattr",
"(",
"self",
",",
"local_attr",
")",
",",
"proxied_attr",
")",
"return",
"property",
"(",
"fget",
",",
"fset",
",",
"fdel",
",",
"doc",
")"
] | python | Create a property that proxies attribute ``proxied_attr`` through
the local attribute ``local_attr``. | true |
2,702,287 | def virtualenv_no_global():
"""
Return True if in a venv and no system site packages.
"""
#this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
if running_under_virtualenv() and os.path.isfile(no_global_file):
return True | [
"def",
"virtualenv_no_global",
"(",
")",
":",
"site_mod_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"site",
".",
"__file__",
")",
")",
"no_global_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site_mod_dir",
",",
"'no-global-site-packages.txt'",
")",
"if",
"running_under_virtualenv",
"(",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"no_global_file",
")",
":",
"return",
"True"
] | python | Return True if in a venv and no system site packages. | true |
2,702,501 | def comment_filter(comment_text):
"""
Passed comment text to be rendered through the function defined
by the ``COMMENT_FILTER`` setting. If no function is defined
(the default), Django's ``linebreaksbr`` and ``urlize`` filters
are used.
"""
filter_func = settings.COMMENT_FILTER
if not filter_func:
def filter_func(s):
return linebreaksbr(urlize(s, autoescape=True), autoescape=True)
elif not callable(filter_func):
filter_func = import_dotted_path(filter_func)
return filter_func(comment_text) | [
"def",
"comment_filter",
"(",
"comment_text",
")",
":",
"filter_func",
"=",
"settings",
".",
"COMMENT_FILTER",
"if",
"not",
"filter_func",
":",
"def",
"filter_func",
"(",
"s",
")",
":",
"return",
"linebreaksbr",
"(",
"urlize",
"(",
"s",
",",
"autoescape",
"=",
"True",
")",
",",
"autoescape",
"=",
"True",
")",
"elif",
"not",
"callable",
"(",
"filter_func",
")",
":",
"filter_func",
"=",
"import_dotted_path",
"(",
"filter_func",
")",
"return",
"filter_func",
"(",
"comment_text",
")"
] | python | Passed comment text to be rendered through the function defined
by the ``COMMENT_FILTER`` setting. If no function is defined
(the default), Django's ``linebreaksbr`` and ``urlize`` filters
are used. | true |
2,702,502 | def shquote(arg):
"""Quote an argument for later parsing by shlex.split()"""
for c in '"', "'", "\\", "#":
if c in arg: return repr(arg)
if arg.split()<>[arg]:
return repr(arg)
return arg | [
"def",
"shquote",
"(",
"arg",
")",
":",
"for",
"c",
"in",
"'\"'",
",",
"\"'\"",
",",
"\"\\\\\"",
",",
"\"#\"",
":",
"if",
"c",
"in",
"arg",
":",
"return",
"repr",
"(",
"arg",
")",
"if",
"arg",
".",
"split",
"(",
")",
"<",
">",
"[",
"arg",
"]",
":",
"return",
"repr",
"(",
"arg",
")",
"return",
"arg"
] | python | Quote an argument for later parsing by shlex.split() | true |
2,702,758 | def inputhook_glut():
"""Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance.
"""
# We need to protect against a user pressing Control-C when IPython is
# idle and this is running. We trap KeyboardInterrupt and pass.
signal.signal(signal.SIGINT, glut_int_handler)
try:
t = clock()
# Make sure the default window is set after a window has been closed
if glut.glutGetWindow() == 0:
glut.glutSetWindow( 1 )
glutMainLoopEvent()
return 0
while not stdin_ready():
glutMainLoopEvent()
# We need to sleep at this point to keep the idle CPU load
# low. However, if sleep to long, GUI response is poor. As
# a compromise, we watch how often GUI events are being processed
# and switch between a short and long sleep time. Here are some
# stats useful in helping to tune this.
# time CPU load
# 0.001 13%
# 0.005 3%
# 0.01 1.5%
# 0.05 0.5%
used_time = clock() - t
if used_time > 5*60.0:
# print 'Sleep for 5 s' # dbg
time.sleep(5.0)
elif used_time > 10.0:
# print 'Sleep for 1 s' # dbg
time.sleep(1.0)
elif used_time > 0.1:
# Few GUI events coming in, so we can sleep longer
# print 'Sleep for 0.05 s' # dbg
time.sleep(0.05)
else:
# Many GUI events coming in, so sleep only very little
time.sleep(0.001)
except KeyboardInterrupt:
pass
return 0 | [
"def",
"inputhook_glut",
"(",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"glut_int_handler",
")",
"try",
":",
"t",
"=",
"clock",
"(",
")",
"if",
"glut",
".",
"glutGetWindow",
"(",
")",
"==",
"0",
":",
"glut",
".",
"glutSetWindow",
"(",
"1",
")",
"glutMainLoopEvent",
"(",
")",
"return",
"0",
"while",
"not",
"stdin_ready",
"(",
")",
":",
"glutMainLoopEvent",
"(",
")",
"used_time",
"=",
"clock",
"(",
")",
"-",
"t",
"if",
"used_time",
">",
"5",
"*",
"60.0",
":",
"time",
".",
"sleep",
"(",
"5.0",
")",
"elif",
"used_time",
">",
"10.0",
":",
"time",
".",
"sleep",
"(",
"1.0",
")",
"elif",
"used_time",
">",
"0.1",
":",
"time",
".",
"sleep",
"(",
"0.05",
")",
"else",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"except",
"KeyboardInterrupt",
":",
"pass",
"return",
"0"
] | python | Run the pyglet event loop by processing pending events only.
This keeps processing pending events until stdin is ready. After
processing all pending events, a call to time.sleep is inserted. This is
needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
though for best performance. | true |
2,702,892 | def dist_in_usersite(dist):
"""
Return True if given Distribution is installed in user site.
"""
if user_site:
return normalize_path(dist_location(dist)).startswith(normalize_path(user_site))
else:
return False | [
"def",
"dist_in_usersite",
"(",
"dist",
")",
":",
"if",
"user_site",
":",
"return",
"normalize_path",
"(",
"dist_location",
"(",
"dist",
")",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"user_site",
")",
")",
"else",
":",
"return",
"False"
] | python | Return True if given Distribution is installed in user site. | true |
2,702,952 | def convert_Decimal(x, encoder):
"""
Called when an instance of U{decimal.Decimal<http://
docs.python.org/library/decimal.html#decimal-objects>} is about to be
encoded to an AMF stream.
@return: If the encoder is in 'strict' mode then C{x} will be converted to
a float. Otherwise an L{pyamf.EncodeError} with a friendly message is
raised.
"""
if encoder.strict is False:
return float(x)
raise pyamf.EncodeError('Unable to encode decimal.Decimal instances as '
'there is no way to guarantee exact conversion. Use strict=False to '
'convert to a float.') | [
"def",
"convert_Decimal",
"(",
"x",
",",
"encoder",
")",
":",
"if",
"encoder",
".",
"strict",
"is",
"False",
":",
"return",
"float",
"(",
"x",
")",
"raise",
"pyamf",
".",
"EncodeError",
"(",
"'Unable to encode decimal.Decimal instances as '",
"'there is no way to guarantee exact conversion. Use strict=False to '",
"'convert to a float.'",
")"
] | python | Called when an instance of U{decimal.Decimal<http://
docs.python.org/library/decimal.html#decimal-objects>} is about to be
encoded to an AMF stream.
@return: If the encoder is in 'strict' mode then C{x} will be converted to
a float. Otherwise an L{pyamf.EncodeError} with a friendly message is
raised. | true |
2,703,182 | def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
return res | [
"def",
"readmodule",
"(",
"module",
",",
"path",
"=",
"None",
")",
":",
"res",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"_readmodule",
"(",
"module",
",",
"path",
"or",
"[",
"]",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Class",
")",
":",
"res",
"[",
"key",
"]",
"=",
"value",
"return",
"res"
] | python | Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary. | true |
2,703,604 | 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) | [
"def",
"uncache_zipdir",
"(",
"path",
")",
":",
"from",
"zipimport",
"import",
"_zip_directory_cache",
"as",
"zdc",
"_uncache",
"(",
"path",
",",
"zdc",
")",
"_uncache",
"(",
"path",
",",
"sys",
".",
"path_importer_cache",
")"
] | python | Ensure that the importer caches dont have stale info for `path` | true |
2,703,606 | def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
fp = open(executable)
magic = fp.read(2)
fp.close()
except (OSError,IOError): return executable
return magic == '#!' | [
"def",
"is_sh",
"(",
"executable",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"executable",
")",
"magic",
"=",
"fp",
".",
"read",
"(",
"2",
")",
"fp",
".",
"close",
"(",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"return",
"executable",
"return",
"magic",
"==",
"'#!'"
] | python | Determine if the specified executable is a .sh (contains a #! line) | true |
2,703,607 | 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 == '"':
# double preceding backslashes, then add a \"
result.append('\\' * (nb*2) + '\\"')
nb = 0
else:
if nb:
result.append('\\' * nb)
nb = 0
result.append(c)
if nb:
result.append('\\' * nb)
if needquote:
result.append('\\' * nb) # double the trailing backslashes
result.append('"')
return ''.join(result) | [
"def",
"nt_quote_arg",
"(",
"arg",
")",
":",
"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",
"==",
"'\"'",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"(",
"nb",
"*",
"2",
")",
"+",
"'\\\\\"'",
")",
"nb",
"=",
"0",
"else",
":",
"if",
"nb",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"nb",
"=",
"0",
"result",
".",
"append",
"(",
"c",
")",
"if",
"nb",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"if",
"needquote",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"result",
".",
"append",
"(",
"'\"'",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | python | Quote a command line argument according to Windows parsing rules | true |
2,703,655 | 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 | [
"def",
"is_archive_file",
"(",
"name",
")",
":",
"archives",
"=",
"(",
"'.zip'",
",",
"'.tar.gz'",
",",
"'.tar.bz2'",
",",
"'.tgz'",
",",
"'.tar'",
",",
"'.whl'",
")",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"archives",
":",
"return",
"True",
"return",
"False"
] | python | Return True if `name` is a considered as an archive file. | true |
2,703,860 | 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) | [
"def",
"_writable_dir",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"W_OK",
")"
] | python | Whether `path` is a directory, to which the user has write access. | true |
2,703,865 | 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 set
xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
if xdg and _writable_dir(xdg):
return py3compat.cast_unicode(xdg, fs_encoding)
return None | [
"def",
"get_xdg_dir",
"(",
")",
":",
"env",
"=",
"os",
".",
"environ",
"if",
"os",
".",
"name",
"==",
"'posix'",
"and",
"sys",
".",
"platform",
"!=",
"'darwin'",
":",
"xdg",
"=",
"env",
".",
"get",
"(",
"\"XDG_CONFIG_HOME\"",
",",
"None",
")",
"or",
"os",
".",
"path",
".",
"join",
"(",
"get_home_dir",
"(",
")",
",",
"'.config'",
")",
"if",
"xdg",
"and",
"_writable_dir",
"(",
"xdg",
")",
":",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"xdg",
",",
"fs_encoding",
")",
"return",
"None"
] | python | 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. | true |
2,703,867 | 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) | [
"def",
"get_ipython_package_dir",
"(",
")",
":",
"ipdir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"IPython",
".",
"__file__",
")",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"ipdir",
",",
"fs_encoding",
")"
] | python | Get the base directory where IPython itself is installed. | true |
2,703,868 | 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 == 'IPython':
return os.path.join(get_ipython_package_dir(), '__init__.py')
mod = import_item(module_str)
the_path = mod.__file__.replace('.pyc', '.py')
the_path = the_path.replace('.pyo', '.py')
return py3compat.cast_unicode(the_path, fs_encoding) | [
"def",
"get_ipython_module_path",
"(",
"module_str",
")",
":",
"if",
"module_str",
"==",
"'IPython'",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"get_ipython_package_dir",
"(",
")",
",",
"'__init__.py'",
")",
"mod",
"=",
"import_item",
"(",
"module_str",
")",
"the_path",
"=",
"mod",
".",
"__file__",
".",
"replace",
"(",
"'.pyc'",
",",
"'.py'",
")",
"the_path",
"=",
"the_path",
".",
"replace",
"(",
"'.pyo'",
",",
"'.py'",
")",
"return",
"py3compat",
".",
"cast_unicode",
"(",
"the_path",
",",
"fs_encoding",
")"
] | python | 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. | true |
2,703,869 | def locate_profile(profile='default'):
"""Find the path to the folder associated with a given profile.
I.e. find $IPYTHONDIR/profile_whatever.
"""
from IPython.core.profiledir import ProfileDir, ProfileDirError
try:
pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
except ProfileDirError:
# IOError makes more sense when people are expecting a path
raise IOError("Couldn't find profile %r" % profile)
return pd.location | [
"def",
"locate_profile",
"(",
"profile",
"=",
"'default'",
")",
":",
"from",
"IPython",
".",
"core",
".",
"profiledir",
"import",
"ProfileDir",
",",
"ProfileDirError",
"try",
":",
"pd",
"=",
"ProfileDir",
".",
"find_profile_dir_by_name",
"(",
"get_ipython_dir",
"(",
")",
",",
"profile",
")",
"except",
"ProfileDirError",
":",
"raise",
"IOError",
"(",
"\"Couldn't find profile %r\"",
"%",
"profile",
")",
"return",
"pd",
".",
"location"
] | python | Find the path to the folder associated with a given profile.
I.e. find $IPYTHONDIR/profile_whatever. | true |
2,703,871 | 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, otherwise return false.
"""
try:
target_time = os.path.getmtime(target)
except os.error:
return 1
for dep in deps:
dep_time = os.path.getmtime(dep)
if dep_time > target_time:
#print "For target",target,"Dep failed:",dep # dbg
#print "times (dep,tar):",dep_time,target_time # dbg
return 1
return 0 | [
"def",
"target_outdated",
"(",
"target",
",",
"deps",
")",
":",
"try",
":",
"target_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"target",
")",
"except",
"os",
".",
"error",
":",
"return",
"1",
"for",
"dep",
"in",
"deps",
":",
"dep_time",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"dep",
")",
"if",
"dep_time",
">",
"target_time",
":",
"return",
"1",
"return",
"0"
] | python | 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, otherwise return false. | true |
2,704,216 | def blog_months(*args):
"""
Put a list of dates for blog posts into the template context.
"""
dates = BlogPost.objects.published().values_list("publish_date", flat=True)
date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates]
month_dicts = []
for date_dict in date_dicts:
if date_dict not in month_dicts:
month_dicts.append(date_dict)
for i, date_dict in enumerate(month_dicts):
month_dicts[i]["post_count"] = date_dicts.count(date_dict)
return month_dicts | [
"def",
"blog_months",
"(",
"*",
"args",
")",
":",
"dates",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
".",
"values_list",
"(",
"\"publish_date\"",
",",
"flat",
"=",
"True",
")",
"date_dicts",
"=",
"[",
"{",
"\"date\"",
":",
"datetime",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"1",
")",
"}",
"for",
"d",
"in",
"dates",
"]",
"month_dicts",
"=",
"[",
"]",
"for",
"date_dict",
"in",
"date_dicts",
":",
"if",
"date_dict",
"not",
"in",
"month_dicts",
":",
"month_dicts",
".",
"append",
"(",
"date_dict",
")",
"for",
"i",
",",
"date_dict",
"in",
"enumerate",
"(",
"month_dicts",
")",
":",
"month_dicts",
"[",
"i",
"]",
"[",
"\"post_count\"",
"]",
"=",
"date_dicts",
".",
"count",
"(",
"date_dict",
")",
"return",
"month_dicts"
] | python | Put a list of dates for blog posts into the template context. | true |
2,704,217 | def blog_categories(*args):
"""
Put a list of categories for blog posts into the template context.
"""
posts = BlogPost.objects.published()
categories = BlogCategory.objects.filter(blogposts__in=posts)
return list(categories.annotate(post_count=Count("blogposts"))) | [
"def",
"blog_categories",
"(",
"*",
"args",
")",
":",
"posts",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
"categories",
"=",
"BlogCategory",
".",
"objects",
".",
"filter",
"(",
"blogposts__in",
"=",
"posts",
")",
"return",
"list",
"(",
"categories",
".",
"annotate",
"(",
"post_count",
"=",
"Count",
"(",
"\"blogposts\"",
")",
")",
")"
] | python | Put a list of categories for blog posts into the template context. | true |
2,704,218 | def blog_authors(*args):
"""
Put a list of authors (users) for blog posts into the template context.
"""
blog_posts = BlogPost.objects.published()
authors = User.objects.filter(blogposts__in=blog_posts)
return list(authors.annotate(post_count=Count("blogposts"))) | [
"def",
"blog_authors",
"(",
"*",
"args",
")",
":",
"blog_posts",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
"authors",
"=",
"User",
".",
"objects",
".",
"filter",
"(",
"blogposts__in",
"=",
"blog_posts",
")",
"return",
"list",
"(",
"authors",
".",
"annotate",
"(",
"post_count",
"=",
"Count",
"(",
"\"blogposts\"",
")",
")",
")"
] | python | Put a list of authors (users) for blog posts into the template context. | true |
2,704,219 | def blog_recent_posts(limit=5, tag=None, username=None, category=None):
"""
Put a list of recently published blog posts into the template
context. A tag title or slug, category title or slug or author's
username can also be specified to filter the recent posts returned.
Usage::
{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %}
"""
blog_posts = BlogPost.objects.published().select_related("user")
title_or_slug = lambda s: Q(title=s) | Q(slug=s)
if tag is not None:
try:
tag = Keyword.objects.get(title_or_slug(tag))
blog_posts = blog_posts.filter(keywords__keyword=tag)
except Keyword.DoesNotExist:
return []
if category is not None:
try:
category = BlogCategory.objects.get(title_or_slug(category))
blog_posts = blog_posts.filter(categories=category)
except BlogCategory.DoesNotExist:
return []
if username is not None:
try:
author = User.objects.get(username=username)
blog_posts = blog_posts.filter(user=author)
except User.DoesNotExist:
return []
return list(blog_posts[:limit]) | [
"def",
"blog_recent_posts",
"(",
"limit",
"=",
"5",
",",
"tag",
"=",
"None",
",",
"username",
"=",
"None",
",",
"category",
"=",
"None",
")",
":",
"blog_posts",
"=",
"BlogPost",
".",
"objects",
".",
"published",
"(",
")",
".",
"select_related",
"(",
"\"user\"",
")",
"title_or_slug",
"=",
"lambda",
"s",
":",
"Q",
"(",
"title",
"=",
"s",
")",
"|",
"Q",
"(",
"slug",
"=",
"s",
")",
"if",
"tag",
"is",
"not",
"None",
":",
"try",
":",
"tag",
"=",
"Keyword",
".",
"objects",
".",
"get",
"(",
"title_or_slug",
"(",
"tag",
")",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"keywords__keyword",
"=",
"tag",
")",
"except",
"Keyword",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"if",
"category",
"is",
"not",
"None",
":",
"try",
":",
"category",
"=",
"BlogCategory",
".",
"objects",
".",
"get",
"(",
"title_or_slug",
"(",
"category",
")",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"categories",
"=",
"category",
")",
"except",
"BlogCategory",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"if",
"username",
"is",
"not",
"None",
":",
"try",
":",
"author",
"=",
"User",
".",
"objects",
".",
"get",
"(",
"username",
"=",
"username",
")",
"blog_posts",
"=",
"blog_posts",
".",
"filter",
"(",
"user",
"=",
"author",
")",
"except",
"User",
".",
"DoesNotExist",
":",
"return",
"[",
"]",
"return",
"list",
"(",
"blog_posts",
"[",
":",
"limit",
"]",
")"
] | python | Put a list of recently published blog posts into the template
context. A tag title or slug, category title or slug or author's
username can also be specified to filter the recent posts returned.
Usage::
{% blog_recent_posts 5 as recent_posts %}
{% blog_recent_posts limit=5 tag="django" as recent_posts %}
{% blog_recent_posts limit=5 category="python" as recent_posts %}
{% blog_recent_posts 5 username=admin as recent_posts %} | true |
2,705,395 | def make_decorator(func):
"""
Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown).
"""
def decorate(newfunc):
if hasattr(func, 'compat_func_name'):
name = func.compat_func_name
else:
name = func.__name__
newfunc.__dict__ = func.__dict__
newfunc.__doc__ = func.__doc__
newfunc.__module__ = func.__module__
if not hasattr(newfunc, 'compat_co_firstlineno'):
newfunc.compat_co_firstlineno = func.func_code.co_firstlineno
try:
newfunc.__name__ = name
except TypeError:
# can't set func name in 2.3
newfunc.compat_func_name = name
return newfunc
return decorate | [
"def",
"make_decorator",
"(",
"func",
")",
":",
"def",
"decorate",
"(",
"newfunc",
")",
":",
"if",
"hasattr",
"(",
"func",
",",
"'compat_func_name'",
")",
":",
"name",
"=",
"func",
".",
"compat_func_name",
"else",
":",
"name",
"=",
"func",
".",
"__name__",
"newfunc",
".",
"__dict__",
"=",
"func",
".",
"__dict__",
"newfunc",
".",
"__doc__",
"=",
"func",
".",
"__doc__",
"newfunc",
".",
"__module__",
"=",
"func",
".",
"__module__",
"if",
"not",
"hasattr",
"(",
"newfunc",
",",
"'compat_co_firstlineno'",
")",
":",
"newfunc",
".",
"compat_co_firstlineno",
"=",
"func",
".",
"func_code",
".",
"co_firstlineno",
"try",
":",
"newfunc",
".",
"__name__",
"=",
"name",
"except",
"TypeError",
":",
"newfunc",
".",
"compat_func_name",
"=",
"name",
"return",
"newfunc",
"return",
"decorate"
] | python | Wraps a test decorator so as to properly replicate metadata
of the decorated function, including nose's additional stuff
(namely, setup and teardown). | true |
2,705,396 | def raises(*exceptions):
"""Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead.
"""
valid = ' or '.join([e.__name__ for e in exceptions])
def decorate(func):
name = func.__name__
def newfunc(*arg, **kw):
try:
func(*arg, **kw)
except exceptions:
pass
except:
raise
else:
message = "%s() did not raise %s" % (name, valid)
raise AssertionError(message)
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorate | [
"def",
"raises",
"(",
"*",
"exceptions",
")",
":",
"valid",
"=",
"' or '",
".",
"join",
"(",
"[",
"e",
".",
"__name__",
"for",
"e",
"in",
"exceptions",
"]",
")",
"def",
"decorate",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"__name__",
"def",
"newfunc",
"(",
"*",
"arg",
",",
"**",
"kw",
")",
":",
"try",
":",
"func",
"(",
"*",
"arg",
",",
"**",
"kw",
")",
"except",
"exceptions",
":",
"pass",
"except",
":",
"raise",
"else",
":",
"message",
"=",
"\"%s() did not raise %s\"",
"%",
"(",
"name",
",",
"valid",
")",
"raise",
"AssertionError",
"(",
"message",
")",
"newfunc",
"=",
"make_decorator",
"(",
"func",
")",
"(",
"newfunc",
")",
"return",
"newfunc",
"return",
"decorate"
] | python | Test must raise one of expected exceptions to pass.
Example use::
@raises(TypeError, ValueError)
def test_raises_type_error():
raise TypeError("This test passes")
@raises(Exception)
def test_that_fails_by_passing():
pass
If you want to test many assertions about exceptions in a single test,
you may want to use `assert_raises` instead. | true |
2,705,399 | def with_setup(setup=None, teardown=None):
"""Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses.
"""
def decorate(func, setup=setup, teardown=teardown):
if setup:
if hasattr(func, 'setup'):
_old_s = func.setup
def _s():
setup()
_old_s()
func.setup = _s
else:
func.setup = setup
if teardown:
if hasattr(func, 'teardown'):
_old_t = func.teardown
def _t():
_old_t()
teardown()
func.teardown = _t
else:
func.teardown = teardown
return func
return decorate | [
"def",
"with_setup",
"(",
"setup",
"=",
"None",
",",
"teardown",
"=",
"None",
")",
":",
"def",
"decorate",
"(",
"func",
",",
"setup",
"=",
"setup",
",",
"teardown",
"=",
"teardown",
")",
":",
"if",
"setup",
":",
"if",
"hasattr",
"(",
"func",
",",
"'setup'",
")",
":",
"_old_s",
"=",
"func",
".",
"setup",
"def",
"_s",
"(",
")",
":",
"setup",
"(",
")",
"_old_s",
"(",
")",
"func",
".",
"setup",
"=",
"_s",
"else",
":",
"func",
".",
"setup",
"=",
"setup",
"if",
"teardown",
":",
"if",
"hasattr",
"(",
"func",
",",
"'teardown'",
")",
":",
"_old_t",
"=",
"func",
".",
"teardown",
"def",
"_t",
"(",
")",
":",
"_old_t",
"(",
")",
"teardown",
"(",
")",
"func",
".",
"teardown",
"=",
"_t",
"else",
":",
"func",
".",
"teardown",
"=",
"teardown",
"return",
"func",
"return",
"decorate"
] | python | Decorator to add setup and/or teardown methods to a test function::
@with_setup(setup, teardown)
def test_something():
" ... "
Note that `with_setup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses. | true |
2,705,648 | def ParseInteger(text, is_signed=False, is_long=False):
"""Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
try:
# We force 32-bit values to int and 64-bit values to long to make
# alternate implementations where the distinction is more significant
# (e.g. the C++ implementation) simpler.
if is_long:
result = long(text, 0)
else:
result = int(text, 0)
except ValueError:
raise ValueError('Couldn\'t parse integer: %s' % text)
# Check if the integer is sane. Exceptions handled by callers.
checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
checker.CheckValue(result)
return result | [
"def",
"ParseInteger",
"(",
"text",
",",
"is_signed",
"=",
"False",
",",
"is_long",
"=",
"False",
")",
":",
"try",
":",
"if",
"is_long",
":",
"result",
"=",
"long",
"(",
"text",
",",
"0",
")",
"else",
":",
"result",
"=",
"int",
"(",
"text",
",",
"0",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'Couldn\\'t parse integer: %s'",
"%",
"text",
")",
"checker",
"=",
"_INTEGER_CHECKERS",
"[",
"2",
"*",
"int",
"(",
"is_long",
")",
"+",
"int",
"(",
"is_signed",
")",
"]",
"checker",
".",
"CheckValue",
"(",
"result",
")",
"return",
"result"
] | python | Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer. | true |
2,705,802 | def templates_for_device(request, templates):
"""
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list.
"""
from yacms.conf import settings
if not isinstance(templates, (list, tuple)):
templates = [templates]
device = device_from_request(request)
device_templates = []
for template in templates:
if device:
device_templates.append("%s/%s" % (device, template))
if settings.DEVICE_DEFAULT and settings.DEVICE_DEFAULT != device:
default = "%s/%s" % (settings.DEVICE_DEFAULT, template)
device_templates.append(default)
device_templates.append(template)
return device_templates | [
"def",
"templates_for_device",
"(",
"request",
",",
"templates",
")",
":",
"from",
"yacms",
".",
"conf",
"import",
"settings",
"if",
"not",
"isinstance",
"(",
"templates",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"templates",
"=",
"[",
"templates",
"]",
"device",
"=",
"device_from_request",
"(",
"request",
")",
"device_templates",
"=",
"[",
"]",
"for",
"template",
"in",
"templates",
":",
"if",
"device",
":",
"device_templates",
".",
"append",
"(",
"\"%s/%s\"",
"%",
"(",
"device",
",",
"template",
")",
")",
"if",
"settings",
".",
"DEVICE_DEFAULT",
"and",
"settings",
".",
"DEVICE_DEFAULT",
"!=",
"device",
":",
"default",
"=",
"\"%s/%s\"",
"%",
"(",
"settings",
".",
"DEVICE_DEFAULT",
",",
"template",
")",
"device_templates",
".",
"append",
"(",
"default",
")",
"device_templates",
".",
"append",
"(",
"template",
")",
"return",
"device_templates"
] | python | Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted before it's associate default in the list. | true |
2,705,988 | def get_method_attr(method, cls, attr_name, default = False):
"""Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any.
"""
Missing = object()
value = getattr(method, attr_name, Missing)
if value is Missing and cls is not None:
value = getattr(cls, attr_name, Missing)
if value is Missing:
return default
return value | [
"def",
"get_method_attr",
"(",
"method",
",",
"cls",
",",
"attr_name",
",",
"default",
"=",
"False",
")",
":",
"Missing",
"=",
"object",
"(",
")",
"value",
"=",
"getattr",
"(",
"method",
",",
"attr_name",
",",
"Missing",
")",
"if",
"value",
"is",
"Missing",
"and",
"cls",
"is",
"not",
"None",
":",
"value",
"=",
"getattr",
"(",
"cls",
",",
"attr_name",
",",
"Missing",
")",
"if",
"value",
"is",
"Missing",
":",
"return",
"default",
"return",
"value"
] | python | Look up an attribute on a method/ function.
If the attribute isn't found there, looking it up in the
method's class, if any. | true |
2,706,102 | def blog_post_feed(request, format, **kwargs):
"""
Blog posts feeds - maps format to the correct feed view.
"""
try:
return {"rss": PostsRSS, "atom": PostsAtom}[format](**kwargs)(request)
except KeyError:
raise Http404() | [
"def",
"blog_post_feed",
"(",
"request",
",",
"format",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"{",
"\"rss\"",
":",
"PostsRSS",
",",
"\"atom\"",
":",
"PostsAtom",
"}",
"[",
"format",
"]",
"(",
"**",
"kwargs",
")",
"(",
"request",
")",
"except",
"KeyError",
":",
"raise",
"Http404",
"(",
")"
] | python | Blog posts feeds - maps format to the correct feed view. | true |
2,706,663 | def host_theme_path():
"""
Returns the directory of the theme associated with the given host.
"""
# Set domain to None, which we'll then query for in the first
# iteration of HOST_THEMES. We use the current site_id rather
# than a request object here, as it may differ for admin users.
domain = None
for (host, theme) in settings.HOST_THEMES:
if domain is None:
domain = Site.objects.get(id=current_site_id()).domain
if host.lower() == domain.lower():
try:
__import__(theme)
module = sys.modules[theme]
except ImportError:
pass
else:
return os.path.dirname(os.path.abspath(module.__file__))
return "" | [
"def",
"host_theme_path",
"(",
")",
":",
"domain",
"=",
"None",
"for",
"(",
"host",
",",
"theme",
")",
"in",
"settings",
".",
"HOST_THEMES",
":",
"if",
"domain",
"is",
"None",
":",
"domain",
"=",
"Site",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"current_site_id",
"(",
")",
")",
".",
"domain",
"if",
"host",
".",
"lower",
"(",
")",
"==",
"domain",
".",
"lower",
"(",
")",
":",
"try",
":",
"__import__",
"(",
"theme",
")",
"module",
"=",
"sys",
".",
"modules",
"[",
"theme",
"]",
"except",
"ImportError",
":",
"pass",
"else",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"module",
".",
"__file__",
")",
")",
"return",
"\"\""
] | python | Returns the directory of the theme associated with the given host. | true |
2,706,664 | def templates_for_host(templates):
"""
Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted into the front of the list.
"""
if not isinstance(templates, (list, tuple)):
templates = [templates]
theme_dir = host_theme_path()
host_templates = []
if theme_dir:
for template in templates:
host_templates.append("%s/templates/%s" % (theme_dir, template))
host_templates.append(template)
return host_templates
return templates | [
"def",
"templates_for_host",
"(",
"templates",
")",
":",
"if",
"not",
"isinstance",
"(",
"templates",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"templates",
"=",
"[",
"templates",
"]",
"theme_dir",
"=",
"host_theme_path",
"(",
")",
"host_templates",
"=",
"[",
"]",
"if",
"theme_dir",
":",
"for",
"template",
"in",
"templates",
":",
"host_templates",
".",
"append",
"(",
"\"%s/templates/%s\"",
"%",
"(",
"theme_dir",
",",
"template",
")",
")",
"host_templates",
".",
"append",
"(",
"template",
")",
"return",
"host_templates",
"return",
"templates"
] | python | Given a template name (or list of them), returns the template names
as a list, with each name prefixed with the device directory
inserted into the front of the list. | true |
2,708,544 | def unit_poly_verts(theta):
"""Return vertices of polygon for subplot axes.
This polygon is circumscribed by a unit circle centered at (0.5, 0.5)
"""
x0, y0, r = [0.5] * 3
verts = [(r*np.cos(t) + x0, r*np.sin(t) + y0) for t in theta]
return verts | [
"def",
"unit_poly_verts",
"(",
"theta",
")",
":",
"x0",
",",
"y0",
",",
"r",
"=",
"[",
"0.5",
"]",
"*",
"3",
"verts",
"=",
"[",
"(",
"r",
"*",
"np",
".",
"cos",
"(",
"t",
")",
"+",
"x0",
",",
"r",
"*",
"np",
".",
"sin",
"(",
"t",
")",
"+",
"y0",
")",
"for",
"t",
"in",
"theta",
"]",
"return",
"verts"
] | python | Return vertices of polygon for subplot axes.
This polygon is circumscribed by a unit circle centered at (0.5, 0.5) | true |
2,708,773 | def generate_error(request, cls, e, tb, include_traceback=False):
"""
Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the
last traceback and the request that was sent.
"""
import traceback
if hasattr(cls, '_amf_code'):
code = cls._amf_code
else:
code = cls.__name__
details = None
rootCause = None
if include_traceback:
details = traceback.format_exception(cls, e, tb)
rootCause = e
faultDetail = None
faultString = None
if hasattr(e, 'message'):
faultString = unicode(e.message)
elif hasattr(e, 'args') and e.args:
if isinstance(e.args[0], pyamf.python.str_types):
faultString = unicode(e.args[0])
if details:
faultDetail = unicode(details)
return messaging.ErrorMessage(
messageId=generate_random_id(),
clientId=generate_random_id(),
timestamp=calendar.timegm(time.gmtime()),
correlationId=request.messageId,
faultCode=code,
faultString=faultString,
faultDetail=faultDetail,
extendedData=details,
rootCause=rootCause) | [
"def",
"generate_error",
"(",
"request",
",",
"cls",
",",
"e",
",",
"tb",
",",
"include_traceback",
"=",
"False",
")",
":",
"import",
"traceback",
"if",
"hasattr",
"(",
"cls",
",",
"'_amf_code'",
")",
":",
"code",
"=",
"cls",
".",
"_amf_code",
"else",
":",
"code",
"=",
"cls",
".",
"__name__",
"details",
"=",
"None",
"rootCause",
"=",
"None",
"if",
"include_traceback",
":",
"details",
"=",
"traceback",
".",
"format_exception",
"(",
"cls",
",",
"e",
",",
"tb",
")",
"rootCause",
"=",
"e",
"faultDetail",
"=",
"None",
"faultString",
"=",
"None",
"if",
"hasattr",
"(",
"e",
",",
"'message'",
")",
":",
"faultString",
"=",
"unicode",
"(",
"e",
".",
"message",
")",
"elif",
"hasattr",
"(",
"e",
",",
"'args'",
")",
"and",
"e",
".",
"args",
":",
"if",
"isinstance",
"(",
"e",
".",
"args",
"[",
"0",
"]",
",",
"pyamf",
".",
"python",
".",
"str_types",
")",
":",
"faultString",
"=",
"unicode",
"(",
"e",
".",
"args",
"[",
"0",
"]",
")",
"if",
"details",
":",
"faultDetail",
"=",
"unicode",
"(",
"details",
")",
"return",
"messaging",
".",
"ErrorMessage",
"(",
"messageId",
"=",
"generate_random_id",
"(",
")",
",",
"clientId",
"=",
"generate_random_id",
"(",
")",
",",
"timestamp",
"=",
"calendar",
".",
"timegm",
"(",
"time",
".",
"gmtime",
"(",
")",
")",
",",
"correlationId",
"=",
"request",
".",
"messageId",
",",
"faultCode",
"=",
"code",
",",
"faultString",
"=",
"faultString",
",",
"faultDetail",
"=",
"faultDetail",
",",
"extendedData",
"=",
"details",
",",
"rootCause",
"=",
"rootCause",
")"
] | python | Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the
last traceback and the request that was sent. | true |
2,708,894 | def tweets_for(query_type, args, per_user=None):
"""
Retrieve tweets for a user, list or search term. The optional
``per_user`` arg limits the number of tweets per user, for
example to allow a fair spread of tweets per user for a list.
"""
lookup = {"query_type": query_type, "value": args[0]}
try:
tweets = Tweet.objects.get_for(**lookup)
except TwitterQueryException:
return []
if per_user is not None:
_tweets = defaultdict(list)
for tweet in tweets:
if len(_tweets[tweet.user_name]) < per_user:
_tweets[tweet.user_name].append(tweet)
tweets = sum(_tweets.values(), [])
tweets.sort(key=lambda t: t.created_at, reverse=True)
if len(args) > 1 and str(args[-1]).isdigit():
tweets = tweets[:int(args[-1])]
return tweets | [
"def",
"tweets_for",
"(",
"query_type",
",",
"args",
",",
"per_user",
"=",
"None",
")",
":",
"lookup",
"=",
"{",
"\"query_type\"",
":",
"query_type",
",",
"\"value\"",
":",
"args",
"[",
"0",
"]",
"}",
"try",
":",
"tweets",
"=",
"Tweet",
".",
"objects",
".",
"get_for",
"(",
"**",
"lookup",
")",
"except",
"TwitterQueryException",
":",
"return",
"[",
"]",
"if",
"per_user",
"is",
"not",
"None",
":",
"_tweets",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"tweet",
"in",
"tweets",
":",
"if",
"len",
"(",
"_tweets",
"[",
"tweet",
".",
"user_name",
"]",
")",
"<",
"per_user",
":",
"_tweets",
"[",
"tweet",
".",
"user_name",
"]",
".",
"append",
"(",
"tweet",
")",
"tweets",
"=",
"sum",
"(",
"_tweets",
".",
"values",
"(",
")",
",",
"[",
"]",
")",
"tweets",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"t",
".",
"created_at",
",",
"reverse",
"=",
"True",
")",
"if",
"len",
"(",
"args",
")",
">",
"1",
"and",
"str",
"(",
"args",
"[",
"-",
"1",
"]",
")",
".",
"isdigit",
"(",
")",
":",
"tweets",
"=",
"tweets",
"[",
":",
"int",
"(",
"args",
"[",
"-",
"1",
"]",
")",
"]",
"return",
"tweets"
] | python | Retrieve tweets for a user, list or search term. The optional
``per_user`` arg limits the number of tweets per user, for
example to allow a fair spread of tweets per user for a list. | true |
2,708,895 | def tweets_default(*args):
"""
Tweets for the default settings.
"""
query_type = settings.TWITTER_DEFAULT_QUERY_TYPE
args = (settings.TWITTER_DEFAULT_QUERY,
settings.TWITTER_DEFAULT_NUM_TWEETS)
per_user = None
if query_type == QUERY_TYPE_LIST:
per_user = 1
return tweets_for(query_type, args, per_user=per_user) | [
"def",
"tweets_default",
"(",
"*",
"args",
")",
":",
"query_type",
"=",
"settings",
".",
"TWITTER_DEFAULT_QUERY_TYPE",
"args",
"=",
"(",
"settings",
".",
"TWITTER_DEFAULT_QUERY",
",",
"settings",
".",
"TWITTER_DEFAULT_NUM_TWEETS",
")",
"per_user",
"=",
"None",
"if",
"query_type",
"==",
"QUERY_TYPE_LIST",
":",
"per_user",
"=",
"1",
"return",
"tweets_for",
"(",
"query_type",
",",
"args",
",",
"per_user",
"=",
"per_user",
")"
] | python | Tweets for the default settings. | true |
2,710,934 | def stop_reactor():
"""Stop the reactor and join the reactor thread until it stops.
Call this function in teardown at the module or package level to
reset the twisted system after your tests. You *must* do this if
you mix tests using these tools and tests using twisted.trial.
"""
global _twisted_thread
def stop_reactor():
'''Helper for calling stop from withing the thread.'''
reactor.stop()
reactor.callFromThread(stop_reactor)
reactor_thread.join()
for p in reactor.getDelayedCalls():
if p.active():
p.cancel()
_twisted_thread = None | [
"def",
"stop_reactor",
"(",
")",
":",
"global",
"_twisted_thread",
"def",
"stop_reactor",
"(",
")",
":",
"reactor",
".",
"stop",
"(",
")",
"reactor",
".",
"callFromThread",
"(",
"stop_reactor",
")",
"reactor_thread",
".",
"join",
"(",
")",
"for",
"p",
"in",
"reactor",
".",
"getDelayedCalls",
"(",
")",
":",
"if",
"p",
".",
"active",
"(",
")",
":",
"p",
".",
"cancel",
"(",
")",
"_twisted_thread",
"=",
"None"
] | python | Stop the reactor and join the reactor thread until it stops.
Call this function in teardown at the module or package level to
reset the twisted system after your tests. You *must* do this if
you mix tests using these tools and tests using twisted.trial. | true |
2,710,935 | def deferred(timeout=None):
"""
By wrapping a test function with this decorator, you can return a
twisted Deferred and the test will wait for the deferred to be triggered.
The whole test function will run inside the Twisted event loop.
The optional timeout parameter specifies the maximum duration of the test.
The difference with timed() is that timed() will still wait for the test
to end, while deferred() will stop the test when its timeout has expired.
The latter is more desireable when dealing with network tests, because
the result may actually never arrive.
If the callback is triggered, the test has passed.
If the errback is triggered or the timeout expires, the test has failed.
Example::
@deferred(timeout=5.0)
def test_resolve():
return reactor.resolve("www.python.org")
Attention! If you combine this decorator with other decorators (like
"raises"), deferred() must be called *first*!
In other words, this is good::
@raises(DNSLookupError)
@deferred()
def test_error():
return reactor.resolve("xxxjhjhj.biz")
and this is bad::
@deferred()
@raises(DNSLookupError)
def test_error():
return reactor.resolve("xxxjhjhj.biz")
"""
reactor, reactor_thread = threaded_reactor()
if reactor is None:
raise ImportError("twisted is not available or could not be imported")
# Check for common syntax mistake
# (otherwise, tests can be silently ignored
# if one writes "@deferred" instead of "@deferred()")
try:
timeout is None or timeout + 0
except TypeError:
raise TypeError("'timeout' argument must be a number or None")
def decorate(func):
def wrapper(*args, **kargs):
q = Queue()
def callback(value):
q.put(None)
def errback(failure):
# Retrieve and save full exception info
try:
failure.raiseException()
except:
q.put(sys.exc_info())
def g():
try:
d = func(*args, **kargs)
try:
d.addCallbacks(callback, errback)
# Check for a common mistake and display a nice error
# message
except AttributeError:
raise TypeError("you must return a twisted Deferred "
"from your test case!")
# Catch exceptions raised in the test body (from the
# Twisted thread)
except:
q.put(sys.exc_info())
reactor.callFromThread(g)
try:
error = q.get(timeout=timeout)
except Empty:
raise TimeExpired("timeout expired before end of test (%f s.)"
% timeout)
# Re-raise all exceptions
if error is not None:
exc_type, exc_value, tb = error
raise exc_type, exc_value, tb
wrapper = make_decorator(func)(wrapper)
return wrapper
return decorate | [
"def",
"deferred",
"(",
"timeout",
"=",
"None",
")",
":",
"reactor",
",",
"reactor_thread",
"=",
"threaded_reactor",
"(",
")",
"if",
"reactor",
"is",
"None",
":",
"raise",
"ImportError",
"(",
"\"twisted is not available or could not be imported\"",
")",
"try",
":",
"timeout",
"is",
"None",
"or",
"timeout",
"+",
"0",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"\"'timeout' argument must be a number or None\"",
")",
"def",
"decorate",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
":",
"q",
"=",
"Queue",
"(",
")",
"def",
"callback",
"(",
"value",
")",
":",
"q",
".",
"put",
"(",
"None",
")",
"def",
"errback",
"(",
"failure",
")",
":",
"try",
":",
"failure",
".",
"raiseException",
"(",
")",
"except",
":",
"q",
".",
"put",
"(",
"sys",
".",
"exc_info",
"(",
")",
")",
"def",
"g",
"(",
")",
":",
"try",
":",
"d",
"=",
"func",
"(",
"*",
"args",
",",
"**",
"kargs",
")",
"try",
":",
"d",
".",
"addCallbacks",
"(",
"callback",
",",
"errback",
")",
"except",
"AttributeError",
":",
"raise",
"TypeError",
"(",
"\"you must return a twisted Deferred \"",
"\"from your test case!\"",
")",
"except",
":",
"q",
".",
"put",
"(",
"sys",
".",
"exc_info",
"(",
")",
")",
"reactor",
".",
"callFromThread",
"(",
"g",
")",
"try",
":",
"error",
"=",
"q",
".",
"get",
"(",
"timeout",
"=",
"timeout",
")",
"except",
"Empty",
":",
"raise",
"TimeExpired",
"(",
"\"timeout expired before end of test (%f s.)\"",
"%",
"timeout",
")",
"if",
"error",
"is",
"not",
"None",
":",
"exc_type",
",",
"exc_value",
",",
"tb",
"=",
"error",
"raise",
"exc_type",
",",
"exc_value",
",",
"tb",
"wrapper",
"=",
"make_decorator",
"(",
"func",
")",
"(",
"wrapper",
")",
"return",
"wrapper",
"return",
"decorate"
] | python | By wrapping a test function with this decorator, you can return a
twisted Deferred and the test will wait for the deferred to be triggered.
The whole test function will run inside the Twisted event loop.
The optional timeout parameter specifies the maximum duration of the test.
The difference with timed() is that timed() will still wait for the test
to end, while deferred() will stop the test when its timeout has expired.
The latter is more desireable when dealing with network tests, because
the result may actually never arrive.
If the callback is triggered, the test has passed.
If the errback is triggered or the timeout expires, the test has failed.
Example::
@deferred(timeout=5.0)
def test_resolve():
return reactor.resolve("www.python.org")
Attention! If you combine this decorator with other decorators (like
"raises"), deferred() must be called *first*!
In other words, this is good::
@raises(DNSLookupError)
@deferred()
def test_error():
return reactor.resolve("xxxjhjhj.biz")
and this is bad::
@deferred()
@raises(DNSLookupError)
def test_error():
return reactor.resolve("xxxjhjhj.biz") | true |
2,711,007 | def expose_request(func):
"""
A decorator that adds an expose_request flag to the underlying callable.
@raise TypeError: C{func} must be callable.
"""
if not python.callable(func):
raise TypeError("func must be callable")
if isinstance(func, types.UnboundMethodType):
setattr(func.im_func, '_pyamf_expose_request', True)
else:
setattr(func, '_pyamf_expose_request', True)
return func | [
"def",
"expose_request",
"(",
"func",
")",
":",
"if",
"not",
"python",
".",
"callable",
"(",
"func",
")",
":",
"raise",
"TypeError",
"(",
"\"func must be callable\"",
")",
"if",
"isinstance",
"(",
"func",
",",
"types",
".",
"UnboundMethodType",
")",
":",
"setattr",
"(",
"func",
".",
"im_func",
",",
"'_pyamf_expose_request'",
",",
"True",
")",
"else",
":",
"setattr",
"(",
"func",
",",
"'_pyamf_expose_request'",
",",
"True",
")",
"return",
"func"
] | python | A decorator that adds an expose_request flag to the underlying callable.
@raise TypeError: C{func} must be callable. | true |
2,711,421 | def getfigs(*fig_nums):
"""Get a list of matplotlib figures by figure numbers.
If no arguments are given, all available figures are returned. If the
argument list contains references to invalid figures, a warning is printed
but the function continues pasting further figures.
Parameters
----------
figs : tuple
A tuple of ints giving the figure numbers of the figures to return.
"""
from matplotlib._pylab_helpers import Gcf
if not fig_nums:
fig_managers = Gcf.get_all_fig_managers()
return [fm.canvas.figure for fm in fig_managers]
else:
figs = []
for num in fig_nums:
f = Gcf.figs.get(num)
if f is None:
print('Warning: figure %s not available.' % num)
else:
figs.append(f.canvas.figure)
return figs | [
"def",
"getfigs",
"(",
"*",
"fig_nums",
")",
":",
"from",
"matplotlib",
".",
"_pylab_helpers",
"import",
"Gcf",
"if",
"not",
"fig_nums",
":",
"fig_managers",
"=",
"Gcf",
".",
"get_all_fig_managers",
"(",
")",
"return",
"[",
"fm",
".",
"canvas",
".",
"figure",
"for",
"fm",
"in",
"fig_managers",
"]",
"else",
":",
"figs",
"=",
"[",
"]",
"for",
"num",
"in",
"fig_nums",
":",
"f",
"=",
"Gcf",
".",
"figs",
".",
"get",
"(",
"num",
")",
"if",
"f",
"is",
"None",
":",
"print",
"(",
"'Warning: figure %s not available.'",
"%",
"num",
")",
"else",
":",
"figs",
".",
"append",
"(",
"f",
".",
"canvas",
".",
"figure",
")",
"return",
"figs"
] | python | Get a list of matplotlib figures by figure numbers.
If no arguments are given, all available figures are returned. If the
argument list contains references to invalid figures, a warning is printed
but the function continues pasting further figures.
Parameters
----------
figs : tuple
A tuple of ints giving the figure numbers of the figures to return. | true |
2,712,100 | def _AddPropertiesForExtensions(descriptor, cls):
"""Adds properties for all fields in this protocol message type."""
extension_dict = descriptor.extensions_by_name
for extension_name, extension_field in extension_dict.items():
constant_name = extension_name.upper() + "_FIELD_NUMBER"
setattr(cls, constant_name, extension_field.number) | [
"def",
"_AddPropertiesForExtensions",
"(",
"descriptor",
",",
"cls",
")",
":",
"extension_dict",
"=",
"descriptor",
".",
"extensions_by_name",
"for",
"extension_name",
",",
"extension_field",
"in",
"extension_dict",
".",
"items",
"(",
")",
":",
"constant_name",
"=",
"extension_name",
".",
"upper",
"(",
")",
"+",
"\"_FIELD_NUMBER\"",
"setattr",
"(",
"cls",
",",
"constant_name",
",",
"extension_field",
".",
"number",
")"
] | python | Adds properties for all fields in this protocol message type. | true |
2,712,125 | def get_app_wx(*args, **kwargs):
"""Create a new wx app or return an exiting one."""
import wx
app = wx.GetApp()
if app is None:
if not kwargs.has_key('redirect'):
kwargs['redirect'] = False
app = wx.PySimpleApp(*args, **kwargs)
return app | [
"def",
"get_app_wx",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"import",
"wx",
"app",
"=",
"wx",
".",
"GetApp",
"(",
")",
"if",
"app",
"is",
"None",
":",
"if",
"not",
"kwargs",
".",
"has_key",
"(",
"'redirect'",
")",
":",
"kwargs",
"[",
"'redirect'",
"]",
"=",
"False",
"app",
"=",
"wx",
".",
"PySimpleApp",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"app"
] | python | Create a new wx app or return an exiting one. | true |
2,712,127 | def start_event_loop_wx(app=None):
"""Start the wx event loop in a consistent manner."""
if app is None:
app = get_app_wx()
if not is_event_loop_running_wx(app):
app._in_event_loop = True
app.MainLoop()
app._in_event_loop = False
else:
app._in_event_loop = True | [
"def",
"start_event_loop_wx",
"(",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"get_app_wx",
"(",
")",
"if",
"not",
"is_event_loop_running_wx",
"(",
"app",
")",
":",
"app",
".",
"_in_event_loop",
"=",
"True",
"app",
".",
"MainLoop",
"(",
")",
"app",
".",
"_in_event_loop",
"=",
"False",
"else",
":",
"app",
".",
"_in_event_loop",
"=",
"True"
] | python | Start the wx event loop in a consistent manner. | true |
2,712,128 | def get_app_qt4(*args, **kwargs):
"""Create a new qt4 app or return an existing one."""
from IPython.external.qt_for_kernel import QtGui
app = QtGui.QApplication.instance()
if app is None:
if not args:
args = ([''],)
app = QtGui.QApplication(*args, **kwargs)
return app | [
"def",
"get_app_qt4",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"from",
"IPython",
".",
"external",
".",
"qt_for_kernel",
"import",
"QtGui",
"app",
"=",
"QtGui",
".",
"QApplication",
".",
"instance",
"(",
")",
"if",
"app",
"is",
"None",
":",
"if",
"not",
"args",
":",
"args",
"=",
"(",
"[",
"''",
"]",
",",
")",
"app",
"=",
"QtGui",
".",
"QApplication",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"return",
"app"
] | python | Create a new qt4 app or return an existing one. | true |
2,712,130 | def start_event_loop_qt4(app=None):
"""Start the qt4 event loop in a consistent manner."""
if app is None:
app = get_app_qt4([''])
if not is_event_loop_running_qt4(app):
app._in_event_loop = True
app.exec_()
app._in_event_loop = False
else:
app._in_event_loop = True | [
"def",
"start_event_loop_qt4",
"(",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"get_app_qt4",
"(",
"[",
"''",
"]",
")",
"if",
"not",
"is_event_loop_running_qt4",
"(",
"app",
")",
":",
"app",
".",
"_in_event_loop",
"=",
"True",
"app",
".",
"exec_",
"(",
")",
"app",
".",
"_in_event_loop",
"=",
"False",
"else",
":",
"app",
".",
"_in_event_loop",
"=",
"True"
] | python | Start the qt4 event loop in a consistent manner. | true |
2,712,288 | def search_fields_to_dict(fields):
"""
In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mapped to
weights, eg: ("title", "content") -> {"title": 1, "content": 1}
"""
if not fields:
return {}
try:
int(list(dict(fields).values())[0])
except (TypeError, ValueError):
fields = dict(zip(fields, [1] * len(fields)))
return fields | [
"def",
"search_fields_to_dict",
"(",
"fields",
")",
":",
"if",
"not",
"fields",
":",
"return",
"{",
"}",
"try",
":",
"int",
"(",
"list",
"(",
"dict",
"(",
"fields",
")",
".",
"values",
"(",
")",
")",
"[",
"0",
"]",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"fields",
"=",
"dict",
"(",
"zip",
"(",
"fields",
",",
"[",
"1",
"]",
"*",
"len",
"(",
"fields",
")",
")",
")",
"return",
"fields"
] | python | In ``SearchableQuerySet`` and ``SearchableManager``, search fields
can either be a sequence, or a dict of fields mapped to weights.
This function converts sequences to a dict mapped to even weights,
so that we're consistently dealing with a dict of fields mapped to
weights, eg: ("title", "content") -> {"title": 1, "content": 1} | true |