Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
3,700 | def _update_variables(self, now):
# we must update the local variables on every cycle
self.gmt = time.gmtime(now)
now = time.localtime(now)
if now[3] < 12: self.ampm='(AM|am)'
else: self.ampm='(PM|pm)'
self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1,... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_strftime.py/StrftimeTest._update_variables |
3,701 | def setUp(self):
try:
import java
java.util.Locale.setDefault(java.util.Locale.US)
except __HOLE__:
import locale
locale.setlocale(locale.LC_TIME, 'C') | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_strftime.py/StrftimeTest.setUp |
3,702 | def strftest1(self, now):
if test_support.verbose:
print "strftime test for", time.ctime(now)
now = self.now
# Make sure any characters that could be taken as regex syntax is
# escaped in escapestr()
expectations = (
('%a', calendar.day_abbr[now[6]], 'abbr... | ValueError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_strftime.py/StrftimeTest.strftest1 |
3,703 | def strftest2(self, now):
nowsecs = str(long(now))[:-1]
now = self.now
nonstandard_expectations = (
# These are standard but don't have predictable output
('%c', fixasctime(time.asctime(now)), 'near-asctime() format'),
('%x', '%02d/%02d/%02d' % (now[1], now[2], (... | ValueError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_strftime.py/StrftimeTest.strftest2 |
3,704 | def _abstract_atom_init(deftype, defvalue):
"""Return a constructor for an abstract `Atom` class."""
defitemsize = split_type(deftype)[1]
def __init__(self, itemsize=defitemsize, shape=(), dflt=defvalue):
assert self.kind in atom_map
try:
atomclass = atom_map[self.kind][itemsiz... | KeyError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/_abstract_atom_init |
3,705 | def _normalize_shape(shape):
"""Check that the `shape` is safe to be used and return it as a tuple."""
if isinstance(shape, (int, numpy.integer, int)):
if shape < 1:
raise ValueError("shape value must be greater than 0: %d"
% shape)
shape = (shape,) # N... | TypeError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/_normalize_shape |
3,706 | def _normalize_default(value, dtype):
"""Return `value` as a valid default of NumPy type `dtype`."""
# Create NumPy objects as defaults
# This is better in order to serialize them as attributes
if value is None:
value = 0
basedtype = dtype.base
try:
default = numpy.array(value, ... | ValueError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/_normalize_default |
3,707 | def _cmp_dispatcher(other_method_name):
"""Dispatch comparisons to a method of the *other* object.
Returns a new *rich comparison* method which dispatches calls to
the method `other_method_name` of the *other* object. If there is
no such method in the object, ``False`` is returned.
This is part o... | AttributeError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/_cmp_dispatcher |
3,708 | def _get_init_args(self):
"""Get a dictionary of instance constructor arguments.
This implementation works on classes which use the same names
for both constructor arguments and instance attributes.
"""
# @COMPATIBILITY: inspect.getargspec has been deprecated since
# ... | AttributeError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/Atom._get_init_args |
3,709 | def _checkbase(self, base):
"""Check the `base` storage atom."""
if base.kind == 'enum':
raise TypeError("can not use an enumerated atom "
"as a storage atom: %r" % base)
# Check whether the storage atom can represent concrete values
# in the enu... | ValueError | dataset/ETHPy150Open PyTables/PyTables/tables/atom.py/EnumAtom._checkbase |
3,710 | def sendMetrics(self, stats, prefix):
for key, value in stats.iteritems():
try:
float(value)
except (__HOLE__, ValueError):
continue
if key in ('version', 'pid'):
continue
path = '%s.%s' % (prefix, key)
... | TypeError | dataset/ETHPy150Open mochi/vor/vor/beanstalk.py/BeanstalkGraphiteService.sendMetrics |
3,711 | def autodiscover():
"""
Goes and imports the permissions submodule of every app in INSTALLED_APPS
to make sure the permission set classes are registered correctly.
"""
global LOADING
if LOADING:
return
LOADING = True
import imp
from django.conf import settings
for app i... | ImportError | dataset/ETHPy150Open jazzband/django-authority/authority/__init__.py/autodiscover |
3,712 | def to_python(self, value):
try:
return ObjectId(urlsafe_b64decode(value))
except (InvalidId, ValueError, __HOLE__):
raise ValidationError() | TypeError | dataset/ETHPy150Open pandemicsyn/stalker/stalkerweb/stalkerweb/stutils.py/ObjectIDConverter.to_python |
3,713 | def __str__(self):
try:
import cStringIO as StringIO
except __HOLE__:
import StringIO
output = StringIO.StringIO()
output.write(Exception.__str__(self))
# Check if we wrapped an exception and print that too.
if hasattr(self, 'exc_info'):
... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/template/__init__.py/TemplateSyntaxError.__str__ |
3,714 | def parse(self, parse_until=None):
if parse_until is None: parse_until = []
nodelist = self.create_nodelist()
while self.tokens:
token = self.next_token()
if token.token_type == TOKEN_TEXT:
self.extend_nodelist(nodelist, TextNode(token.contents), token)
... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/template/__init__.py/Parser.parse |
3,715 | def args_check(name, func, provided):
provided = list(provided)
plen = len(provided)
# Check to see if a decorator is providing the real function.
func = getattr(func, '_decorated_function', func)
args, varargs, varkw, defaults = getargspec(func)
# First argument is filte... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/template/__init__.py/FilterExpression.args_check |
3,716 | def resolve_variable(path, context):
"""
Returns the resolved variable, which may contain attribute syntax, within
the given context. The variable may be a hard-coded string (if it begins
and ends with single or double quote marks).
>>> c = {'article': {'section':'News'}}
>>> resolve_variable('... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/template/__init__.py/resolve_variable |
3,717 | def get_library(module_name):
lib = libraries.get(module_name, None)
if not lib:
try:
mod = __import__(module_name, {}, {}, [''])
except __HOLE__, e:
raise InvalidTemplateLibrary, "Could not load template library from %s, %s" % (module_name, e)
try:
li... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/template/__init__.py/get_library |
3,718 | def RAW(self, message):
try:
#Join up the message parts
if isinstance(message, (list, tuple)):
message = ' '.join(message)
#Raw Send but don't allow empty spam
if message is not None:
#Clean up messages
message = re.... | TypeError | dataset/ETHPy150Open facebook/pyaib/pyaib/irc.py/Context.RAW |
3,719 | def retrieve(self, url, destination, callback=None):
self.size = 0
time.clock()
try: urllib.urlretrieve(url, destination, self.progress)
except __HOLE__:
print '\n~ Download cancelled'
print '~'
for i in range(5):
try:
... | KeyboardInterrupt | dataset/ETHPy150Open eBay/restcommander/play-1.2.4/framework/pym/play/commands/modulesrepo.py/Downloader.retrieve |
3,720 | def create_default_config(config_dir, detect_location=True):
"""Create a default configuration file in given configuration directory.
Return path to new config file if success, None if failed.
"""
config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
info = {attr: default for attr, default, _, ... | IOError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/config.py/create_default_config |
3,721 | def __getattr__(self, name):
if name in self.__dict__:
return self.__dict__[name]
try:
return self[name]
except __HOLE__:
raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) | KeyError | dataset/ETHPy150Open samuel/kokki/kokki/utils.py/AttributeDictionary.__getattr__ |
3,722 | def main():
try:
cmd = TCeleryCommand()
cmd.execute_from_commandline()
except __HOLE__:
pass | KeyboardInterrupt | dataset/ETHPy150Open mher/tornado-celery/tcelery/__main__.py/main |
3,723 | def _get_container(self, thread_id, document_html, container, index):
if not document_html:
document_html = self.get_thread(thread_id).get("html")
if not document_html:
return None
tree = self.parse_document_html(document_html)
lists = list(tree.iter(conta... | IndexError | dataset/ETHPy150Open quip/quip-api/python/quip.py/QuipClient._get_container |
3,724 | def modified_time(self, name):
try:
modified = self.__get_blob_properties(name)['last-modified']
except (__HOLE__, KeyError):
return super(AzureStorage, self).modified_time(name)
modified = time.strptime(modified, '%a, %d %b %Y %H:%M:%S %Z')
modified = datetime.f... | TypeError | dataset/ETHPy150Open jschneier/django-storages/storages/backends/azure_storage.py/AzureStorage.modified_time |
3,725 | @staticmethod
def parse_spec(opts, spec):
"""Parse the comma-separated key=value configuration from the gen spec.
Names and semantics were inspired from subset of mcsoda parameters."""
cfg = {'cur-ops': 0,
'cur-gets': 0,
'cur-sets': 0,
'cur-ite... | ValueError | dataset/ETHPy150Open membase/membase-cli/pump_gen.py/GenSource.parse_spec |
3,726 | def output(self, **kwargs):
options = dict(self.options)
options['outfile'] = kwargs['outfile']
infiles = []
for infile in kwargs['content_meta']:
# type, full_filename, relative_filename
# In debug mode we use the full path so that in development we see changes ... | OSError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/style/uglify.py/UglifySourcemapFilter.output |
3,727 | @register.filter
def JSON(obj):
# json.dumps does not properly convert QueryDict array parameter to json
if isinstance(obj, QueryDict):
obj = dict(obj)
try:
return mark_safe(escape_script_tags(json.dumps(obj, default=json_handler)))
except __HOLE__ as e:
msg = ("Unserializable da... | TypeError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/templatetags/hq_shared_tags.py/JSON |
3,728 | @register.filter
def BOOL(obj):
try:
obj = obj.to_json()
except __HOLE__:
pass
return 'true' if obj else 'false' | AttributeError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/templatetags/hq_shared_tags.py/BOOL |
3,729 | @register.tag(name='captureas')
def do_captureas(parser, token):
"""
Assign to a context variable from within a template
{% captureas my_context_var %}<!-- anything -->{% endcaptureas %}
<h1>Nice job capturing {{ my_context_var }}</h1>
"""
try:
tag_name, args = token.contents.spl... | ValueError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/templatetags/hq_shared_tags.py/do_captureas |
3,730 | @register.simple_tag
def maintenance_alert():
try:
alert = (MaintenanceAlert.objects
.filter(active=True)
.order_by('-modified'))[0]
except __HOLE__:
return ''
else:
return format_html(
'<div class="alert alert-warning" style="text-align:... | IndexError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqwebapp/templatetags/hq_shared_tags.py/maintenance_alert |
3,731 | def _transstat(status, grouppath, dictpath, line):
"""Executes processing steps when reading a line"""
if status == 0:
raise MTLParseError(
"Status should not be '%s' after reading line:\n%s"
% (STATUSCODE[status], line))
elif status == 1:
currentdict = dictpath[-1]
... | IndexError | dataset/ETHPy150Open landsat-pds/landsat_ingestor/ingestor/mtlutils.py/_transstat |
3,732 | def _postprocess(valuestr):
"""
Takes value as str, returns str, int, float, date, datetime, or time
"""
# USGS has started quoting time sometimes. Grr, strip quotes in this case
intpattern = re.compile(r'^\-?\d+$')
floatpattern = re.compile(r'^\-?\d+\.\d+(E[+-]?\d\d+)?$')
datedtpattern = '... | ValueError | dataset/ETHPy150Open landsat-pds/landsat_ingestor/ingestor/mtlutils.py/_postprocess |
3,733 | def check_honeypot(request, form):
"""
Make sure that the hidden form field is empty, using django-honeypot.
"""
try:
from honeypot.decorators import verify_honeypot_value
return verify_honeypot_value(request, '') is None
except __HOLE__: # pragma: no cover
return True | ImportError | dataset/ETHPy150Open zsiciarz/django-envelope/envelope/spam_filters.py/check_honeypot |
3,734 | def stylesheet_call(self, path):
"""Return code to reference or embed stylesheet file `path`"""
if self.settings.embed_stylesheet:
try:
content = io.FileInput(source_path=path,
encoding='utf-8').read()
self.settings.recor... | IOError | dataset/ETHPy150Open zackw/header-survey/sphinx/ext/html5_output.py/BaseTranslator.stylesheet_call |
3,735 | def set_class_on_child(self, node, class_, index=0):
"""
Set class `class_` on the visible child no. index of `node`.
Do nothing if node has fewer children than `index`.
"""
children = [n for n in node if not isinstance(n, nodes.Invisible)]
try:
child = childr... | IndexError | dataset/ETHPy150Open zackw/header-survey/sphinx/ext/html5_output.py/BaseTranslator.set_class_on_child |
3,736 | def visit_image(self, node):
atts = {}
uri = node['uri']
# SVG works in <img> now
# place SWF images in an <object> element
types = {'.swf': 'application/x-shockwave-flash'}
ext = os.path.splitext(uri)[1].lower()
if ext == '.swf':
atts['data'] = uri
... | IOError | dataset/ETHPy150Open zackw/header-survey/sphinx/ext/html5_output.py/BaseTranslator.visit_image |
3,737 | def visit_image(self, node):
olduri = node['uri']
# rewrite the URI if the environment knows about it
if olduri in self.builder.images:
node['uri'] = posixpath.join(self.builder.imgpath,
self.builder.images[olduri])
if 'scale' in node... | IOError | dataset/ETHPy150Open zackw/header-survey/sphinx/ext/html5_output.py/HTML5Translator.visit_image |
3,738 | def RetrieveIPInfo(self, ip):
if not ip:
return (IPInfo.UNKNOWN, "No ip information.")
ip_str = utils.SmartStr(ip)
try:
return self.cache.Get(ip_str)
except KeyError:
pass
try:
ip = ipaddr.IPAddress(ip_str)
except __HOLE__:
return (IPInfo.UNKNOWN, "No ip informatio... | ValueError | dataset/ETHPy150Open google/grr/grr/lib/ip_resolver.py/IPResolver.RetrieveIPInfo |
3,739 | def create(self, **metadata):
metadata['created_at'] = NOW_GLANCE_FORMAT
metadata['updated_at'] = NOW_GLANCE_FORMAT
self._images.append(FakeImage(metadata))
try:
image_id = str(metadata['id'])
except __HOLE__:
# auto-generate an id if one wasn't provided... | KeyError | dataset/ETHPy150Open openstack/ironic/ironic/tests/unit/stubs.py/StubGlanceClient.create |
3,740 | def __getattr__(self, key):
try:
return self.__dict__['raw'][key]
except __HOLE__:
raise AttributeError(key) | KeyError | dataset/ETHPy150Open openstack/ironic/ironic/tests/unit/stubs.py/FakeImage.__getattr__ |
3,741 | def __setattr__(self, key, value):
try:
self.__dict__['raw'][key] = value
except __HOLE__:
raise AttributeError(key) | KeyError | dataset/ETHPy150Open openstack/ironic/ironic/tests/unit/stubs.py/FakeImage.__setattr__ |
3,742 | def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except __HOLE__:
exc_name = str(self.expected)
raise self.failureException(
"{0} not raised".format(exc_name))
if n... | AttributeError | dataset/ETHPy150Open wbond/oscrypto/tests/_unittest_compat.py/_AssertRaisesContext.__exit__ |
3,743 | def handle_noargs(self, **options):
center = options['center']
pattern = options['pattern']
size = options['size']
speed = options['speed']
steps = options['steps']
wrap = options['wrap']
if pattern is None:
states = [[None] * size] * size
els... | KeyboardInterrupt | dataset/ETHPy150Open aaugustin/django-c10k-demo/gameoflife/management/commands/gameoflife.py/Command.handle_noargs |
3,744 | def run(self):
self.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.sock.bind(('localhost',self.port))
except:
# If I can't bind, there is nothing I cand do
return
... | SystemExit | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/rt_debugger.py/Debugger.run |
3,745 | def pgcli_line_magic(line):
_logger.debug('pgcli magic called: %r', line)
parsed = sql.parse.parse(line, {})
conn = sql.connection.Connection.get(parsed['connection'])
try:
# A corresponding pgcli object already exists
pgcli = conn._pgcli
_logger.debug('Reusing existing pgcli')
... | AttributeError | dataset/ETHPy150Open dbcli/pgcli/pgcli/magic.py/pgcli_line_magic |
3,746 | def bayesdb_read_pandas_df(bdb, table, df, create=False, ifnotexists=False,
index=None):
"""Read data from a pandas dataframe into a table.
:param bayeslite.BayesDB bdb: BayesDB instance
:param str table: name of table
:param pandas.DataFrame df: pandas dataframe
:param bool create: if true... | ValueError | dataset/ETHPy150Open probcomp/bayeslite/src/read_pandas.py/bayesdb_read_pandas_df |
3,747 | def save_rib(self, file_name, bg=0, resolution=None, resfactor=1.0):
"""Save scene to a RenderMan RIB file.
Keyword Arguments:
file_name -- File name to save to.
bg -- Optional background option. If 0 then no background is
saved. If non-None then a background is saved. If l... | TypeError | dataset/ETHPy150Open enthought/mayavi/tvtk/pyface/tvtk_scene.py/TVTKScene.save_rib |
3,748 | def cancel(self):
''' Cancels the callback if it was scheduled to be called.
'''
if self._is_triggered:
self._is_triggered = False
try:
self.clock._events[self.cid].remove(self)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open kivy/kivy/kivy/clock.py/ClockEvent.cancel |
3,749 | def tick(self, curtime, remove):
# timeout happened ? (check also if we would miss from 5ms) this
# 5ms increase the accuracy if the timing of animation for
# example.
if curtime - self._last_dt < self.timeout - 0.005:
return True
# calculate current timediff for thi... | ValueError | dataset/ETHPy150Open kivy/kivy/kivy/clock.py/ClockEvent.tick |
3,750 | def check_dependencies(settings):
# Some of our checks require access to django.conf.settings, so
# tell Django about our settings.
#
from djblets.util.filesystem import is_exe_in_path
from reviewboard.admin.import_utils import has_module
dependency_error = settings.dependency_error
# Pyt... | OSError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/manage.py/check_dependencies |
3,751 | def run():
# Add the parent directory of 'manage.py' to the python path, so
# manage.py can be run from any directory.
# From http://www.djangosnippets.org/snippets/281/
sys.path.insert(0, dirname(dirname(abspath(__file__))))
# Python may insert the directory that manage.py is in into the Python
... | ImportError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/manage.py/run |
3,752 | def handle(self, *args, **options):
models_to_import = [Realm, Stream, UserProfile, Recipient, Subscription,
Client, Message, UserMessage, Huddle, DefaultStream, RealmAlias,
RealmFilter]
self.chunk_size = options["chunk_size"] # type: int # ignore mypy options bug
encodi... | IOError | dataset/ETHPy150Open zulip/zulip/zerver/management/commands/import_dump.py/Command.handle |
3,753 | def processor_for(content_model_or_slug, exact_page=False):
"""
Decorator that registers the decorated function as a page
processor for the given content model or slug.
When a page exists that forms the prefix of custom urlpatterns
in a project (eg: the blog page and app), the page will be
adde... | TypeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/pages/page_processors.py/processor_for |
3,754 | def autodiscover():
"""
Taken from ``django.contrib.admin.autodiscover`` and used to run
any calls to the ``processor_for`` decorator.
"""
global LOADED
if LOADED:
return
LOADED = True
for app in get_app_name_list():
try:
module = import_module(app)
ex... | ImportError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/pages/page_processors.py/autodiscover |
3,755 | def wrap(self, stream):
try:
while True:
ch = stream.next()
self.line.append(ch)
if ch == '\n':
for tok in self.emit_line():
yield tok
except __HOLE__:
for tok in self.emit_line():
... | StopIteration | dataset/ETHPy150Open brehaut/picoparse/picoparse/text.py/TextDiagnostics.wrap |
3,756 | def define_process_title(proc_title='twork'):
"""Define Custom Process Title
"""
try:
import setproctitle
setproctitle.setproctitle(proc_title)
except __HOLE__ as e:
gen_logger.error(e) | ImportError | dataset/ETHPy150Open bufferx/twork/twork/utils/common.py/define_process_title |
3,757 | def rm_fstab(name, device, config='/etc/fstab'):
'''
Remove the mount point from the fstab
CLI Example:
.. code-block:: bash
salt '*' mount.rm_fstab /mnt/foo /dev/sdg
'''
modified = False
criteria = _fstab_entry(name=name, device=device)
lines = []
try:
with salt... | IOError | dataset/ETHPy150Open saltstack/salt/salt/modules/mount.py/rm_fstab |
3,758 | def set_fstab(
name,
device,
fstype,
opts='defaults',
dump=0,
pass_num=0,
config='/etc/fstab',
test=False,
match_on='auto',
**kwargs):
'''
Verify that this mount is represented in the fstab, change the mount
to match the data pa... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/mount.py/set_fstab |
3,759 | def rm_automaster(name, device, config='/etc/auto_salt'):
'''
Remove the mount point from the auto_master
CLI Example:
.. code-block:: bash
salt '*' mount.rm_automaster /mnt/foo /dev/sdg
'''
contents = automaster(config)
if name not in contents:
return True
# The entry... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/mount.py/rm_automaster |
3,760 | def set_automaster(
name,
device,
fstype,
opts='',
config='/etc/auto_salt',
test=False,
**kwargs):
'''
Verify that this mount is represented in the auto_salt, change the mount
to match the data passed, or add the mount if it is not present.
CLI Ex... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/mount.py/set_automaster |
3,761 | def parse_Config(config_path):
"""
Parse PETRglobals.ConfigFileName. The file should be ; the default is PETR_config.ini
in the working directory but this can be changed using the -c option in the command
line. Most of the entries are obvious (but will eventually be documented) with the
exception of... | ValueError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/parse_Config |
3,762 | def open_FIN(filename, descrstr):
# opens the global input stream fin using filename;
# descrstr provides information about the file in the event it isn't found
global FIN
global FINline, FINnline, CurrentFINname
try:
FIN = io.open(filename, 'r', encoding='utf-8')
CurrentFINname = fi... | IOError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/open_FIN |
3,763 | def close_FIN():
# closes the global input stream fin.
# IOError should only happen during debugging or if something has seriously gone wrong
# with the system, so exit if this occurs.
global FIN
try:
FIN.close()
except __HOLE__:
print("\aError: Could not close the input file")
... | IOError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/close_FIN |
3,764 | def read_verb_dictionary(verb_path):
""" Reads the verb dictionary from VerbFileName """
"""
======= VERB DICTIONARY ORGANIZATION =======
The verb dictionary consists of a set of synsets followed by a series of verb
synonyms and patterns.
VERB SYNONYM BLOCKS AND PATTERNS
A verb synonym b... | ValueError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/read_verb_dictionary |
3,765 | def dstr_to_ordate(datestring):
""" Computes an ordinal date from a Gregorian calendar date string YYYYMMDD or YYMMDD."""
"""
This uses the 'ANSI date' with the base -- ordate == 1 -- of 1 Jan 1601. This derives
from [OMG!] COBOL (see http://en.wikipedia.org/wiki/Julian_day) but in fact should
work fairly w... | ValueError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/dstr_to_ordate |
3,766 | def read_actor_dictionary(actorfile):
""" Reads a TABARI-style actor dictionary. """
"""
Actor dictionary list elements:
Actors are stored in a dictionary of a list of pattern lists keyed on the first word
of the phrase. The pattern lists are sorted by length.
The individual pattern lists begin with an inte... | ValueError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/read_actor_dictionary |
3,767 | def read_pipeline_input(pipeline_list):
"""
Reads input from the processing pipeline and MongoDB and creates the global
holding dictionary. Please consult the documentation for more information
on the format of the global holding dictionary. The function iteratively
parses each file so is capable of... | IndexError | dataset/ETHPy150Open openeventdata/petrarch/petrarch/PETRreader.py/read_pipeline_input |
3,768 | def main():
parser = argparse.ArgumentParser(prog='enjarify', description='Translates Dalvik bytecode (.dex or .apk) to Java bytecode (.jar)')
parser.add_argument('inputfile')
parser.add_argument('-o', '--output', help='Output .jar file. Default is [input-filename]-enjarify.jar.')
parser.add_argument('-... | NameError | dataset/ETHPy150Open ajinabraham/Mobile-Security-Framework-MobSF/StaticAnalyzer/tools/enjarify/enjarify/main.py/main |
3,769 | def check_version(branch, latest_hash=None):
if branch == 'master':
remote_dir = 'devel'
regex = ("(?<=This documentation is for version <b>\d{1}\.\d{1}\."
"\d{1}\.dev-)(\w{7})")
else:
remote_dir = 'stable'
regex = ("(?<=This documentation is for the <b>)(\d{1}\.... | AttributeError | dataset/ETHPy150Open statsmodels/statsmodels/tools/update_web.py/check_version |
3,770 | def use(wcspkg, raise_err=True):
"""Choose WCS package."""
global coord_types, wcs_configured, WCS, \
have_kapteyn, kapwcs, \
have_astlib, astWCS, astCoords, \
have_starlink, Ast, Atl, \
have_astropy, pywcs, pyfits, astropy, coordinates, units
if wcspkg == 'kapte... | ImportError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcsmod.py/use |
3,771 | def load_header(self, header, fobj=None):
from astropy.wcs.utils import wcs_to_celestial_frame
try:
# reconstruct a pyfits header, because otherwise we take an
# incredible performance hit in astropy.wcs
self.header = pyfits.Header(header.items())
self.lo... | ValueError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcsmod.py/AstropyWCS2.load_header |
3,772 | def pixtocoords(self, idxs, system=None, coords='data'):
if self.coordsys == 'raw':
raise WCSError("No usable WCS")
if system is None:
system = 'icrs'
# Get a coordinates object based on ra/dec wcs transform
ra_deg, dec_deg = self.pixtoradec(idxs, coords=coords... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcsmod.py/AstropyWCS.pixtocoords |
3,773 | def get_pixel_coordinates(self):
try:
cd11 = float(self.get_keyword('CD1_1'))
cd12 = float(self.get_keyword('CD1_2'))
cd21 = float(self.get_keyword('CD2_1'))
cd22 = float(self.get_keyword('CD2_2'))
except Exception as e:
cdelt1 = float(self.ge... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcsmod.py/BareBonesWCS.get_pixel_coordinates |
3,774 | def get_coord_system_name(header):
"""Return an appropriate key code for the axes coordinate system by
examining the FITS header.
"""
try:
ctype = header['CTYPE1'].strip().upper()
except KeyError:
try:
# see if we have an "RA" header
ra = header['RA']
... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcsmod.py/get_coord_system_name |
3,775 | def __init__(self, values=None, maximize=True):
if values is None:
values = []
self.values = values
try:
iter(maximize)
except __HOLE__:
maximize = [maximize for v in values]
self.maximize = maximize | TypeError | dataset/ETHPy150Open aarongarrett/inspyred/inspyred/ec/emo.py/Pareto.__init__ |
3,776 | def evolve(self, generator, evaluator, pop_size=1, seeds=None, maximize=True, bounder=None, **args):
final_pop = ec.EvolutionaryComputation.evolve(self, generator, evaluator, pop_size, seeds, maximize, bounder, **args)
try:
del self.archiver.grid_population
except AttributeError:... | AttributeError | dataset/ETHPy150Open aarongarrett/inspyred/inspyred/ec/emo.py/PAES.evolve |
3,777 | def pop_frame():
"""
Pop a specific frame from the dictionary.
"""
try:
_thread_locals.d_stack.pop(get_tpid_key())
except __HOLE__:
print "[WARNING] Exception at 'expedient.common.middleware.threadlocals.ThreadLocals': tried to access to permittees stack when it was already empty. Th... | KeyError | dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/middleware/threadlocals.py/pop_frame |
3,778 | def date(date_str):
try:
return dt.strptime(date_str, "%Y-%m-%d")
except __HOLE__:
msg = "Not a valid date: '{date_str}'. "\
"Expected format: YYYY-MM-DD.".format(date_str=date_str)
raise argparse.ArgumentTypeError(msg) | ValueError | dataset/ETHPy150Open PressLabs/silver/silver/management/commands/generate_docs.py/date |
3,779 | def test_get_system_time(self):
'''
Test to get system time
'''
tm = datetime.strftime(datetime.now(), "%I:%M %p")
win_tm = win_system.get_system_time()
try:
self.assertEqual(win_tm, tm)
except __HOLE__:
# handle race condition
... | AssertionError | dataset/ETHPy150Open saltstack/salt/tests/unit/modules/win_system_test.py/WinSystemTestCase.test_get_system_time |
3,780 | def system_methodHelp(self, method_name):
"""system.methodHelp('add') => "Adds two integers together"
Returns a string containing documentation for the specified method."""
method = None
if method_name in self.funcs:
method = self.funcs[method_name]
elif self.instan... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/SimpleXMLRPCDispatcher.system_methodHelp |
3,781 | def _dispatch(self, method, params):
"""Dispatches the XML-RPC method.
XML-RPC calls are forwarded to a registered function that
matches the called XML-RPC method name. If no such function
exists then the call is forwarded to the registered instance,
if available.
If th... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/SimpleXMLRPCDispatcher._dispatch |
3,782 | def do_POST(self):
"""Handles the HTTP POST request.
Attempts to interpret all HTTP POST requests as XML-RPC calls,
which are forwarded to the server's _dispatch method for handling.
"""
# Check that the path is legal
if not self.is_rpc_path_valid():
self.re... | NotImplementedError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/SimpleXMLRPCRequestHandler.do_POST |
3,783 | def decode_request_content(self, data):
#support gzip encoding of request
encoding = self.headers.get("content-encoding", "identity").lower()
if encoding == "identity":
return data
if encoding == "gzip":
try:
return gzip_decode(data)
ex... | ValueError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/SimpleXMLRPCRequestHandler.decode_request_content |
3,784 | def handle_request(self, request_text=None):
"""Handle a single XML-RPC request passed through a CGI post method.
If no XML data is given then it is read from stdin. The resulting
XML-RPC response is printed to stdout along with the correct HTTP
headers.
"""
if request_... | ValueError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/CGIXMLRPCRequestHandler.handle_request |
3,785 | def generate_html_documentation(self):
"""generate_html_documentation() => html documentation for the server
Generates HTML documentation for the server using introspection for
installed functions and instances that do not implement the
_dispatch method. Alternatively, instances can cho... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/xmlrpc/server.py/XMLRPCDocGenerator.generate_html_documentation |
3,786 | def get_filters(self):
filters = {'is_public': None}
filter_field = self.table.get_filter_field()
filter_string = self.table.get_filter_string()
filter_action = self.table._meta._filter_action
if filter_field and filter_string and (
filter_action.is_api_filter(fil... | ValueError | dataset/ETHPy150Open CiscoSystems/avos/openstack_dashboard/dashboards/admin/images/views.py/IndexView.get_filters |
3,787 | def test_create_raise_exception_with_bad_keys(self):
try:
Address.create({"customer_id": "12345", "bad_key": "value"})
self.assertTrue(False)
except __HOLE__ as e:
self.assertEquals("'Invalid keys: bad_key'", str(e)) | KeyError | dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_address.py/TestAddress.test_create_raise_exception_with_bad_keys |
3,788 | def test_create_raises_error_if_no_customer_id_given(self):
try:
Address.create({"country_name": "United States of America"})
self.assertTrue(False)
except __HOLE__ as e:
self.assertEquals("'customer_id must be provided'", str(e)) | KeyError | dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_address.py/TestAddress.test_create_raises_error_if_no_customer_id_given |
3,789 | def test_create_raises_key_error_if_given_invalid_customer_id(self):
try:
Address.create({"customer_id": "!@#$%"})
self.assertTrue(False)
except __HOLE__ as e:
self.assertEquals("'customer_id contains invalid characters'", str(e)) | KeyError | dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_address.py/TestAddress.test_create_raises_key_error_if_given_invalid_customer_id |
3,790 | def test_update_raise_exception_with_bad_keys(self):
try:
Address.update("customer_id", "address_id", {"bad_key": "value"})
self.assertTrue(False)
except __HOLE__ as e:
self.assertEquals("'Invalid keys: bad_key'", str(e)) | KeyError | dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_address.py/TestAddress.test_update_raise_exception_with_bad_keys |
3,791 | def crawl_path(self, path_descriptor):
info = self.path_info[path_descriptor.key()] = {}
for path, dirs, files in os.walk(path_descriptor.path):
for file in [os.path.abspath(os.path.join(path, filename)) for filename in files]:
try:
info[file] = os.path.ge... | OSError | dataset/ETHPy150Open tmc/mutter/mutter/watchers.py/ModTimeWatcher.crawl_path |
3,792 | @validator
def ipv6(value):
"""
Return whether or not given value is a valid IP version 6 address.
This validator is based on `WTForms IPAddress validator`_.
.. _WTForms IPAddress validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> ipv6('... | ValueError | dataset/ETHPy150Open SickRage/SickRage/lib/validators/ip_address.py/ipv6 |
3,793 | def buildReactor(self):
"""
Create and return a reactor using C{self.reactorFactory}.
"""
try:
from twisted.internet.cfreactor import CFReactor
from twisted.internet import reactor as globalReactor
except __HOLE__:
pass
else:
... | ImportError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/test/reactormixins.py/ReactorBuilder.buildReactor |
3,794 | def LinkFunc(target, source, env):
# Relative paths cause problems with symbolic links, so
# we use absolute paths, which may be a problem for people
# who want to move their soft-linked src-trees around. Those
# people should use the 'hard-copy' mode, softlinks cannot be
# used for that; at least I... | OSError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/LinkFunc |
3,795 | def do_diskcheck_match(node, predicate, errorfmt):
result = predicate()
try:
# If calling the predicate() cached a None value from stat(),
# remove it so it doesn't interfere with later attempts to
# build this Node as we walk the DAG. (This isn't a great way
# to do this, we're... | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/do_diskcheck_match |
3,796 | def do_diskcheck_rcs(node, name):
try:
rcs_dir = node.rcs_dir
except __HOLE__:
if node.entry_exists_on_disk('RCS'):
rcs_dir = node.Dir('RCS')
else:
rcs_dir = None
node.rcs_dir = rcs_dir
if rcs_dir:
return rcs_dir.entry_exists_on_disk(name+',v')... | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/do_diskcheck_rcs |
3,797 | def do_diskcheck_sccs(node, name):
try:
sccs_dir = node.sccs_dir
except __HOLE__:
if node.entry_exists_on_disk('SCCS'):
sccs_dir = node.Dir('SCCS')
else:
sccs_dir = None
node.sccs_dir = sccs_dir
if sccs_dir:
return sccs_dir.entry_exists_on_disk... | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/do_diskcheck_sccs |
3,798 | def __getattr__(self, name):
# This is how we implement the "special" attributes
# such as base, posix, srcdir, etc.
try:
attr_function = self.dictSpecialAttrs[name]
except KeyError:
try:
attr = SCons.Util.Proxy.__getattr__(self, name)
... | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/EntryProxy.__getattr__ |
3,799 | def _save_str(self):
try:
return self._memo['_save_str']
except __HOLE__:
pass
result = sys.intern(self._get_str())
self._memo['_save_str'] = result
return result | KeyError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/FS.py/Base._save_str |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.