Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
6,400
def main(): '''Command line version of tool''' import sys import optparse import json class MyParser(optparse.OptionParser): def format_epilog(self, formatter): return self.epilog usage = "%prog [options] filename(s)" parser = MyParser(usage=usage, version ="%prog " + __version__, epilog = """ More info...
IOError
dataset/ETHPy150Open dschwilk/bibstuff/scripts/biblabel.py/main
6,401
def _sqlite_date_extract(lookup_type, dt): if dt is None: return None try: dt = backend_utils.typecast_timestamp(dt) except (ValueError, __HOLE__): return None if lookup_type == 'week_day': return (dt.isoweekday() % 7) + 1 else: return getattr(dt, lookup_type)
TypeError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/base.py/_sqlite_date_extract
6,402
def _sqlite_date_trunc(lookup_type, dt): try: dt = backend_utils.typecast_timestamp(dt) except (__HOLE__, TypeError): return None if lookup_type == 'year': return "%i-01-01" % dt.year elif lookup_type == 'month': return "%i-%02i-01" % (dt.year, dt.month) elif lookup_t...
ValueError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/base.py/_sqlite_date_trunc
6,403
def _sqlite_datetime_parse(dt, tzname): if dt is None: return None try: dt = backend_utils.typecast_timestamp(dt) except (ValueError, __HOLE__): return None if tzname is not None: dt = timezone.localtime(dt, pytz.timezone(tzname)) return dt
TypeError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/base.py/_sqlite_datetime_parse
6,404
def _sqlite_time_extract(lookup_type, dt): if dt is None: return None try: dt = backend_utils.typecast_time(dt) except (ValueError, __HOLE__): return None return getattr(dt, lookup_type)
TypeError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/base.py/_sqlite_time_extract
6,405
def _sqlite_format_dtdelta(conn, lhs, rhs): """ LHS and RHS can be either: - An integer number of microseconds - A string representing a timedelta object - A string representing a datetime """ try: if isinstance(lhs, six.integer_types): lhs = str(decimal.Decim...
TypeError
dataset/ETHPy150Open django/django/django/db/backends/sqlite3/base.py/_sqlite_format_dtdelta
6,406
def parse_bytes(s): if isinstance(s, six.integer_types + (float,)): return s if len(s) == 0: return 0 if s[-2:-1].isalpha() and s[-1].isalpha(): if s[-1] == "b" or s[-1] == "B": s = s[:-1] units = BYTE_UNITS suffix = s[-1].lower() # Check if the variable is ...
ValueError
dataset/ETHPy150Open docker/docker-py/docker/utils/utils.py/parse_bytes
6,407
def get_server_number(ipport, ipport2server): server_number = ipport2server[ipport] server, number = server_number[:-1], server_number[-1:] try: number = int(number) except __HOLE__: # probably the proxy return server_number, None return server, number
ValueError
dataset/ETHPy150Open openstack/swift/test/probe/common.py/get_server_number
6,408
def get_policy(**kwargs): kwargs.setdefault('is_deprecated', False) # go through the policies and make sure they match the # requirements of kwargs for policy in POLICIES: # TODO: for EC, pop policy type here and check it first matches = True for key, value in kwargs.items(): ...
AttributeError
dataset/ETHPy150Open openstack/swift/test/probe/common.py/get_policy
6,409
def read(self, amount): if len(self.buff) < amount: try: self.buff += next(self) except __HOLE__: pass rv, self.buff = self.buff[:amount], self.buff[amount:] return rv
StopIteration
dataset/ETHPy150Open openstack/swift/test/probe/common.py/Body.read
6,410
def reloadConfig(): reloadCommand = [] if args.command: reloadCommand = shlex.split(args.command) else: logger.debug("No reload command provided, trying to find out how to" + " reload the configuration") if os.path.isfile('/etc/init/haproxy.conf'): lo...
OSError
dataset/ETHPy150Open mesosphere/marathon-lb/marathon_lb.py/reloadConfig
6,411
def compareWriteAndReloadConfig(config, config_file): # See if the last config on disk matches this, and if so don't reload # haproxy runningConfig = str() try: logger.debug("reading running config from %s", config_file) with open(config_file, "r") as f: runningConfig = f.rea...
IOError
dataset/ETHPy150Open mesosphere/marathon-lb/marathon_lb.py/compareWriteAndReloadConfig
6,412
def return_detail(self, key): """ This will attempt to match a "detail" to look for in the room. Args: key (str): A detail identifier. Returns: detail (str or None): A detail mathing the given key. Notes: A detail is a way to offer more thin...
AttributeError
dataset/ETHPy150Open evennia/evennia/evennia/contrib/extended_room.py/ExtendedRoom.return_detail
6,413
@patch('beets.plugins.find_plugins') def test_listener_params(self, mock_find_plugins): test = self class DummyPlugin(plugins.BeetsPlugin): def __init__(self): super(DummyPlugin, self).__init__() for i in itertools.count(1): try: ...
AttributeError
dataset/ETHPy150Open beetbox/beets/test/test_plugins.py/ListenersTest.test_listener_params
6,414
def PILExporter(image, file_handle, extension='', **kwargs): r""" Given a file handle to write in to (which should act like a Python `file` object), write out the image data. No value is returned. Uses PIL to save the image and so supports most commonly used image formats. Parameters -----...
KeyError
dataset/ETHPy150Open menpo/menpo/menpo/io/output/image.py/PILExporter
6,415
def makeTodo(value): """ Return a L{Todo} object built from C{value}. If C{value} is a string, return a Todo that expects any exception with C{value} as a reason. If C{value} is a tuple, the second element is used as the reason and the first element as the excepted error(s). @param value: A st...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/unittest.py/makeTodo
6,416
def getTimeout(self): """ Returns the timeout value set on this test. Checks on the instance first, then the class, then the module, then packages. As soon as it finds something with a C{timeout} attribute, returns that. Returns L{util.DEFAULT_TIMEOUT_DURATION} if it cannot find ...
ValueError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/unittest.py/TestCase.getTimeout
6,417
def decorate(test, decorator): """ Decorate all test cases in C{test} with C{decorator}. C{test} can be a test case or a test suite. If it is a test suite, then the structure of the suite is preserved. L{decorate} tries to preserve the class of the test suites it finds, but assumes the presenc...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/unittest.py/decorate
6,418
def _iterateTests(testSuiteOrCase): """ Iterate through all of the test cases in C{testSuiteOrCase}. """ try: suite = iter(testSuiteOrCase) except __HOLE__: yield testSuiteOrCase else: for test in suite: for subtest in _iterateTests(test): yiel...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/unittest.py/_iterateTests
6,419
def read(filename): PID = 0 CVE = 1 CVSS = 2 RISK = 3 HOST = 4 PROTOCOL = 5 PORT = 6 NAME = 7 SYNOPSIS = 8 DESCRIPTION = 9 SOLUTION = 10 OUTPUT = 11 host_to_vulns = {} vuln_to_hosts = {} id_to_name = {} host_to_ip = {} id_to_severity = {} try: ...
IOError
dataset/ETHPy150Open maxburkhardt/nessus-parser/util/reader.py/read
6,420
def createPortItem(self, port, x, y): """ createPortItem(port: Port, x: int, y: int) -> QGraphicsPortItem Create a item from the port spec """ # pts = [(0,2),(0,-2), (2,None), (-2,None), # (None,-2), (None,2), (-2,0), (2,0)] # pts = [(0,0.2), (0, 0.8), (0....
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/pipeline_view.py/QGraphicsModuleItem.createPortItem
6,421
def set_module_computing(self, moduleId): """ set_module_computing(moduleId: int) -> None Post an event to the scene (self) for updating the module color """ p = self.controller.progress if p is not None: self.check_progress_canceled() pipeline = ...
KeyError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/pipeline_view.py/QPipelineScene.set_module_computing
6,422
def is_int(self, text): try: int(text) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open cloudera/hue/apps/oozie/src/oozie/models.py/Dataset.is_int
6,423
def has_installed(dependency): try: importlib.import_module(dependency) return True except __HOLE__: return False
ImportError
dataset/ETHPy150Open python-thumbnails/python-thumbnails/tests/utils.py/has_installed
6,424
def __get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except __HOLE__: return default if callable(attr): # Check func_code.co_argcount rather than try/excepting the # function and catching the TypeError, becau...
AttributeError
dataset/ETHPy150Open llazzaro/django-scheduler/schedule/feeds/atom.py/Feed.__get_dynamic_attr
6,425
def get_feed(self, extra_params=None): if extra_params: try: obj = self.get_object(extra_params.split('/')) except (__HOLE__, LookupError): raise LookupError('Feed does not exist') else: obj = None feed = AtomFeed( ...
AttributeError
dataset/ETHPy150Open llazzaro/django-scheduler/schedule/feeds/atom.py/Feed.get_feed
6,426
def json_splitter(buffer): """Attempt to parse a json object from a buffer. If there is at least one object, return it and the rest of the buffer, otherwise return None. """ try: obj, index = json_decoder.raw_decode(buffer) rest = buffer[json.decoder.WHITESPACE.match(buffer, index).end()...
ValueError
dataset/ETHPy150Open docker/compose/compose/utils.py/json_splitter
6,427
def get_key(self, network_id): try: return self[network_id] except __HOLE__: raise TunnelKeyNotFound(network_id=network_id)
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/controller/tunnels.py/TunnelKeys.get_key
6,428
def delete_key(self, network_id): try: tunnel_key = self[network_id] self.send_event(EventTunnelKeyDel(network_id, tunnel_key)) del self[network_id] except __HOLE__: raise ryu_exc.NetworkNotFound(network_id=network_id)
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/controller/tunnels.py/TunnelKeys.delete_key
6,429
def get_remote_dpid(self, dpid, port_no): try: return self.dpids[dpid][port_no] except __HOLE__: raise ryu_exc.PortNotFound(dpid=dpid, port=port_no)
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/controller/tunnels.py/DPIDs.get_remote_dpid
6,430
def delete_port(self, dpid, port_no): try: remote_dpid = self.dpids[dpid][port_no] self.send_event(EventTunnelPort(dpid, port_no, remote_dpid, False)) del self.dpids[dpid][port_no] except __HOLE__: raise ryu_exc.PortNotFound(dpid=dpid, port=port_no)
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/controller/tunnels.py/DPIDs.delete_port
6,431
def get_port(self, dpid, remote_dpid): try: dp = self.dpids[dpid] except __HOLE__: raise ryu_exc.PortNotFound(dpid=dpid, port=None, network_id=None) res = [port_no for (port_no, remote_dpid_) in dp.items() if remote_dpid_ == remote_dpid] assert len...
KeyError
dataset/ETHPy150Open osrg/ryu/ryu/controller/tunnels.py/DPIDs.get_port
6,432
def len(obj): try: return _len(obj) except __HOLE__: try: # note: this is an internal undocumented API, # don't rely on it in your own programs return obj.__length_hint__() except AttributeError: raise TypeError
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_iterlen.py/len
6,433
def test_queue_task_done(self): # Test to make sure a queue task completed successfully. q = self.type2test() try: q.task_done() except __HOLE__: pass else: self.fail("Did not detect task count going negative")
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_queue.py/BaseQueueTestMixin.test_queue_task_done
6,434
def test_queue_join(self): # Test that a queue join()s successfully, and before anything else # (done twice for insurance). q = self.type2test() self.queue_join_test(q) self.queue_join_test(q) try: q.task_done() except __HOLE__: pass ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_queue.py/BaseQueueTestMixin.test_queue_join
6,435
def server_error(request): """Own view in order to pass RequestContext and send an error message. """ exc_type, exc_info, tb = sys.exc_info() response = "%s\n" % exc_type.__name__ response += "%s\n" % exc_info response += "TRACEBACK:\n" for tb in traceback.format_tb(tb): response += ...
IndexError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/views.py/server_error
6,436
def generate_getconn(engine, user, password, host, port, dbname, dirname = None): kwargs = {} if engine == 'mysql': # If using mysql, choose among MySQLdb or pymysql, # Trying to load MySQLdb, and if it fails, trying # to load and register pymysql try: import MySQLd...
ImportError
dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/voodoo/dbutil.py/generate_getconn
6,437
def py2js(v): """Note that None values are rendered as ``null`` (not ``undefined``. """ # assert _for_user_profile is not None # logger.debug("py2js(%r)",v) for cv in CONVERTERS: v = cv(v) # if isinstance(v,LanguageInfo): # return v.django_code if isinstance(v, Value): ...
TypeError
dataset/ETHPy150Open lsaffre/lino/lino/utils/jsgen.py/py2js
6,438
def clean_upload_data(data): image = data['image'] image.seek(0) try: pil_image = PIL.Image.open(image) except __HOLE__ as e: if e.errno: error_msg = force_unicode(e) else: error_msg = u"Invalid or unsupported image file" raise forms.ValidationErro...
IOError
dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/forms.py/clean_upload_data
6,439
def _existing_object(self, pk): """ Avoid potentially expensive list comprehension over self.queryset() in the parent method. """ if not hasattr(self, '_object_dict'): self._object_dict = {} if not pk: return None try: obj = sel...
ObjectDoesNotExist
dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/views/forms.py/ThumbFormSet._existing_object
6,440
def check_reload(self): filenames = list(self.extra_files) for file_callback in self.file_callbacks: try: filenames.extend(file_callback()) except: print("Error calling paste.reloader callback %r:" % file_callback, file=sys.st...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/reloader.py/Monitor.check_reload
6,441
def read(self, path): logInfo = {} logInfo["statistics"] = {} logInfo["config"] = {} logInfo["distribution"] = {} logInfo["summary"] = {} file_id = open(path, "r") line = file_id.readline() while(line): config_pattern_matched = re.search(self.c...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.read
6,442
def readStats(self, file_id): statDic = {} binPattern = '~([^~]+) Bin Statistics' setPattern = '~([^~]+) Set Statistics' servicePattern = 'Service Statistics' nsPattern = '~([^~]+) Namespace Statistics' xdrPattern = 'XDR Statistics' dcPattern = '~([^~]+) DC Stati...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.readStats
6,443
def readConfig(self, file_id): configDic = {} servicePattern = '(~+)Service Configuration(~+)' netPattern = '(~+)Network Configuration(~+)' nsPattern = '~([^~]+)Namespace Configuration(~+)' xdrPattern = '(~+)XDR Configuration(~+)' dcPattern = '~([^~]+)DC Configuration(~+)...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.readConfig
6,444
def readLatency(self, file_id): configDic = {} pattern = '~([^~]+) Latency(~+)' line = file_id.readline() while(not re.search(self.section_separator, line) and not re.search(self.section_separator_with_date,line)): if line.strip().__len__() != 0: m1 = re.se...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.readLatency
6,445
def readSummaryStr(self, file_id): line = file_id.readline() summaryStr = "" while(not re.search(self.section_separator, line) and not re.search(self.section_separator_with_date,line)): if line.strip().__len__() != 0: summaryStr += line try: ...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.readSummaryStr
6,446
def readDistribution(self, file_id): configDic = {} ttlPattern = '~([^~]+) - TTL Distribution in Seconds(~+)' evictPattern = '~([^~]+) - Eviction Distribution in Seconds(~+)' objszPattern = '~([^~]+) - Object Size Distribution in Record Blocks(~+)' objszBytesPattern = '([^~]+) -...
IndexError
dataset/ETHPy150Open aerospike/aerospike-admin/lib/logreader.py/LogReader.readDistribution
6,447
def post_dispatch_input(self, etype, me): '''This function is called by dispatch_input() when we want to dispatch an input event. The event is dispatched to all listeners and if grabbed, it's dispatched to grabbed widgets. ''' # update available list if etype == 'begin': ...
AttributeError
dataset/ETHPy150Open kivy/kivy/kivy/base.py/EventLoopBase.post_dispatch_input
6,448
def extract_features_using_pefile(self, pe): ''' Process the PE File using the Python pefile module. ''' # Store all extracted features into feature lists extracted_dense = {} extracted_sparse = {} # Now slog through the info and extract the features feature_not_found_f...
ValueError
dataset/ETHPy150Open ClickSecurity/data_hacking/pefile_classification/pe_features.py/PEFileFeatures.extract_features_using_pefile
6,449
def __init__(self, bot): self.bot = bot self.db = os.path.expanduser( bot.config.get('human', '~/.irc3/human.db')) self.delay = (2, 5) try: os.makedirs(os.path.dirname(self.db)) except __HOLE__: pass if not os.path.isfile(self.db): # p...
OSError
dataset/ETHPy150Open gawel/irc3/irc3/plugins/human.py/Human.__init__
6,450
def _parse_bytes(range_header): """Parses a full HTTP Range header. Args: range_header: The str value of the Range header. Returns: A tuple (units, parsed_ranges) where: units: A str containing the units of the Range header, e.g. "bytes". parsed_ranges: A list of (start, end) tuples in the f...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/webapp/blobstore_handlers.py/_parse_bytes
6,451
@attr('numpy') def test_biadjacency_matrix_weight(self): try: import numpy except __HOLE__: raise SkipTest('numpy not available.') G=nx.path_graph(5) G.add_edge(0,1,weight=2,other=4) X=[1,3] Y=[0,2,4] M = bipartite.biadjacency_matrix(G,...
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/bipartite/tests/test_basic.py/TestBipartiteBasic.test_biadjacency_matrix_weight
6,452
@attr('numpy') def test_biadjacency_matrix(self): try: import numpy except __HOLE__: raise SkipTest('numpy not available.') tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = nx.bipartite_random_graph(tops[i], bots[i], 0.2) ...
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/bipartite/tests/test_basic.py/TestBipartiteBasic.test_biadjacency_matrix
6,453
@attr('numpy') def test_biadjacency_matrix_order(self): try: import numpy except __HOLE__: raise SkipTest('numpy not available.') G=nx.path_graph(5) G.add_edge(0,1,weight=2) X=[3,1] Y=[4,2,0] M = bipartite.biadjacency_matrix(G,X,Y,weigh...
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/bipartite/tests/test_basic.py/TestBipartiteBasic.test_biadjacency_matrix_order
6,454
def _get_docs_from_pyobject(obj, options, progress_estimator): progress_estimator.complete += 1 log.progress(progress_estimator.progress(), repr(obj)) if not options.introspect: log.error("Cannot get docs for Python objects without " "introspecting them.") int...
ImportError
dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docbuilder.py/_get_docs_from_pyobject
6,455
def _get_docs_from_pyname(name, options, progress_estimator, supress_warnings=False): progress_estimator.complete += 1 if options.must_introspect(name) or options.must_parse(name): log.progress(progress_estimator.progress(), name) introspect_doc = parse_doc = None ...
ImportError
dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docbuilder.py/_get_docs_from_pyname
6,456
def _get_docs_from_pyscript(filename, options, progress_estimator): # [xx] I should be careful about what names I allow as filenames, # and maybe do some munging to prevent problems. introspect_doc = parse_doc = None introspect_error = parse_error = None if options.introspect: try: ...
ImportError
dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docbuilder.py/_get_docs_from_pyscript
6,457
def _get_docs_from_module_file(filename, options, progress_estimator, parent_docs=(None,None)): """ Construct and return the API documentation for the python module with the given filename. @param parent_docs: The C{ModuleDoc} of the containing package. If C{paren...
ImportError
dataset/ETHPy150Open ardekantur/pyglet/tools/epydoc/epydoc/docbuilder.py/_get_docs_from_module_file
6,458
def import_module(module): """ Allows custom providers, configurators and distros. Import the provider, configurator, or distro module via a string. ex. ``bootmachine.contrib.providers.rackspace_openstack_v2`` ex. ``bootmachine.contrib.configurators.salt`` ex. ``bootmachine.contrib....
ImportError
dataset/ETHPy150Open rizumu/bootmachine/bootmachine/core.py/import_module
6,459
@task def reboot_server(name): """ Simply reboot a server by name. The trick here is to change the env vars to that of the server to be rebooted. Perform the reboot and change env vars back to their original value. Usage: fab reboot_server:name """ __shared_setup() try: ...
IOError
dataset/ETHPy150Open rizumu/bootmachine/bootmachine/core.py/reboot_server
6,460
def __set_ssh_vars(valid_object): """ This method takes a valid_object, either the env or a server, and based on the results of telnet, it sets port, user, host_string varibles for ssh. It also sets a configured variable if the SSH_PORT matches that in the settings. This would only match if the ...
IOError
dataset/ETHPy150Open rizumu/bootmachine/bootmachine/core.py/__set_ssh_vars
6,461
def daemonize(self): """ Do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: ...
OSError
dataset/ETHPy150Open oleiade/Elevator/debian/elevator/usr/lib/python2.6/dist-packages/elevator/utils/daemon.py/Daemon.daemonize
6,462
def start(self, *args, **kwargs): """ Start the daemon """ if self.verbose >= 1: print "Starting..." # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf...
IOError
dataset/ETHPy150Open oleiade/Elevator/debian/elevator/usr/lib/python2.6/dist-packages/elevator/utils/daemon.py/Daemon.start
6,463
def stop(self): """ Stop the daemon """ if self.verbose >= 1: print "Stopping..." # Get the pid from the pidfile try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except __HOLE__: ...
IOError
dataset/ETHPy150Open oleiade/Elevator/debian/elevator/usr/lib/python2.6/dist-packages/elevator/utils/daemon.py/Daemon.stop
6,464
def _nanargmin(x, axis, **kwargs): try: return chunk.nanargmin(x, axis, **kwargs) except __HOLE__: return chunk.nanargmin(np.where(np.isnan(x), np.inf, x), axis, **kwargs)
ValueError
dataset/ETHPy150Open dask/dask/dask/array/reductions.py/_nanargmin
6,465
def _nanargmax(x, axis, **kwargs): try: return chunk.nanargmax(x, axis, **kwargs) except __HOLE__: return chunk.nanargmax(np.where(np.isnan(x), -np.inf, x), axis, **kwargs)
ValueError
dataset/ETHPy150Open dask/dask/dask/array/reductions.py/_nanargmax
6,466
def callit(f, funct): try: funct(f) except (__HOLE__, Exception), err: f.write(str(err)+'\n')
SystemExit
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/envirodump.py/callit
6,467
def decode(data): """ Decode data employing some charset detection and including unicode BOM stripping. """ # Don't make more work than we have to. if not isinstance(data, str): return data # Detect standard unicodes. for bom, encoding in UNICODES: if data.startswith(bo...
UnicodeDecodeError
dataset/ETHPy150Open mozilla/app-validator/appvalidator/unicodehelper.py/decode
6,468
def UrlEncode(s): try: return urllib.parse.quote_plus(s) except __HOLE__: return urllib.quote_plus(s)
AttributeError
dataset/ETHPy150Open coronalabs/CoronaSDK-SublimeText/corona_docs.py/UrlEncode
6,469
def mergeFunctionMetadata(f, g): """ Overwrite C{g}'s name and docstring with values from C{f}. Update C{g}'s instance dictionary with C{f}'s. To use this function safely you must use the return value. In Python 2.3, L{mergeFunctionMetadata} will create a new function. In later versions of Pyt...
AttributeError
dataset/ETHPy150Open bokeh/bokeh/bokeh/util/deprecate.py/mergeFunctionMetadata
6,470
def read_list(self): # Clear rules and move on if file isn't there if not os.path.exists(self.list_file): self.regex_list = [] return try: mtime = os.path.getmtime(self.list_file) except __HOLE__: log.err("Failed to get mtime of %s" % self.list_file) return if mtime <...
OSError
dataset/ETHPy150Open graphite-project/carbon/lib/carbon/regexlist.py/RegexList.read_list
6,471
def _saveModel(self): delimiter = self._delimiterBox.currentSelected() header = self._headerCheckBox.isChecked() # column labels filename = self._filenameLineEdit.text() index = False # row labels encodingIndex = self._encodingComboBox.currentIndex() encoding = self._enc...
IOError
dataset/ETHPy150Open datalyze-solutions/pandas-qt/pandasqt/views/CSVDialogs.py/CSVExportDialog._saveModel
6,472
def test_nullbooleanfield_blank(self): """ Regression test for #13071: NullBooleanField should not throw a validation error when given a value of None. """ nullboolean = NullBooleanModel(nbfield=None) try: nullboolean.full_clean() except __HOLE__, e: ...
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/model_fields/tests.py/BasicFieldTests.test_nullbooleanfield_blank
6,473
def sniff(self): self.initialize_socket() try: while(True): try: data = self.sock.recv(1024) request = unpack_lifx_message(data) print("\nRECV:"), print(request) ...
KeyboardInterrupt
dataset/ETHPy150Open mclarkk/lifxlan/examples/sniffer.py/Sniffer.sniff
6,474
def _parseLine(self, line): try: key, val = line.split(':', 1) except __HOLE__: # unpack list of wrong size # -> invalid input data raise LDIFLineWithoutSemicolonError, line val = self.parseValue(val) return key, val
ValueError
dataset/ETHPy150Open antong/ldaptor/ldaptor/protocols/ldap/ldifprotocol.py/LDIF._parseLine
6,475
def state_HEADER(self, line): key, val = self._parseLine(line) self.mode = WAIT_FOR_DN if key != 'version': self.logicalLineReceived(line) else: try: version = int(val) except __HOLE__: raise LDIFVersionNotANumberError,...
ValueError
dataset/ETHPy150Open antong/ldaptor/ldaptor/protocols/ldap/ldifprotocol.py/LDIF.state_HEADER
6,476
def __init__(self, **kwargs): super(Route53Service, self).__init__(**kwargs) self.conn = boto.connect_route53() try: self.hostname = os.environ['EC2_PUBLIC_HOSTNAME'] except __HOLE__: app.logger.warn("We cannot register a domain on non ec2 instances")
KeyError
dataset/ETHPy150Open Netflix/security_monkey/security_monkey/common/route53.py/Route53Service.__init__
6,477
def PatternResolution( quad, cursor, BRPs, orderByTriple=True, fetchall=True, fetchContexts=False, select_modifier=''): """ This function implements query pattern resolution against a list of partition objects and 3 parameters specifying whether to sort the result...
ValueError
dataset/ETHPy150Open RDFLib/rdfextras/rdfextras/store/FOPLRelationalModel/BinaryRelationPartition.py/PatternResolution
6,478
def _on_raw(func_name): """ Like query_super, but makes the operation run on the raw string. """ def wrapped(self, *args, **kwargs): args = list(args) try: string = args.pop(0) if hasattr(string, '_raw_string'): args.insert(0, string.raw()) ...
IndexError
dataset/ETHPy150Open evennia/evennia/evennia/utils/ansi.py/_on_raw
6,479
def _slice(self, slc): """ This function takes a slice() object. Slices have to be handled specially. Not only are they able to specify a start and end with [x:y], but many forget that they can also specify an interval with [x:y:z]. As a result, not only do we have to track ...
IndexError
dataset/ETHPy150Open evennia/evennia/evennia/utils/ansi.py/ANSIString._slice
6,480
def __getitem__(self, item): """ Gateway for slices and getting specific indexes in the ANSIString. If this is a regexable ANSIString, it will get the data from the raw string instead, bypassing ANSIString's intelligent escape skipping, for reasons explained in the __new__ method...
IndexError
dataset/ETHPy150Open evennia/evennia/evennia/utils/ansi.py/ANSIString.__getitem__
6,481
def _get_interleving(self, index): """ Get the code characters from the given slice end to the next character. """ try: index = self._char_indexes[index - 1] except __HOLE__: return '' s = '' while True: index += 1 ...
IndexError
dataset/ETHPy150Open evennia/evennia/evennia/utils/ansi.py/ANSIString._get_interleving
6,482
def _filler(self, char, amount): """ Generate a line of characters in a more efficient way than just adding ANSIStrings. """ if not isinstance(char, ANSIString): line = char * amount return ANSIString( char * amount, code_indexes=[], char_...
IndexError
dataset/ETHPy150Open evennia/evennia/evennia/utils/ansi.py/ANSIString._filler
6,483
def to_internal_value(self, value): try: year, month = [int(el) for el in value.split('.')] except __HOLE__: raise serializers.ValidationError('Value "{}" should be valid be in format YYYY.MM'.format(value)) if not 0 < month < 13: raise serializers.ValidationE...
ValueError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/cost_tracking/serializers.py/YearMonthField.to_internal_value
6,484
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: ...
RuntimeError
dataset/ETHPy150Open Tanganelli/CoAPthon/coapthon/server/coap.py/CoAP.listen
6,485
def add_resource(self, path, resource): """ Helper function to add resources to the resource directory during server initialization. :param path: the path for the new created resource :type resource: Resource :param resource: the resource to be added """ assert ...
KeyError
dataset/ETHPy150Open Tanganelli/CoAPthon/coapthon/server/coap.py/CoAP.add_resource
6,486
def _retransmit(self, transaction, message, future_time, retransmit_count): """ Thread function to retransmit the message in the future :param transaction: the transaction that owns the message that needs retransmission :param message: the message that needs the retransmission task ...
ValueError
dataset/ETHPy150Open Tanganelli/CoAPthon/coapthon/server/coap.py/CoAP._retransmit
6,487
def updateVersion(self, versionNumber): """ updateVersion(versionNumber: int) -> None Update the property page of the version """ self.versionNumber = versionNumber self.versionNotes.updateVersion(versionNumber) self.versionThumbs.updateVersion(versionNumber) ...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/version_prop.py/QVersionProp.updateVersion
6,488
def pop(self, key, default=__marker): """D.pop(k[,d]) -> v, remove specified key and return the value. If key is not found, d is returned if given, otherwise KeyError is raised. """ # Using the MutableMapping function directly fails due to the private # marker. #...
KeyError
dataset/ETHPy150Open sigmavirus24/betamax/betamax/headers.py/HTTPHeaderDict.pop
6,489
def discard(self, key): try: del self[key] except __HOLE__: pass
KeyError
dataset/ETHPy150Open sigmavirus24/betamax/betamax/headers.py/HTTPHeaderDict.discard
6,490
def getlist(self, key): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._container[key.lower()] except __HOLE__: return [] else: if isinstance(vals, tuple): ...
KeyError
dataset/ETHPy150Open sigmavirus24/betamax/betamax/headers.py/HTTPHeaderDict.getlist
6,491
def build_split_list(self, expr): ''' Take the max_char function and break up an expression list based on the character limits of individual items ''' if isinstance(expr, str): expr = expr.split(',') expr.sort() new_list = [] running_total ...
IndexError
dataset/ETHPy150Open linkedin/sysops-api/seco/range/__init__.py/Range.build_split_list
6,492
def conjugate_row(row, K): """ Returns the conjugate of a row element-wise Examples ======== >>> from sympy.matrices.densetools import conjugate_row >>> from sympy import ZZ >>> a = [ZZ(3), ZZ(2), ZZ(6)] >>> conjugate_row(a, ZZ) [3, 2, 6] """ result = [] for r in row: ...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/matrices/densetools.py/conjugate_row
6,493
def short(self, url): params = {'url': url} response = self._post(self.api_url, data=params) if response.ok: try: data = response.json() except __HOLE__: raise ShorteningErrorException('There was an error shortening' ...
ValueError
dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/readability.py/Readability.short
6,494
def expand(self, url): url_id = url.split('/')[-1] api_url = '{0}{1}'.format(self.api_url, url_id) response = self._get(api_url) if response.ok: try: data = response.json() except __HOLE__ as e: raise ExpandingErrorException('There ...
ValueError
dataset/ETHPy150Open ellisonleao/pyshorteners/pyshorteners/shorteners/readability.py/Readability.expand
6,495
def enable(self): self.options = {} for name, operations in self.operations: try: # When called from SimpleTestCase._pre_setup, values may be # overridden several times; cumulate changes. value = self.options[name] except __HOLE__: ...
KeyError
dataset/ETHPy150Open jazzband/django-pipeline/tests/utils.py/modify_settings.enable
6,496
def run(self): self._push_rpc = pushrpc.PushRPC(self._push_event_callback, self._args) # These modules should work 100% of the time - # they don't need special hardware, or root self._proxies = { 'hue': hue.Hue(self._args.hue_scan_interval_secs, self._device_event_callbac...
KeyboardInterrupt
dataset/ETHPy150Open tomwilkie/awesomation/src/pi/control.py/Control.run
6,497
def read_ints(self, shape, order='C', full_record=False): """ Returns integers as a :mod:`numpy` array of `shape`. shape: tuple(int) Dimensions of returned array. order: string If 'C', the data is in row-major order. If 'Fortran', the data is in colu...
TypeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/stream.py/Stream.read_ints
6,498
def read_floats(self, shape, order='C', full_record=False): """ Returns floats as a :mod:`numpy` array of `shape`. shape: tuple(int) Dimensions of returned array. order: string If 'C', the data is in row-major order. If 'Fortran', the data is in colu...
TypeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/stream.py/Stream.read_floats
6,499
def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handlers: ...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/http/multipartparser.py/MultiPartParser.__init__