Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,300 | def get_sha(a_file):
"""
Returns sha1 hash of the file supplied as an argument
"""
try:
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with io.open(a_file, "rb") as fh:
buf = fh.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
... | IOError | dataset/ETHPy150Open tonyfischetti/sake/functests/test3/functest.py/get_sha |
5,301 | def GetValue(self, ignore_error=True):
"""Extracts and returns a single value from a DataBlob."""
if self.HasField("none"):
return None
field_names = ["integer", "string", "data", "boolean", "list", "dict",
"rdf_value", "float"]
values = [getattr(self, x) for x in field_names ... | ValueError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/protodict.py/DataBlob.GetValue |
5,302 | def GetItem(self, key, default=None):
try:
return self[key]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/protodict.py/Dict.GetItem |
5,303 | def __init__(self, initializer=None, age=None):
super(RDFValueArray, self).__init__(age=age)
if self.__class__ == initializer.__class__:
self.content = initializer.Copy().content
self.age = initializer.age
# Initialize from a serialized protobuf.
elif isinstance(initializer, str):
se... | TypeError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/protodict.py/RDFValueArray.__init__ |
5,304 | def Append(self, value=None, **kwarg):
"""Add another member to the array.
Args:
value: The new data to append to the array.
**kwarg: Create a new element from these keywords.
Returns:
The value which was added. This can be modified further by the caller and
changes will be propag... | TypeError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/protodict.py/RDFValueArray.Append |
5,305 | @property
def payload(self):
"""Extracts and returns the serialized object."""
try:
rdf_cls = self.classes.get(self.name)
value = rdf_cls(self.data)
value.age = self.embedded_age
return value
except __HOLE__:
return None | TypeError | dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/protodict.py/EmbeddedRDFValue.payload |
5,306 | def __init__(self, v):
if isinstance(v, solr_date):
self._dt_obj = v._dt_obj
elif isinstance(v, basestring):
try:
self._dt_obj = datetime_from_w3_datestring(v)
except __HOLE__, e:
raise SolrError(*e.args)
elif hasattr(v, "strfti... | ValueError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/solr_date.__init__ |
5,307 | def __cmp__(self, other):
try:
other = other._dt_obj
except __HOLE__:
pass
if self._dt_obj < other:
return -1
elif self._dt_obj > other:
return 1
else:
return 0 | AttributeError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/solr_date.__cmp__ |
5,308 | def solr_point_factory(dimension):
if dimension < 1:
raise ValueError("dimension of PointType must be greater than one")
class solr_point(object):
dim = int(dimension)
def __init__(self, *args):
if dimension > 1 and len(args) == 1:
v = args[0]
... | TypeError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/solr_point_factory |
5,309 | def from_user_data(self, value):
try:
return str(value)
except (__HOLE__, ValueError):
raise SolrError("Could not convert data to binary string (field %s)" %
self.name) | TypeError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrBinaryField.from_user_data |
5,310 | def normalize(self, value):
try:
v = self.base_type(value)
except (OverflowError, __HOLE__, ValueError):
raise SolrError("%s is invalid value for %s (field %s)" %
(value, self.__class__, self.name))
if v < self.min or v > self.max:
raise So... | TypeError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrNumericalField.normalize |
5,311 | def field_type_factory(self, field_type_node):
try:
name, class_name = field_type_node.attrib['name'], field_type_node.attrib['class']
except __HOLE__, e:
raise SolrError("Invalid schema.xml: missing %s attribute on fieldType" % e.args[0])
#Obtain field type for given cla... | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrSchema.field_type_factory |
5,312 | def field_factory(self, field_node, field_type_classes, dynamic):
try:
name, field_type = field_node.attrib['name'], field_node.attrib['type']
except KeyError, e:
raise SolrError("Invalid schema.xml: missing %s attribute on field" % e.args[0])
try:
field_type_... | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrSchema.field_factory |
5,313 | def match_dynamic_field(self, name):
try:
return self.dynamic_field_cache[name]
except __HOLE__:
for field in self.dynamic_fields:
if field.match(name):
self.dynamic_field_cache[name] = field
return field | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrSchema.match_dynamic_field |
5,314 | def match_field(self, name):
try:
return self.fields[name]
except __HOLE__:
field = self.match_dynamic_field(name)
return field | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrSchema.match_field |
5,315 | def doc_id_from_doc(self, doc):
# Is this a dictionary, or an document object, or a thing
# that can be cast to a uniqueKey? (which could also be an
# arbitrary object.
if isinstance(doc, (basestring, int, long, float)):
# It's obviously not a document object, just coerce to ... | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrDelete.doc_id_from_doc |
5,316 | @classmethod
def from_response_json(cls, response):
try:
facet_counts_dict = response['facet_counts']
except __HOLE__:
return SolrFacetCounts()
facet_fields = {}
for facet_field, facet_values in facet_counts_dict['facet_fields'].viewitems():
facets... | KeyError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/SolrFacetCounts.from_response_json |
5,317 | def get_attribute_or_callable(o, name):
try:
a = getattr(o, name)
# Might be attribute or callable
if callable(a):
try:
a = a()
except TypeError:
a = None
except __HOLE__:
a = None
return a | AttributeError | dataset/ETHPy150Open tow/sunburnt/sunburnt/schema.py/get_attribute_or_callable |
5,318 | def event_attach(self, eventtype, callback, *args, **kwds):
"""Register an event notification.
@param eventtype: the desired event type to be notified about.
@param callback: the function to call when the event occurs.
@param args: optional positional arguments for the callback.
... | KeyError | dataset/ETHPy150Open disqus/playa/playa/lib/vlc.py/EventManager.event_attach |
5,319 | def hex_version():
"""Return the version of these bindings in hex or 0 if unavailable.
"""
try:
return _dot2int(__version__.split('-')[-1])
except (NameError, __HOLE__):
return 0 | ValueError | dataset/ETHPy150Open disqus/playa/playa/lib/vlc.py/hex_version |
5,320 | def libvlc_hex_version():
"""Return the libvlc version in hex or 0 if unavailable.
"""
try:
return _dot2int(libvlc_get_version().split()[0])
except __HOLE__:
return 0 | ValueError | dataset/ETHPy150Open disqus/playa/playa/lib/vlc.py/libvlc_hex_version |
5,321 | def test_bad_commands(self):
sources_cache = get_cache_dir()
cmd_extras = ['-c', sources_cache]
for commands in [[], ['fake', 'something'], ['check'], ['install', '-a', 'rospack_fake'],
['check', 'rospack_fake', '--os', 'ubuntulucid'],
]:
... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_bad_commands |
5,322 | def test_check(self):
sources_cache = get_cache_dir()
cmd_extras = ['-c', sources_cache]
with fakeout() as b:
try:
rosdep_main(['check', 'python_dep']+cmd_extras)
except SystemExit:
assert False, "system exit occurred: %s\n%s"%(b[0].getval... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_check |
5,323 | def test_install(self):
sources_cache = get_cache_dir()
cmd_extras = ['-c', sources_cache]
try:
# python must have already been installed
with fakeout() as b:
rosdep_main(['install', 'python_dep']+cmd_extras)
stdout, stderr = b
... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_install |
5,324 | def test_where_defined(self):
try:
sources_cache = get_cache_dir()
expected = GITHUB_PYTHON_URL
for command in (['where_defined', 'testpython'], ['where_defined', 'testpython']):
with fakeout() as b:
# set os to ubuntu so this test works o... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_where_defined |
5,325 | def test_what_needs(self):
try:
sources_cache = get_cache_dir()
cmd_extras = ['-c', sources_cache]
expected = ['python_dep']
with fakeout() as b:
rosdep_main(['what-needs', 'testpython']+cmd_extras)
stdout, stderr = b
... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_what_needs |
5,326 | def test_keys(self):
sources_cache = get_cache_dir()
cmd_extras = ['-c', sources_cache]
try:
with fakeout() as b:
rosdep_main(['keys', 'rospack_fake']+cmd_extras)
stdout, stderr = b
assert stdout.getvalue().strip() == "testtinyxml", st... | SystemExit | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_main.py/TestRosdepMain.test_keys |
5,327 | def _handle(self, expression, command, x=0, y=0):
"""
:param expression: the expression to handle
:param command: the function to apply, either _draw_command or _visit_command
:param x: the top of the current drawing area
:param y: the left side of the current drawing area
... | AttributeError | dataset/ETHPy150Open nltk/nltk/nltk/sem/drt.py/DrsDrawer._handle |
5,328 | def test_draw():
try:
from tkinter import Tk
except __HOLE__:
from nose import SkipTest
raise SkipTest("tkinter is required, but it's not available.")
expressions = [
r'x',
r'([],[])',
r'([x],[])',
r'([x],[man(x)])',
r'([x... | ImportError | dataset/ETHPy150Open nltk/nltk/nltk/sem/drt.py/test_draw |
5,329 | def is_expected(item):
with open(item) as f:
expect(f).to_be_a_file()
expect(item).to_be_a_file()
try:
expect(item).not_to_be_a_file()
except __HOLE__:
return
assert False, 'Should not have gotten this far' | AssertionError | dataset/ETHPy150Open heynemann/preggy/tests/types/test_file.py/is_expected |
5,330 | def is_not_expected(item):
expect(item).Not.to_be_a_file()
expect(item).not_to_be_a_file()
try:
expect(item).to_be_a_file()
except __HOLE__:
return
assert False, 'Should not have gotten this far'
#----------------------------------------------------------------------------- | AssertionError | dataset/ETHPy150Open heynemann/preggy/tests/types/test_file.py/is_not_expected |
5,331 | def test_is_not_file_obj():
with open('./README.md') as f:
try:
expect(f).not_to_be_a_file()
except __HOLE__:
return
assert False, 'Should not have gotten this far' | AssertionError | dataset/ETHPy150Open heynemann/preggy/tests/types/test_file.py/test_is_not_file_obj |
5,332 | def test_other_entities_are_not_deleted(self):
gazette = GazetteItemFactory()
entity1 = EntityFactory()
entity2 = EntityFactory()
gazette.save()
entity1.gazette = gazette
entity1.save()
entity2.save()
entity1_id = entity1.id
entity2_id = entity2.... | ObjectDoesNotExist | dataset/ETHPy150Open machinalis/iepy/tests/test_entity.py/TestEntityGazetteRelation.test_other_entities_are_not_deleted |
5,333 | def lookup_object(model, object_id, slug, slug_field):
"""
Return the ``model`` object with the passed ``object_id``. If
``object_id`` is None, then return the object whose ``slug_field``
equals the passed ``slug``. If ``slug`` and ``slug_field`` are not passed,
then raise Http404 exception.
"... | ObjectDoesNotExist | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/views/generic/create_update.py/lookup_object |
5,334 | def verify_cache(index, res_folder):
num_files = len(index)
missing = 0
corrupt = 0
scanned = 0
for entry in index:
scanned += 1
progress.write("Scanned %6.1d of %6.1d files (%6.1d corrupt, %6.1d missing)\r" %
(scanned, num_files, corrupt, missing))
fi... | IOError | dataset/ETHPy150Open ccpgames/rescache/verify.py/verify_cache |
5,335 | def string_references(self, minimum_length=2):
"""
All of the constant string references used by this function.
:param minimum_length: The minimum length of strings to find (default is 1)
:return: A list of tuples of (address, string) where is address is the loca... | KeyError | dataset/ETHPy150Open angr/angr/angr/knowledge/function.py/Function.string_references |
5,336 | def _get_cudafft():
"""Helper to deal with scikit-cuda namespace change"""
try:
from skcuda import fft
except __HOLE__:
try:
from scikits.cuda import fft
except ImportError:
fft = None
return fft | ImportError | dataset/ETHPy150Open mne-tools/mne-python/mne/cuda.py/_get_cudafft |
5,337 | def init_cuda(ignore_config=False):
"""Initialize CUDA functionality
This function attempts to load the necessary interfaces
(hardware connectivity) to run CUDA-based filtering. This
function should only need to be run once per session.
If the config var (set via mne.set_config or in ENV)
MNE_... | ImportError | dataset/ETHPy150Open mne-tools/mne-python/mne/cuda.py/init_cuda |
5,338 | def __init__(self,
address=None,
payload=None,
sources=None,
resources=None, # Old-style resources (file list, Fileset).
resource_targets=None, # New-style resources (Resources target specs).
provides=None,
compat... | ValueError | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/backend/python/targets/python_target.py/PythonTarget.__init__ |
5,339 | def draw(cursor, out=sys.stdout, paginate=True, max_fieldsize=100):
"""Render an result set as an ascii-table.
Renders an SQL result set to `out`, some file-like object.
Assumes that we can determine the current terminal height and
width via the termsize module.
Args:
cursor: An iterable o... | UnicodeDecodeError | dataset/ETHPy150Open jaysw/ipydb/ipydb/asciitable.py/draw |
5,340 | def _ReadNumericFile(file_name):
"""Reads a file containing a number.
@rtype: None or int
@return: None if file is not found, otherwise number
"""
try:
contents = utils.ReadFile(file_name)
except EnvironmentError, err:
if err.errno in (errno.ENOENT, ):
return None
raise
try:
retur... | ValueError | dataset/ETHPy150Open ganeti/ganeti/lib/jstore.py/_ReadNumericFile |
5,341 | def ParseJobId(job_id):
"""Parses a job ID and converts it to integer.
"""
try:
return int(job_id)
except (ValueError, __HOLE__):
raise errors.ParameterError("Invalid job ID '%s'" % job_id) | TypeError | dataset/ETHPy150Open ganeti/ganeti/lib/jstore.py/ParseJobId |
5,342 | def iter_cont_objs_to_expire(self):
"""
Yields (container, obj) tuples to be deleted
"""
obj_cache = {}
cnt = 0
all_containers = set()
for c in self.swift.iter_containers(self.expiring_objects_account):
container = str(c['name'])
timestam... | ValueError | dataset/ETHPy150Open openstack/swift/swift/obj/expirer.py/ObjectExpirer.iter_cont_objs_to_expire |
5,343 | @authorization_required(is_admin=True)
@threaded
def post(self):
try:
login = self.json["login"]
email = self.json["email"]
is_admin = bool(self.json.get("is_admin", 0))
password = self.json["password"]
assert password and len(password) > 3
... | KeyError | dataset/ETHPy150Open mosquito/pypi-server/pypi_server/handlers/api/users.py/UsersHandler.post |
5,344 | def process(self):
self.logger.info('asynscheduler : [started]')
while True:
try:
for entity in ENTITYS:
fp = open(self.cf["%s.mkfifo.path" % entity], 'w')
try:
fp.write(str(self.cf['%s.mkfifo.start.code' % entit... | IOError | dataset/ETHPy150Open karesansui/pysilhouette/pysilhouette/asynscheduler.py/AsynScheduler.process |
5,345 | def main():
(opts, args) = getopts()
if chkopts(opts) is True:
return PROCERROR
cf = readconf(opts.config)
if cf is None:
print >>sys.stderr, 'Failed to load the config file "%s". (%s)' % (opts.config, sys.argv[0])
return PROCERROR
# conf parse
if parse_conf(cf) is ... | KeyboardInterrupt | dataset/ETHPy150Open karesansui/pysilhouette/pysilhouette/asynscheduler.py/main |
5,346 | @cli.command()
@click.argument('environment', required=True)
@click.argument('zappa_settings', required=True, type=click.File('rb'))
def tail(environment, zappa_settings):
""" Stolen verbatim from django-zappa:
https://github.com/Miserlou/django-zappa/blob/master/django_zappa/management/commands/tail.py
... | KeyboardInterrupt | dataset/ETHPy150Open Miserlou/flask-zappa/bin/client.py/tail |
5,347 | def has_permission(self, request, view):
"""
Check if the subscriber has an active subscription.
Returns false if:
* a subscriber isn't passed through the request
See ``utils.subscriber_has_active_subscription`` for more rules.
"""
try:
subscri... | AttributeError | dataset/ETHPy150Open pydanny/dj-stripe/djstripe/contrib/rest_framework/permissions.py/DJStripeSubscriptionPermission.has_permission |
5,348 | def sici(x_gpu):
"""
Sine/Cosine integral.
Computes the sine and cosine integral of every element in the
input matrix.
Parameters
----------
x_gpu : GPUArray
Input matrix of shape `(m, n)`.
Returns
-------
(si_gpu, ci_gpu) : tuple of GPUArrays
Tuple of ... | KeyError | dataset/ETHPy150Open lebedov/scikit-cuda/skcuda/special.py/sici |
5,349 | def exp1(z_gpu):
"""
Exponential integral with `n = 1` of complex arguments.
Parameters
----------
z_gpu : GPUArray
Input matrix of shape `(m, n)`.
Returns
-------
e_gpu : GPUArray
GPUarrays containing the exponential integrals of
the entries of `z_gpu`.... | KeyError | dataset/ETHPy150Open lebedov/scikit-cuda/skcuda/special.py/exp1 |
5,350 | def expi(z_gpu):
"""
Exponential integral of complex arguments.
Parameters
----------
z_gpu : GPUArray
Input matrix of shape `(m, n)`.
Returns
-------
e_gpu : GPUArray
GPUarrays containing the exponential integrals of
the entries of `z_gpu`.
Example... | KeyError | dataset/ETHPy150Open lebedov/scikit-cuda/skcuda/special.py/expi |
5,351 | def arg_parser():
"""
Parses the arguments and calls the help() function if any problem is found
"""
global PRINT_PIXIE
global PRINT_REAVER
global USE_PIXIEWPS
global AIRODUMP_TIME
global REAVER_TIME
global CHANNEL
global PROMPT_APS
global OUTPUT_FILE
global OUTPUT
global GET_PASSWORD
glob... | ValueError | dataset/ETHPy150Open jgilhutton/pyxiewps_WPShack-Python/pyxiewps-EN.py/arg_parser |
5,352 | def parse_airodump(self, input):
"""
Parses the airodump output
If you find some error in the program flow, check this function first.
returns ESSIDs, WPSstatus, channel, bssid and RSSI
"""
plist = []
input.reverse() # Important
inds = [47,73,86] # CHANNEL, WPS, ESSID indexes
if CHA... | ValueError | dataset/ETHPy150Open jgilhutton/pyxiewps_WPShack-Python/pyxiewps-EN.py/Engine.parse_airodump |
5,353 | def run(self, cmd, shell = False, kill_tree = True, timeout = -1, airodump = False):
"""
Runs a command witha given time after wich is terminated
returns stdout of proc.
output is a list without passing strip() on the lines.
"""
class Alarm(Exception):
pass
def alarm_handler(signum, f... | OSError | dataset/ETHPy150Open jgilhutton/pyxiewps_WPShack-Python/pyxiewps-EN.py/Engine.run |
5,354 | def get_iface(self):
"""
If any monitor interfaces are found, returns the wlans.
If more than onw are found, ask the user to choose.
If monitor mode is already enable, returns the name.
"""
if self.IS_MON: # If the interface is already in monitor mode, it returns its name
proc = subproces... | ValueError | dataset/ETHPy150Open jgilhutton/pyxiewps_WPShack-Python/pyxiewps-EN.py/Config.get_iface |
5,355 | def get_wps_aps(self):
"""
Enumerates any WPS-active APs
Goes to get_reaver_info
"""
print INFO + "Enumerating WPS-active APs..."
cmd = 'airodump-ng -c 1-11 --wps %s' %(c.IFACE_MON)
if CHANNEL != '':
cmd = 'airodump-ng -c %d --wps %s' %(CHANNEL, c.IFACE_MON)
output = engine.run(cm... | KeyboardInterrupt | dataset/ETHPy150Open jgilhutton/pyxiewps_WPShack-Python/pyxiewps-EN.py/Attack.get_wps_aps |
5,356 | def get(using=None):
"""Return a browser launcher instance appropriate for the environment."""
if using is not None:
alternatives = [using]
else:
alternatives = _tryorder
for browser in alternatives:
if '%s' in browser:
# User gave us a command line, split it ... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/get |
5,357 | def _synthesize(browser, update_tryorder=1):
"""Attempt to synthesize a controller base on existing controllers.
This is useful to create a controller when a user specifies a path to
an entry in the BROWSER environment variable -- we can copy a general
controller to operate using a specific instal... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/_synthesize |
5,358 | def open(self, url, new=0, autoraise=1):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
p = subprocess.Popen(cmdli... | OSError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/GenericBrowser.open |
5,359 | def open(self, url, new=0, autoraise=1):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
setsid = getattr(os, 'sets... | OSError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/BackgroundBrowser.open |
5,360 | def open(self, url, new=0, autoraise=1):
# XXX Currently I know no way to prevent KFM from opening a new win.
if new == 2:
action = "newTab"
else:
action = "openURL"
devnull = file(os.devnull, "r+")
# if possible, put browser in separate process g... | OSError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/Konqueror.open |
5,361 | def _find_grail_rc(self):
import glob
import pwd
import socket
import tempfile
tempdir = os.path.join(tempfile.gettempdir(),
".grail-unix")
user = pwd.getpwuid(os.getuid())[0]
filename = os.path.join(tempdir, user + "-*")
... | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/webbrowser.py/Grail._find_grail_rc |
5,362 | def Scalar(self, event, loader):
"""Handle scalar value
Since scalars are simple values that are passed directly in by the
parser, handle like any value with no additional processing.
Of course, key values will be handles specially. A key value is recognized
when the top token is _TOKEN_MAPPING.
... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/yaml_builder.py/BuilderHandler.Scalar |
5,363 | @classmethod
def get_transform(cls, spec):
try:
return cls.spec_map[spec['type']].wrap(spec)
except __HOLE__:
raise BadSpecError(_('Invalid or missing transform type: {}. Valid options are: {}').format(
spec.get('type', None),
', '.join(cls.spe... | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/userreports/transforms/factory.py/TransformFactory.get_transform |
5,364 | @property
def token(self):
"""
set the instance attribute `token` following the following logic,
stopping whenever a token is found. Raises NoTokenFound is no token
is found
- environment variables TOKEN_ENVIRON_VARS
- file containing plaintext as the contents in TOKE... | IOError | dataset/ETHPy150Open andycasey/ads/ads/base.py/BaseQuery.token |
5,365 | def get_tests(suite):
"""Generates a sequence of tests from a test suite
"""
for item in suite:
try:
# TODO: This could be "yield from..." with Python 3.3+
for i in get_tests(item):
yield i
except __HOLE__:
yield item | TypeError | dataset/ETHPy150Open jborg/attic/attic/testsuite/__init__.py/get_tests |
5,366 | def find_module(self, fullname, path=None):
tail = fullname.rsplit('.', 1)[-1]
try:
fd, fn, info = imp.find_module(tail, path)
if fullname in self._cache:
old_fd = self._cache[fullname][0]
if old_fd:
old_fd.close()
s... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/utils/module_loading.py/ProxyFinder.find_module |
5,367 | def parse_arguments():
# Construct the option parser.
usage = '%prog [ACTION] [options] NAMES...'
version = "Epydoc, version %s" % epydoc.__version__
optparser = OptionParser(usage=usage, add_help_option=False)
optparser.add_option('--config',
action='append', dest="configfiles", metavar='F... | SystemExit | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/parse_arguments |
5,368 | def _str_to_int(val, optname):
try:
return int(val)
except __HOLE__:
raise ValueError('"%s" option expected an int' % optname) | ValueError | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/_str_to_int |
5,369 | def main(options, names):
# Set the debug flag, if '--debug' was specified.
if options.debug:
epydoc.DEBUG = True
## [XX] Did this serve a purpose? Commenting out for now:
#if options.action == 'text':
# if options.parse and options.introspect:
# options.parse = False
# ... | ImportError | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/main |
5,370 | def write_latex(docindex, options, format):
from epydoc.docwriter.latex import LatexWriter
latex_writer = LatexWriter(docindex, **options.__dict__)
log.start_progress('Writing LaTeX docs')
latex_writer.write(options.target)
log.end_progress()
# If we're just generating the latex, and not any out... | OSError | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/write_latex |
5,371 | def cli():
# Parse command-line arguments.
options, names = parse_arguments()
try:
try:
if options.profile:
_profile()
else:
main(options, names)
finally:
log.close()
except __HOLE__:
raise
except KeyboardIn... | SystemExit | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/cli |
5,372 | def _profile():
# Hotshot profiler.
if PROFILER == 'hotshot':
try: import hotshot, hotshot.stats
except ImportError:
print >>sys.stderr, "Could not import profile module!"
return
try:
prof = hotshot.Profile('hotshot.out')
prof = prof.runctx... | ImportError | dataset/ETHPy150Open QuantSoftware/QuantSoftwareToolkit/Legacy/epydoc-3.0.1/epydoc/cli.py/_profile |
5,373 | def addIntergenicSegment(last, this, fasta, options):
"""add an intergenic segment between last and this.
At telomeres, either can be None.
"""
if not this and not last:
return 0
nadded = 0
if not this:
# last telomere
try:
lcontig = fasta.getLength(last.con... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/scripts/gtf2gff.py/addIntergenicSegment |
5,374 | def annotateGenes(iterator, fasta, options):
"""annotate gene structures
This method outputs intervals for first/middle/last exon/intron,
UTRs and flanking regions.
This method annotates per transcript. In order to achieve a unique tiling,
use only a single transcript per gene and remove any overl... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/scripts/gtf2gff.py/annotateGenes |
5,375 | def _get_profiles(self):
log.info("Getting firefox profiles")
if self.os == 'linux':
profiles_folder = self._expand("~/.mozilla/firefox/")
elif self.os == 'windows':
if platform.release() == "XP":
log.error("Unsupported OS (Windows XP). Returning None")
... | AttributeError | dataset/ETHPy150Open Nikola-K/RESTool/RESTool/browsers/firefox.py/Firefox._get_profiles |
5,376 | def _get_res(self, profile_name):
log.debug("Getting firefox path for profile name: {}".format(profile_name))
ff_profile = self.available_profiles.get(profile_name)
res_file = "jetpack/jid1-xUfzOsOFlzSOXg@jetpack/simple-storage/store.json"
if not ff_profile:
log.error("Coul... | AttributeError | dataset/ETHPy150Open Nikola-K/RESTool/RESTool/browsers/firefox.py/Firefox._get_res |
5,377 | def ec2_id_to_id(ec2_id):
"""Convert an ec2 ID (i-[base 16 number]) to an instance id (int)"""
try:
return int(ec2_id.split('-')[-1], 16)
except __HOLE__:
raise exception.InvalidEc2Id(ec2_id=ec2_id) | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/ec2/ec2utils.py/ec2_id_to_id |
5,378 | def _try_convert(value):
"""Return a non-string from a string or unicode, if possible.
============= =====================================================
When value is returns
============= =====================================================
zero-length ''
'None' None
'True' ... | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/ec2/ec2utils.py/_try_convert |
5,379 | def _key_press_event(self, widget, event):
keyname = gtk.gdk.keyval_name(event.keyval)
if keyname == 'Up':
try:
text = self.history.prev()
self.set_text(text)
self.widget.set_position(len(text))
except __HOLE__:
pass... | ValueError | dataset/ETHPy150Open ejeschke/ginga/ginga/gtkw/Widgets.py/TextEntry._key_press_event |
5,380 | def _add_subtree(self, level, shadow, model, parent_item, key, node):
if level >= self.levels:
# leaf node
try:
bnch = shadow[key]
item_iter = bnch.item
# TODO: update leaf item
except KeyError:
# new item
... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/gtkw/Widgets.py/TreeView._add_subtree |
5,381 | def list_or_args(command, keys, args):
oldapi = bool(args)
try:
iter(keys)
if isinstance(keys, (str, unicode)):
raise TypeError
except __HOLE__:
oldapi = True
keys = [keys]
if oldapi:
warnings.warn(DeprecationWarning(
"Passing *args to red... | TypeError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/txredisapi.py/list_or_args |
5,382 | def dataReceived(self, data, unpause=False):
if unpause is True:
if self.__buffer:
self.__buffer = data + self.__buffer
else:
self.__buffer += data
self.resumeProducing()
else:
self.__buffer = self.__buffer + data
... | ValueError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/txredisapi.py/LineReceiver.dataReceived |
5,383 | def lineReceived(self, line):
"""
Reply types:
"-" error message
"+" single line status reply
":" integer number (protocol level only?)
"$" bulk data
"*" multi-bulk data
"""
if line:
self.resetTimeout()
token, data... | ValueError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/txredisapi.py/RedisProtocol.lineReceived |
5,384 | def bulkDataReceived(self, data):
"""
Receipt of a bulk data element.
"""
el = None
if data is not None:
if data and data[0] in _NUM_FIRST_CHARS: # Most likely a number
try:
el = int(data) if data.find('.') == -1 else float(data)
... | ValueError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/txredisapi.py/RedisProtocol.bulkDataReceived |
5,385 | def execute_command(self, *args, **kwargs):
if self.connected == 0:
raise ConnectionError("Not connected")
else:
cmds = []
cmd_template = "$%s\r\n%s\r\n"
for s in args:
if isinstance(s, str):
cmd = s
elif... | NameError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/txredisapi.py/RedisProtocol.execute_command |
5,386 | def fetch_covtype(data_home=None, download_if_missing=True,
random_state=None, shuffle=False):
"""Load the covertype dataset, downloading it if necessary.
Read more in the :ref:`User Guide <datasets>`.
Parameters
----------
data_home : string, optional
Specify another dow... | NameError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/datasets/covtype.py/fetch_covtype |
5,387 | def make_rst(self):
app = import_object(self.arguments[0])
for method, path, endpoint in get_routes(app):
try:
blueprint, _, endpoint_internal = endpoint.rpartition('.')
if self.blueprints and blueprint not in self.blueprints:
continue
... | ValueError | dataset/ETHPy150Open preems/nltk-server/docs/source/sphinxcontrib/autohttp/flask.py/AutoflaskDirective.make_rst |
5,388 | def _get_version(self, listener):
try:
return int(getattr(listener, 'ROBOT_LISTENER_API_VERSION', 1))
except __HOLE__:
return 1 | ValueError | dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/output/listeners.py/_ListenerProxy._get_version |
5,389 | def try_number(value):
"""
Attempt to cast the string `value` to an int, and failing that, a float,
failing that, raise a ValueError.
"""
for cast_function in [int, float]:
try:
return cast_function(value)
except __HOLE__:
pass
raise ValueError("Unable t... | ValueError | dataset/ETHPy150Open alphagov/performanceplatform-collector/performanceplatform/collector/ga/core.py/try_number |
5,390 | def _flush_pipeline(self):
self.io.flush_send()
while True:
try:
reply = self.reply_queue.pop(0)
except __HOLE__:
return None
reply.recv(self.io)
if reply.is_error():
self.last_error = reply | IndexError | dataset/ETHPy150Open slimta/python-slimta/slimta/smtp/client.py/Client._flush_pipeline |
5,391 | def drop_privs(username):
uid = pwd.getpwnam(username).pw_uid
gid = pwd.getpwnam(username).pw_gid
os.setgroups([])
os.setgid(gid)
os.setuid(uid)
try:
os.setuid(0)
except __HOLE__:
pass
else:
raise AssertionError("setuid(0) succeeded after attempting to drop privil... | OSError | dataset/ETHPy150Open arlolra/flashproxy/flashproxy/proc.py/drop_privs |
5,392 | def catch_epipe(fn):
def ret(self, *args):
try:
return fn(self, *args)
except socket.error, e:
try:
err_num = e.errno
except __HOLE__:
# Before Python 2.6, exception can be a pair.
err_num, errstr = e
exc... | AttributeError | dataset/ETHPy150Open arlolra/flashproxy/flashproxy/proc.py/catch_epipe |
5,393 | def upgrade(migrate_engine):
meta.bind = migrate_engine
instances = Table('instances', meta, autoload=True,
autoload_with=migrate_engine)
types = {}
for instance in migrate_engine.execute(instances.select()):
if instance.instance_type_id is None:
types[instance... | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/db/sqlalchemy/migrate_repo/versions/017_make_instance_type_id_an_integer.py/upgrade |
5,394 | def _eventlet_sendfile(fdout, fdin, offset, nbytes):
while True:
try:
return o_sendfile(fdout, fdin, offset, nbytes)
except __HOLE__ as e:
if e.args[0] == errno.EAGAIN:
trampoline(fdout, write=True)
else:
raise | OSError | dataset/ETHPy150Open chalasr/Flask-P2P/venv/lib/python2.7/site-packages/gunicorn/workers/geventlet.py/_eventlet_sendfile |
5,395 | def authenticate(self, token):
# For backwards compatibility only use the ApiToken model if
# Serrano is installed as an app as this was not a requirement
# previously.
if 'serrano' in settings.INSTALLED_APPS:
# NOTE: This has the limitation of requiring the token to be
... | ValueError | dataset/ETHPy150Open chop-dbhi/serrano/serrano/backends.py/TokenBackend.authenticate |
5,396 | def first(self):
"""Retrieve the first object matching the query.
"""
try:
result = self[0]
except __HOLE__:
result = None
return result | IndexError | dataset/ETHPy150Open aparo/django-elasticsearch/django_elasticsearch/manager.py/QuerySet.first |
5,397 | def __getitem__(self, key):
"""Support skip and limit using getitem and slicing syntax.
"""
# Slice provided
if isinstance(key, slice):
try:
self._cursor_obj = self._cursor[key]
self._skip, self._limit = key.start, key.stop
except _... | IndexError | dataset/ETHPy150Open aparo/django-elasticsearch/django_elasticsearch/manager.py/QuerySet.__getitem__ |
5,398 | def daemonize(pidfile=None, progname=None, stdin='/dev/null',
stdout='/dev/null', stderr='/dev/null', umask=022):
"""Fork a daemon process."""
if pidfile:
# Check whether the pid file already exists and refers to a still
# process running
pidfile = os.path.abspath(pidfile)
... | OSError | dataset/ETHPy150Open edgewall/trac/trac/util/daemon.py/daemonize |
5,399 | def test_uninitialized_array(self):
expected = ": out1.x was not initialized. OpenMDAO does not support uninitialized variables."
"""
out1.x is:
- uninitialized
- flattenable
- the source of a connection
- not a slice
"""
top = se... | ValueError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_system.py/UninitializedArray.test_uninitialized_array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.