Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,300 | def test_build_traceback(self):
fault = None
try:
raise TypeError("Unknown type")
except __HOLE__:
fault = amf0.build_fault(include_traceback=True, *sys.exc_info())
self.assertTrue(isinstance(fault, remoting.ErrorFault))
self.assertEqual(fault.level, 'er... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/tests/test_gateway.py/FaultTestCase.test_build_traceback |
2,301 | def test_encode(self):
encoder = pyamf.get_encoder(pyamf.AMF0)
decoder = pyamf.get_decoder(pyamf.AMF0)
decoder.stream = encoder.stream
try:
raise TypeError("Unknown type")
except __HOLE__:
encoder.writeElement(amf0.build_fault(*sys.exc_info()))
b... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/tests/test_gateway.py/FaultTestCase.test_encode |
2,302 | def __init__(self, conf, engine=None):
super(SQLAlchemyBackend, self).__init__(conf)
if engine is not None:
self._engine = engine
self._owns_engine = False
else:
self._engine = self._create_engine(self._conf)
self._owns_engine = True
self._... | TypeError | dataset/ETHPy150Open openstack/taskflow/taskflow/persistence/backends/impl_sqlalchemy.py/SQLAlchemyBackend.__init__ |
2,303 | def _run_services(self, services):
"""Service runner main loop."""
if not services:
self._logger.critical('no services to run, bailing!')
return
service_thread_map = {service: threading.Thread(target=service.run) for service in services}
# Start services.
for service, service_thread in... | RuntimeError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/pantsd/pants_daemon.py/PantsDaemon._run_services |
2,304 | def iter_paths(filepath):
if not filepath:
return
try:
with open(filepath) as f:
for line in f:
# Use `#` for comments
if line.startswith("#"):
continue
# Remove trailing spaces and newlines, then normalize to avoid ... | IOError | dataset/ETHPy150Open tmr232/Sark/plugins/plugin_loader.py/iter_paths |
2,305 | def init(self):
# Show usage message.
usage_message = ["Loading plugins from system-wide and user-specific lists:",
" System-wide List: {}".format(SYS_PLUGIN_LIST_PATH),
" User-specific List: {}".format(USER_PLUGIN_LIST_PATH)]
if PROJEC... | IOError | dataset/ETHPy150Open tmr232/Sark/plugins/plugin_loader.py/PluginLoader.init |
2,306 | def relay(self, bot, relay_ins):
def channel_for(channel_id):
return bot.slack_client.server.channels.find(channel_id)
def name(channel):
if self.name:
if not channel.name.startswith(self.name):
return None
return channel.name.... | ImportError | dataset/ETHPy150Open youknowone/slairck/ircbot.py/IrcBot.relay |
2,307 | def ensure_dependencies():
if not shell('python', '--version', capture=True).startswith('Python 2.7'):
raise EnvironmentError('Python 2.7 is required.')
try:
shell('pg_config' + ext, capture=True)
except __HOLE__ as e:
if e.errno != os.errno.ENOENT:
raise
raise E... | OSError | dataset/ETHPy150Open gratipay/gratipay.com/gratipay.py/ensure_dependencies |
2,308 | @register.filter
def sort_by(items, attr):
"""
General sort filter - sorts by either attribute or key.
"""
def key_func(item):
try:
return getattr(item, attr)
except AttributeError:
try:
return item[attr]
except __HOLE__:
... | TypeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/sort_by |
2,309 | @register.tag
def ifinstalled(parser, token):
"""
Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn... | ValueError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/ifinstalled |
2,310 | @register.simple_tag
def thumbnail(image_url, width, height, upscale=True, quality=95, left=.5,
top=.5, padding=False, padding_color="#fff"):
"""
Given the URL to an image, resizes the image using the given width
and height on the first time it is requested, and returns the URL
to the new ... | OSError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/thumbnail |
2,311 | @register.filter
def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
filter_names = settings.RICHTEXT_FILTERS
if not filter_names:
try:
filter_names = [setti... | AttributeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/richtext_filters |
2,312 | @register.to_end_tag
def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permis... | AttributeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/editable |
2,313 | def admin_app_list(request):
"""
Adopted from ``django.contrib.admin.sites.AdminSite.index``.
Returns a list of lists of models grouped and ordered according to
``mezzanine.conf.ADMIN_MENU_ORDER``. Called from the
``admin_dropdown_menu`` template tag as well as the ``app_list``
dashboard widget.... | KeyError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/admin_app_list |
2,314 | @register.inclusion_tag("admin/includes/dropdown_menu.html",
takes_context=True)
def admin_dropdown_menu(context):
"""
Renders the app list for the admin dropdown menu navigation.
"""
user = context["request"].user
template_vars = {}
if user.is_staff:
template_var... | ObjectDoesNotExist | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/admin_dropdown_menu |
2,315 | @register.simple_tag(takes_context=True)
def translate_url(context, language):
"""
Translates the current URL for the given language code, eg:
{% translate_url de %}
"""
try:
request = context["request"]
except __HOLE__:
return ""
view = resolve(request.path)
current... | KeyError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/templatetags/mezzanine_tags.py/translate_url |
2,316 | def validate_bug_tracker(input_url):
"""Validate a bug tracker URL.
This checks that the given URL string contains one (and only one) `%s`
Python format specification type (no other types are supported).
"""
try:
# Ignore escaped `%`'s
test_url = input_url.replace('%%', '')
... | TypeError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/admin/validation.py/validate_bug_tracker |
2,317 | def validate_bug_tracker_base_hosting_url(input_url):
"""Check that hosting service bug URLs don't contain %s."""
# Try formatting the URL using an empty tuple to verify that it
# doesn't contain any format characters.
try:
input_url % ()
except __HOLE__:
raise ValidationError([
... | TypeError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/admin/validation.py/validate_bug_tracker_base_hosting_url |
2,318 | def test_migrate_gis(self):
"""
Tests basic usage of the migrate command when a model uses Geodjango
fields. Regression test for ticket #22001:
https://code.djangoproject.com/ticket/22001
It's also used to showcase an error in migrations where spatialite is
enabled and g... | NotImplementedError | dataset/ETHPy150Open django/django/tests/gis_tests/gis_migrations/test_commands.py/MigrateTests.test_migrate_gis |
2,319 | def notify_errors(request_id, error):
"""Add errors to a config request."""
try:
_REQUESTS[request_id].notify_errors(request_id, error)
except __HOLE__:
# If request_id does not exist
pass | KeyError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/configurator.py/notify_errors |
2,320 | def request_done(request_id):
"""Mark a configuration request as done."""
try:
_REQUESTS.pop(request_id).request_done(request_id)
except __HOLE__:
# If request_id does not exist
pass | KeyError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/configurator.py/request_done |
2,321 | def _get_instance(hass):
"""Get an instance per hass object."""
try:
return _INSTANCES[hass]
except __HOLE__:
_INSTANCES[hass] = Configurator(hass)
if DOMAIN not in hass.config.components:
hass.config.components.append(DOMAIN)
return _INSTANCES[hass] | KeyError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/configurator.py/_get_instance |
2,322 | def from_url(url, db=None):
"""Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provided.
"""
url = urlparse(url)
# Make sure it's a redis database.
if url.scheme:
assert url.scheme... | ValueError | dataset/ETHPy150Open kumar303/jstestnet/vendor-local/redis-2.4.13/redis/utils.py/from_url |
2,323 | def destroy_datastore(datastore_path, history_path):
"""Destroys the appengine datastore at the specified paths."""
for path in [datastore_path, history_path]:
if not path: continue
try:
os.remove(path)
except __HOLE__, e:
if e.errno != 2:
logging.error("Failed to clear datastore: %s... | OSError | dataset/ETHPy150Open CollabQ/CollabQ/appengine_django/db/base.py/destroy_datastore |
2,324 | def _from_json(self, datastring):
try:
return jsonutils.loads(datastring)
except __HOLE__:
msg = _("cannot understand JSON")
raise exceptions.MalformedRequestBody(msg) | ValueError | dataset/ETHPy150Open openstack/sahara/sahara/utils/wsgi.py/JSONDeserializer._from_json |
2,325 | def AttachParents(self, tree, parent = None):
""" Attach parents to the tree.
Also create the cache at the each node, by exercising
tree.GetFlattenedChildren()."""
tree.SetParent(parent)
for c in tree.GetFlattenedChildren():
if c is not None:
try:
self.AttachParents(c, tree)
... | AttributeError | dataset/ETHPy150Open spranesh/Redhawk/redhawk/common/tree_converter.py/TreeConverter.AttachParents |
2,326 | def pytest_configure():
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
try:
django.setup()
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open jpadilla/django-jwt-auth/tests/conftest.py/pytest_configure |
2,327 | def list_directory(path, ignore_directories, ignore_extensions):
for root, dirs, files in os.walk(path):
# skip over directories to ignore
for dir in ignore_directories:
try:
dirs.remove(dir)
except __HOLE__:
pass
# we are interested in... | ValueError | dataset/ETHPy150Open faassen/bowerstatic/bowerstatic/autoversion.py/list_directory |
2,328 | def build(runas,
tgt,
dest_dir,
spec,
sources,
deps,
env,
template,
saltenv='base',
log_dir='/var/log/salt/pkgbuild'): # pylint: disable=unused-argument
'''
Given the package destination directory, the tarball containing ... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/debbuild.py/build |
2,329 | def parse_creation(creation_string):
"""Parses creation string from header format.
Parse creation date of the format:
YYYY-mm-dd HH:MM:SS.ffffff
Y: Year
m: Month (01-12)
d: Day (01-31)
H: Hour (00-24)
M: Minute (00-59)
S: Second (00-59)
f: Microsecond
Args:
creation_string:... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/blobstore/blobstore.py/parse_creation |
2,330 | def loadPrices(self):
success = False
for priority in self.loadPriorities:
try:
getattr(self, priority)()
success = True
break
except URLError as e:
print "Error loading " + priority + " url " + str(e)
... | ValueError | dataset/ETHPy150Open OpenBazaar/OpenBazaar-Server/market/btcprice.py/BtcPrice.loadPrices |
2,331 | def _fit_transform(self, X):
"""Assumes X contains only categorical features."""
X = check_array(X, dtype=np.int)
if np.any(X < 0):
raise ValueError("X needs to contain only non-negative integers.")
n_samples, n_features = X.shape
if (isinstance(self.n_values, six.str... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/preprocessing/data.py/OneHotEncoder._fit_transform |
2,332 | @response_server.route('/weather/', methods=['GET', 'POST'])
def weather():
# Get destination from url query string:
# 'node' : destination
# 'Digits' : input digits from user
if request.method == 'POST':
dtmf = request.form.get('Digits', -1)
else:
dtmf = -1
try:
dtmf = i... | ValueError | dataset/ETHPy150Open plivo/plivohelper-python/examples/weatherbyphone/weather.py/weather |
2,333 | @contextmanager
def TemporaryDirectory(suffix='', prefix=None, dir=None):
name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
try:
yield name
finally:
try:
shutil.rmtree(name)
except __HOLE__ as e:
# ENOENT - no such file or directory
... | OSError | dataset/ETHPy150Open airbnb/airflow/airflow/utils/file.py/TemporaryDirectory |
2,334 | def _really_load(self, f, filename, ignore_discard, ignore_expires):
now = time.time()
magic = f.readline()
if not re.search(self.magic_re, magic):
f.close()
raise LoadError(
"%r does not look like a Netscape format cookies file" %
filenam... | IOError | dataset/ETHPy150Open babble/babble/include/jython/Lib/_MozillaCookieJar.py/MozillaCookieJar._really_load |
2,335 | def play_music(self, lib, opts, args):
"""Execute query, create temporary playlist and execute player
command passing that playlist, at request insert optional arguments.
"""
command_str = config['play']['command'].get()
if not command_str:
command_str = util.open_any... | OSError | dataset/ETHPy150Open beetbox/beets/beetsplug/play.py/PlayPlugin.play_music |
2,336 | def _compute_loss(self, model_output):
""" Computes the loss for the whole batch.
Notes:
------
Unless overriden, the default behavior is to return the mean of all individual losses.
"""
try:
return T.mean(self.losses)
except __HOLE__:
rai... | NotImplementedError | dataset/ETHPy150Open SMART-Lab/smartlearner/smartlearner/interfaces/loss.py/Loss._compute_loss |
2,337 | def get(self, *args, **kwargs):
'''Service a GET request to the '/map' URI.
The 'bbox' parameter contains 4 coordinates "l" (w), "b" (s),
"r" (e) and "t" (n).'''
# Sanity check the input.
bbox_arg = self.get_argument('bbox', None)
if not bbox_arg:
ra... | ValueError | dataset/ETHPy150Open MapQuest/mapquest-osm-server/src/python/frontend/maphandler.py/MapHandler.get |
2,338 | def _flush_stream(self, stream):
try:
stream.flush()
except __HOLE__:
pass | IOError | dataset/ETHPy150Open aws/aws-cli/awscli/formatter.py/Formatter._flush_stream |
2,339 | def __call__(self, command_name, response, stream=None):
if stream is None:
# Retrieve stdout on invocation instead of at import time
# so that if anything wraps stdout we'll pick up those changes
# (specifically colorama on windows wraps stdout).
stream = self._g... | IOError | dataset/ETHPy150Open aws/aws-cli/awscli/formatter.py/FullyBufferedFormatter.__call__ |
2,340 | def _format_response(self, command_name, response, stream):
if self._build_table(command_name, response):
try:
self.table.render(stream)
except __HOLE__:
# If they're piping stdout to another process which exits before
# we're done writing ... | IOError | dataset/ETHPy150Open aws/aws-cli/awscli/formatter.py/TableFormatter._format_response |
2,341 | def __send_request_json(self, request):
req = urllib2.Request(url=request)
req.add_header('Accept', 'application/json')
try:
response = urllib2.urlopen(req)
assert response.code == 200
data = response.read()
return json.loads(data.decode('utf-8'))
... | ValueError | dataset/ETHPy150Open marcuz/libpynexmo/nexmomessage/nexmo.py/Nexmo.__send_request_json |
2,342 | def start(self, config_file):
cmdline = [self.path, 'run', config_file]
stdout = sys.stdout if not isinstance(sys.stdout, StringIO) else None
stderr = sys.stderr if not isinstance(sys.stderr, StringIO) else None
try:
self.process = self.executor.execute(cmdline,
... | OSError | dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/pbench.py/PBenchTool.start |
2,343 | def check_if_installed(self):
self.log.debug("Trying phantom: %s", self.tool_path)
try:
pbench = shell_exec([self.tool_path], stderr=subprocess.STDOUT)
pbench_out, pbench_err = pbench.communicate()
self.log.debug("PBench check: %s", pbench_out)
if pbench_e... | OSError | dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/pbench.py/PBench.check_if_installed |
2,344 | def lookup_casstype_simple(casstype):
"""
Given a Cassandra type name (either fully distinguished or not), hand
back the CassandraType class responsible for it. If a name is not
recognized, a custom _UnrecognizedType subclass will be created for it.
This function does not handle complex types (so n... | KeyError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/lookup_casstype_simple |
2,345 | def lookup_casstype(casstype):
"""
Given a Cassandra type as a string (possibly including parameters), hand
back the CassandraType class responsible for it. If a name is not
recognized, a custom _UnrecognizedType subclass will be created for it.
Example:
>>> lookup_casstype('org.apache.cas... | AssertionError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/lookup_casstype |
2,346 | @staticmethod
def serialize(dec, protocol_version):
try:
sign, digits, exponent = dec.as_tuple()
except __HOLE__:
try:
sign, digits, exponent = Decimal(dec).as_tuple()
except Exception:
raise TypeError("Invalid type for Decimal valu... | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/DecimalType.serialize |
2,347 | @staticmethod
def serialize(uuid, protocol_version):
try:
return uuid.bytes
except __HOLE__:
raise TypeError("Got a non-UUID object for a UUID value") | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/UUIDType.serialize |
2,348 | @staticmethod
def serialize(var, protocol_version):
try:
return var.encode('ascii')
except __HOLE__:
return var | UnicodeDecodeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/AsciiType.serialize |
2,349 | @staticmethod
def interpret_datestring(val):
if val[-5] in ('+', '-'):
offset = (int(val[-4:-2]) * 3600 + int(val[-2:]) * 60) * int(val[-5] + '1')
val = val[:-5]
else:
offset = -time.timezone
for tformat in cql_timestamp_formats:
try:
... | ValueError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/DateType.interpret_datestring |
2,350 | @staticmethod
def serialize(v, protocol_version):
try:
# v is datetime
timestamp_seconds = calendar.timegm(v.utctimetuple())
timestamp = timestamp_seconds * 1e3 + getattr(v, 'microsecond', 0) / 1e3
except __HOLE__:
try:
timestamp = cale... | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/DateType.serialize |
2,351 | @staticmethod
def serialize(timeuuid, protocol_version):
try:
return timeuuid.bytes
except __HOLE__:
raise TypeError("Got a non-UUID object for a UUID value") | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/TimeUUIDType.serialize |
2,352 | @staticmethod
def serialize(val, protocol_version):
try:
days = val.days_from_epoch
except __HOLE__:
if isinstance(val, six.integer_types):
# the DB wants offset int values, but util.Date init takes days from epoch
# here we assume int values a... | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/SimpleDateType.serialize |
2,353 | @staticmethod
def serialize(val, protocol_version):
try:
nano = val.nanosecond_time
except __HOLE__:
nano = util.Time(val).nanosecond_time
return int64_pack(nano) | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/TimeType.serialize |
2,354 | @staticmethod
def serialize(ustr, protocol_version):
try:
return ustr.encode('utf-8')
except __HOLE__:
# already utf-8
return ustr | UnicodeDecodeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/UTF8Type.serialize |
2,355 | @classmethod
def serialize_safe(cls, themap, protocol_version):
key_type, value_type = cls.subtypes
pack = int32_pack if protocol_version >= 3 else uint16_pack
buf = io.BytesIO()
buf.write(pack(len(themap)))
try:
items = six.iteritems(themap)
except __HOLE... | AttributeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/MapType.serialize_safe |
2,356 | @classmethod
def evict_udt_class(cls, keyspace, udt_name):
if six.PY2 and isinstance(udt_name, unicode):
udt_name = udt_name.encode('utf-8')
try:
del cls._cache[(keyspace, udt_name)]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/UserType.evict_udt_class |
2,357 | @classmethod
def serialize_safe(cls, val, protocol_version):
proto_version = max(3, protocol_version)
buf = io.BytesIO()
for i, (fieldname, subtype) in enumerate(zip(cls.fieldnames, cls.subtypes)):
# first treat as a tuple, else by custom type
try:
ite... | TypeError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/UserType.serialize_safe |
2,358 | @classmethod
def _make_udt_tuple_type(cls, name, field_names):
# fallback to positional named, then unnamed tuples
# for CQL identifiers that aren't valid in Python,
try:
t = namedtuple(name, field_names)
except ValueError:
try:
t = namedtuple(... | ValueError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqltypes.py/UserType._make_udt_tuple_type |
2,359 | def root_bdm(self):
"""It only makes sense to call this method when the
BlockDeviceMappingList contains BlockDeviceMappings from
exactly one instance rather than BlockDeviceMappings from
multiple instances.
For example, you should not call this method from a
BlockDeviceM... | StopIteration | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/objects/block_device.py/BlockDeviceMappingList.root_bdm |
2,360 | def bootstrap_twilio_gateway(apps, twilio_rates_filename):
currency_class = apps.get_model('accounting', 'Currency') if apps else Currency
sms_gateway_fee_class = apps.get_model('smsbillables', 'SmsGatewayFee') if apps else SmsGatewayFee
sms_gateway_fee_criteria_class = apps.get_model('smsbillables', 'SmsGa... | IndexError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/smsbillables/management/commands/bootstrap_twilio_gateway.py/bootstrap_twilio_gateway |
2,361 | def load_backend(self, path):
module_name, attr_name = path.rsplit('.', 1)
try:
mod = import_module(module_name)
except (ImportError, ValueError), e:
raise ImproperlyConfigured('Error importing backend module %s: "%s"'
% (module_name, e))
try:
... | AttributeError | dataset/ETHPy150Open adieu/django-dbindexer/dbindexer/resolver.py/Resolver.load_backend |
2,362 | def test_sync_tool(tmpdir):
# test non-existing destination
try:
_SyncTool(client, 'should-not-exist', None, None, None)
except __HOLE__ as ve:
assert str(ve) == 'destination must exist and be a directory'
# test existing destination, no aoi.geojson
td = tmpdir.mkdir('sync-dest')
... | ValueError | dataset/ETHPy150Open planetlabs/planet-client-python/tests/test_sync.py/test_sync_tool |
2,363 | def get_process_memory():
if get_process_memory.psutil_process is None:
try:
import psutil
except ImportError:
get_process_memory.psutil_process = False
else:
pid = os.getpid()
get_process_memory.psutil_process = psutil.Process(pid)
if get... | IOError | dataset/ETHPy150Open wyplay/pytracemalloc/tracemalloc.py/get_process_memory |
2,364 | def _lazy_import_pickle():
# lazy loader for the pickle module
global pickle
if pickle is None:
try:
import cPickle as pickle
except __HOLE__:
import pickle
return pickle | ImportError | dataset/ETHPy150Open wyplay/pytracemalloc/tracemalloc.py/_lazy_import_pickle |
2,365 | @classmethod
def load(cls, filename):
pickle = _lazy_import_pickle()
try:
with open(filename, "rb") as fp:
data = pickle.load(fp)
except Exception:
err = sys.exc_info()[1]
print("ERROR: Failed to load %s: [%s] %s" % (filename, type(err).__n... | KeyError | dataset/ETHPy150Open wyplay/pytracemalloc/tracemalloc.py/Snapshot.load |
2,366 | def __init__(self, file=None):
try:
# Python 3
import reprlib
except __HOLE__:
# Python 2
import repr as reprlib
if file is not None:
self.stream = file
else:
self.stream = sys.stdout
self.cumulative = False... | ImportError | dataset/ETHPy150Open wyplay/pytracemalloc/tracemalloc.py/DisplayGarbage.__init__ |
2,367 | def get_integration(integration, *args, **kwargs):
"""Return a integration instance specified by `integration` name"""
klass = integration_cache.get(integration, None)
if not klass:
integration_filename = "%s_integration" % integration
integration_module = None
for app in settings.... | ImportError | dataset/ETHPy150Open agiliq/merchant/billing/integration.py/get_integration |
2,368 | def repl_linker_command(m):
# Replaces any linker command file directives (e.g. "@foo.lnk") with
# the actual contents of the file.
try:
f=open(m.group(2), "r")
return m.group(1) + f.read()
except __HOLE__:
# the linker should return an error if it can't
# find the linker... | IOError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/linkloc.py/repl_linker_command |
2,369 | def name_from_value(self, value, default=core.UNSET, patterns=["*"]):
"""Find the longest name in the set of constants (optionally qualified by pattern)
which matches value.
"""
try:
return max(
(name for name in self.names(patterns) if self[name] == val... | ValueError | dataset/ETHPy150Open tjguk/winsys/winsys/registry.py/RegistryConstants.name_from_value |
2,370 | def _parse_moniker(moniker, accept_value=True):
r"""Take a registry moniker and return the computer, root key, subkey path and value label.
NB: neither the computer nor the registry key need exist; they
need simply to be of the right format. The slashes must be backslashes (since
registry key names ... | KeyError | dataset/ETHPy150Open tjguk/winsys/winsys/registry.py/_parse_moniker |
2,371 | @classmethod
def _access(cls, access):
"""Conversion function which returns an integer representing a security access
bit pattern. Uses the class's ACCESS map to translate letters to integers.
"""
if access is None:
return None
try:
return int(... | ValueError | dataset/ETHPy150Open tjguk/winsys/winsys/registry.py/Registry._access |
2,372 | def set_value(self, label, value, type=None):
"""Attempt to set one of the key's named values. If type is
None, then if the value already exists under the key its
current type is assumed; otherwise a guess is made at
the datatype as follows:
* If the value is an int, use D... | TypeError | dataset/ETHPy150Open tjguk/winsys/winsys/registry.py/Registry.set_value |
2,373 | def _readmodule(module, path, inpackage=None):
'''Do the hard work for readmodule[_ex].
If INPACKAGE is given, it must be the dotted name of the package in
which we are searching for a submodule, and then PATH must be the
package search path; otherwise, we are searching for a top-level
module, and ... | StopIteration | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pyclbr.py/_readmodule |
2,374 | def create(self, image):
if self.exists(image) and not self.regenerate_images:
return
try:
ImageModel(image)
except __HOLE__:
log.warning("Unable to store models on this machine")
image.root = self.root
image.generate()
with suppress... | ImportError | dataset/ETHPy150Open jacebrowning/memegen/memegen/stores/image.py/ImageStore.create |
2,375 | def transform(self, X, y=None):
"""Transform feature->value dicts to array or sparse matrix.
Named features not encountered during fit or fit_transform will be
silently ignored.
Parameters
----------
X : Mapping or iterable over Mappings, length = n_samples
... | KeyError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/feature_extraction/dict_vectorizer.py/DictVectorizer.transform |
2,376 | def handle(self, *url_lists, **options):
from django.conf import settings
from debug_logging.models import TestRun
from debug_logging.utils import (get_project_name, get_hostname,
get_revision)
verbosity = int(options.get('verbosity', 1))
... | NameError | dataset/ETHPy150Open lincolnloop/django-debug-logging/debug_logging/management/commands/log_urls.py/Command.handle |
2,377 | def check_argument_type(name, value):
text = NamedTemporaryFile()
try:
with patch('sys.stderr') as mock_stderr:
args = cli.parse_args(['--text', text.name, '--' + name, str(value)])
raise AssertionError('argument "{}" was accepted even though the type did not match'.format(name))
... | ValueError | dataset/ETHPy150Open amueller/word_cloud/test/test_wordcloud_cli.py/check_argument_type |
2,378 | def test_check_duplicate_color_error():
color_mask_file = NamedTemporaryFile()
text_file = NamedTemporaryFile()
try:
cli.parse_args(['--color', 'red', '--colormask', color_mask_file.name, '--text', text_file.name])
raise AssertionError('parse_args(...) didn\'t raise')
except __HOLE__ as... | ValueError | dataset/ETHPy150Open amueller/word_cloud/test/test_wordcloud_cli.py/test_check_duplicate_color_error |
2,379 | def flatten_json(
form,
json,
parent_key='',
separator='-',
skip_unknown_keys=True
):
"""Flattens given JSON dict to cope with WTForms dict structure.
:form form: WTForms Form object
:param json: json to be converted into flat WTForms style dict
:param parent_key: this argument is u... | AttributeError | dataset/ETHPy150Open kvesteri/wtforms-json/wtforms_json/__init__.py/flatten_json |
2,380 | def run(self, args):
try:
return self.dispatch(args)
except getopt.GetoptError as e:
print("Error: %s\n" % str(e))
self.display_help()
return 2
except CallError as e:
sys.stderr.write("%s\n" % str(e))
return 1
except... | KeyboardInterrupt | dataset/ETHPy150Open circus-tent/circus/circus/circusctl.py/ControllerApp.run |
2,381 | def autocomplete(self, autocomplete=False, words=None, cword=None):
"""
Output completion suggestions for BASH.
The output of this function is passed to BASH's `COMREPLY` variable and
treated as completion suggestions. `COMREPLY` expects a space
separated string as the result.
... | IndexError | dataset/ETHPy150Open circus-tent/circus/circus/circusctl.py/CircusCtl.autocomplete |
2,382 | def start(self, globalopts):
self.autocomplete()
self.controller.globalopts = globalopts
args = globalopts['args']
parser = globalopts['parser']
if hasattr(args, 'command'):
sys.exit(self.controller.run(globalopts['args']))
if args.help:
for co... | KeyboardInterrupt | dataset/ETHPy150Open circus-tent/circus/circus/circusctl.py/CircusCtl.start |
2,383 | def _handle_exception():
"""Print exceptions raised by subscribers to stderr."""
# Heavily influenced by logging.Handler.handleError.
# See note here:
# https://docs.python.org/3.4/library/sys.html#sys.__stderr__
if sys.stderr:
einfo = sys.exc_info()
try:
traceback.print... | IOError | dataset/ETHPy150Open mongodb/mongo-python-driver/pymongo/monitoring.py/_handle_exception |
2,384 | def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(
version="%prog version: $Id$",
usage=globals()["__doc__"])
parser.add_option("-c", "--columns", dest="co... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/data2stats.py/main |
2,385 | def get_boolean(self, section, name, default=None):
"""Retrieve a configuration setting as boolean.
:param section: Tuple with section name and optional subsection namee
:param name: Name of the setting, including section and possible
subsection.
:return: Contents of the set... | KeyError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/Config.get_boolean |
2,386 | def get(self, section, name):
if isinstance(section, basestring):
section = (section, )
if len(section) > 1:
try:
return self._values[section][name]
except __HOLE__:
pass
return self._values[(section[0],)][name] | KeyError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/ConfigDict.get |
2,387 | @classmethod
def from_file(cls, f):
"""Read configuration from a file-like object."""
ret = cls()
section = None
setting = None
for lineno, line in enumerate(f.readlines()):
line = line.lstrip()
if setting is None:
if _strip_comments(li... | ValueError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/ConfigFile.from_file |
2,388 | def write_to_file(self, f):
"""Write configuration to a file-like object."""
for section, values in self._values.iteritems():
try:
section_name, subsection_name = section
except __HOLE__:
(section_name, ) = section
subsection_name =... | ValueError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/ConfigFile.write_to_file |
2,389 | @classmethod
def default_backends(cls):
"""Retrieve the default configuration.
This will look in the repository configuration (if for_path is
specified), the users' home directory and the system
configuration.
"""
paths = []
paths.append(os.path.expanduser("~... | IOError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/StackedConfig.default_backends |
2,390 | def get(self, section, name):
for backend in self.backends:
try:
return backend.get(section, name)
except __HOLE__:
pass
raise KeyError(name) | KeyError | dataset/ETHPy150Open codeinn/vcs/vcs/backends/git/config.py/StackedConfig.get |
2,391 | def smtpcli(argv):
"""smtpcli [-h] [-l <logfilename>] [-s <portname>] [host] [port]
Provides an interactive session at a protocol level to an SMTP server.
"""
bindto = None
port = 25
sourcefile = None
paged = False
logname = None
try:
optlist, longopts, args = getopt.getopt(arg... | ValueError | dataset/ETHPy150Open kdart/pycopia/net/pycopia/smtpCLI.py/smtpcli |
2,392 | def from_archive(archive_path):
archive = zipfile.ZipFile(archive_path)
try:
xml_data = archive.read("package.xml")
except __HOLE__:
raise qisys.error.Error("Could not find package.xml in %s" %
archive_path)
element = etree.fromstring(xml_data)
return ... | KeyError | dataset/ETHPy150Open aldebaran/qibuild/python/qitoolchain/qipackage.py/from_archive |
2,393 | def test_local_fail(self):
try:
import ckan
except __HOLE__:
raise unittest.SkipTest('ckan not importable')
self.assertRaises(
ckanapi.CKANAPIError,
ckanapi.LocalCKAN('fake').call_action,
'fake', {}, {}, 'apikey not allowed') | ImportError | dataset/ETHPy150Open ckan/ckanapi/ckanapi/tests/test_call.py/TestCallAction.test_local_fail |
2,394 | def _non_atomic_requests(view, using):
try:
view._non_atomic_requests.add(using)
except __HOLE__:
view._non_atomic_requests = set([using])
return view | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/db/transaction.py/_non_atomic_requests |
2,395 | def _osUrandom(self, nbytes):
"""
Wrapper around C{os.urandom} that cleanly manage its absence.
"""
try:
return os.urandom(nbytes)
except (AttributeError, __HOLE__), e:
raise SourceNotAvailable(e) | NotImplementedError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/randbytes.py/RandomFactory._osUrandom |
2,396 | def _fileUrandom(self, nbytes):
"""
Wrapper around random file sources.
This method isn't meant to be call out of the class and could be
removed arbitrarily.
"""
for src in self.randomSources:
try:
f = file(src, 'rb')
except (__HOL... | IOError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/randbytes.py/RandomFactory._fileUrandom |
2,397 | def handle_interactive_request(self, environ):
code = environ['wsgi.input'].read().replace('\r\n', '\n')
user_environ = self.get_user_environ(environ)
if 'HTTP_CONTENT_LENGTH' in user_environ:
del user_environ['HTTP_CONTENT_LENGTH']
user_environ['REQUEST_METHOD'] = 'GET'
url = 'http://%s:%s%s... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/python/request_handler.py/RequestHandler.handle_interactive_request |
2,398 | def execute(task, *args, **kwargs):
"""
Execute ``task`` (callable or name), honoring host/role decorators, etc.
``task`` may be an actual callable object, or it may be a registered task
name, which is used to look up a callable just as if the name had been
given on the command line (including :ref... | ImportError | dataset/ETHPy150Open fabric/fabric/fabric/tasks.py/execute |
2,399 | def run_ner(self, doc):
entities = []
# Apply the ner algorithm which takes a list of sentences and returns
# a list of sentences, each being a list of NER-tokens, each of which is
# a pairs (tokenstring, class)
ner_sentences = self.ner(doc.get_sentences())
# Flatten the ... | StopIteration | dataset/ETHPy150Open machinalis/iepy/iepy/preprocess/ner/stanford.py/NERRunner.run_ner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.