Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
4,500
def import_book(stream): """Return dataset of given stream.""" (format, stream) = detect(stream) try: databook = Databook() format.import_book(databook, stream) return databook except __HOLE__: return None
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/core.py/import_book
4,501
@osbsapi def create_build(self, **kwargs): """ take input args, create build request from provided build type and submit the build :param kwargs: keyword args for build :return: instance of BuildRequest """ build_type = self.build_conf.get_build_type() if bui...
KeyError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/api.py/OSBS.create_build
4,502
def isclass(obj): try: issubclass(obj, object) except __HOLE__: return False else: return True
TypeError
dataset/ETHPy150Open nicolaiarocci/cerberus/cerberus/utils.py/isclass
4,503
def get_library_instance(self, libname): try: return self._testlibs[libname.replace(' ', '')].get_instance() except __HOLE__: raise DataError("No library with name '%s' found." % libname)
KeyError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/running/namespace.py/Namespace.get_library_instance
4,504
def _is_old_x_times_syntax(self, name): if not name.lower().endswith('x'): return False times = name[:-1].strip() if is_scalar_var(times): return True try: int(times) except __HOLE__: return False else: return Tr...
ValueError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/running/namespace.py/Namespace._is_old_x_times_syntax
4,505
def _get_commands(self): try: variables = Utils.get_variables_from_file(self.abspath, self.script_encoding) SQL_UP = Migration.ensure_sql_unicode(variables['SQL_UP'], self.script_encoding) SQL_DOWN = Migration.ensure_sql_unicode(variables['SQL_DOWN'], self.script_encoding) ...
KeyError
dataset/ETHPy150Open guilhermechapiewski/simple-db-migrate/simple_db_migrate/core/__init__.py/Migration._get_commands
4,506
@staticmethod def create(migration_name, migration_dir='.', script_encoding='utf-8', utc_timestamp = False): timestamp = strftime("%Y%m%d%H%M%S", gmtime() if utc_timestamp else localtime()) file_name = "%s_%s%s" % (timestamp, migration_name, Migration.MIGRATION_FILES_EXTENSION) if not Migra...
IOError
dataset/ETHPy150Open guilhermechapiewski/simple-db-migrate/simple_db_migrate/core/__init__.py/Migration.create
4,507
def get_all_migrations(self): if self.all_migrations: return self.all_migrations migrations = [] for _dir in self._migrations_dir: path = os.path.abspath(_dir) dir_list = None try: dir_list = os.listdir(path) except _...
OSError
dataset/ETHPy150Open guilhermechapiewski/simple-db-migrate/simple_db_migrate/core/__init__.py/SimpleDBMigrate.get_all_migrations
4,508
def _makeTracePlayable(self, trace, traceFileName, checkCoherence = True): """Makes sure that the given trace is playable. @returns a tuple (trace_file_name, is_temporary), where the is_temporary flag indicates that the trace file is temporary and should be deleted after...
IndexError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/plugins/player/Player.py/TracePlayer._makeTracePlayable
4,509
def testUnknownType(self): for value in [None, 19410, "xyz"]: try: outils.ContainerToDicts(value) except __HOLE__, err: self.assertTrue(str(err).startswith("Unknown container type")) else: self.fail("Exception was not raised")
TypeError
dataset/ETHPy150Open ganeti/ganeti/test/py/ganeti.outils_unittest.py/TestContainerToDicts.testUnknownType
4,510
def testUnknownType(self): for cls in [str, int, bool]: try: outils.ContainerFromDicts(None, cls, NotImplemented) except __HOLE__, err: self.assertTrue(str(err).startswith("Unknown container type")) else: self.fail("Exception was not raised") try: outils.Cont...
TypeError
dataset/ETHPy150Open ganeti/ganeti/test/py/ganeti.outils_unittest.py/TestContainerFromDicts.testUnknownType
4,511
def define_find_libary(): import re import tempfile import errno def _findlib_gcc(name): expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name) fdout, ccout = tempfile.mkstemp() _os.close(fdout) cmd = 'if type gcc >/dev/null 2>&1; then CC...
OSError
dataset/ETHPy150Open hgrecco/pyvisa/pyvisa/ctwrapper/cthelper.py/define_find_libary
4,512
def django_tests(verbosity, interactive, failfast, test_labels): from django.conf import settings state = setup(verbosity, test_labels) # Add tests for invalid models. extra_tests = [] for model_dir, model_name in get_invalid_models(): model_label = '.'.join([model_dir, model_name]) ...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/runtests.py/django_tests
4,513
def bisect_tests(bisection_label, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] for app in get...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/runtests.py/bisect_tests
4,514
def paired_tests(paired_test, options, test_labels): state = setup(int(options.verbosity), test_labels) if not test_labels: print "" # Get the full list of test labels to use for bisection from django.db.models.loading import get_apps test_labels = [app.__name__.split('.')[-2] f...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/runtests.py/paired_tests
4,515
def sort_by(iterable, sortstr=None, reverse=False, col_map=None, default_type=None, default_value=None): """sort an iterable, cast to ``col_map.get(colkey, default_type)``, and default to ``default_value``. Args: iterable (iterable): itera...
ValueError
dataset/ETHPy150Open westurner/pyline/pyline.py/sort_by
4,516
def str2boolintorfloat(str_): """ Try to cast a string as a ``bool``, ``float``, ``int``, or ``str_.__class__``. Args: str_ (basestring): string to try and cast Returns: object: casted ``{boot, float, int, or str_.__class__}`` """ match = re.match('([\d\.]+)', str_) type...
ValueError
dataset/ETHPy150Open westurner/pyline/pyline.py/str2boolintorfloat
4,517
def get_request_url(self, request_id): """Returns the URL the request e.g. 'http://localhost:8080/foo?bar=baz'. Args: request_id: The string id of the request making the API call. Returns: The URL of the request as a string. """ try: host = os.environ['HTTP_HOST'] except __HO...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/request_info.py/_LocalRequestInfo.get_request_url
4,518
def main(argv=None): import lymph.monkey lymph.monkey.patch() import docopt import sys import logging from lymph import __version__ as VERSION from lymph.cli.help import HELP from lymph.cli.base import get_command_class from lymph.utils import logging as lymph_logging bootup_h...
KeyError
dataset/ETHPy150Open deliveryhero/lymph/lymph/cli/main.py/main
4,519
def main(directory): if not os.path.isdir(directory): sys.exit("ERROR: {} is not a directory".format(directory)) # tag the metrics to group them together metrics.tag("worker_latency", "worker") metrics.tag("worker_throughput", "worker") # register a csv reporter that will dump the metrics ...
KeyboardInterrupt
dataset/ETHPy150Open avalente/appmetrics/examples/csv_reporter.py/main
4,520
def get_remote(self, node, method): method = method or "ssh" key = (node.name, method) remote = self.remotes.get(key) if not remote: parts = method.split(":", 1) if len(parts) == 2: method, args = parts args = [args] els...
KeyError
dataset/ETHPy150Open ohmu/poni/poni/rcontrol_all.py/RemoteManager.get_remote
4,521
def _read(fname): try: return open(op.join(op.dirname(__file__), fname)).read() except __HOLE__: return ''
IOError
dataset/ETHPy150Open klen/flask-pw/setup.py/_read
4,522
def run(self): try: while True: with self.abort_lock: if self.abort_flag: return # Get the value from the generator. try: msg = self.coro.next() except __HOLE__: ...
StopIteration
dataset/ETHPy150Open beetbox/beets/beets/util/pipeline.py/FirstPipelineThread.run
4,523
def get_vid_for_direction(instance, direction): ''' get next video instance based on direction and current video instance''' category = instance.category video_qs = category.video_set.all() if direction == "next": new_qs = video_qs.filter(order__gt=instance.order) else: new_qs = video_qs.filter(order__lt=insta...
IndexError
dataset/ETHPy150Open codingforentrepreneurs/srvup-membership/src/videos/utils.py/get_vid_for_direction
4,524
def writeData(self,req,tblName): try: res = writeDataSrvResponse() db_username,db_password=self.getLogin() con = mdb.connect('localhost', db_username, db_password, 'RappStore'); cur = con.cursor() returncols=self.constructCommaColumns(req.req_cols) if (len(returncols)>1): ...
IOError
dataset/ETHPy150Open rapp-project/rapp-platform/rapp_mysql_wrapper/src/mysql_wrapper.py/MySQLdbWrapper.writeData
4,525
def deleteData(self,req,tblName): try: res = deleteDataSrvResponse() db_username,db_password=self.getLogin() con = mdb.connect('localhost', db_username, db_password, 'RappStore'); cur = con.cursor() where=self.constructAndQuery(req.where_data) query="Delete from "+tblName+where ...
IOError
dataset/ETHPy150Open rapp-project/rapp-platform/rapp_mysql_wrapper/src/mysql_wrapper.py/MySQLdbWrapper.deleteData
4,526
def updateData(self,req,tblName): try: res = updateDataSrvResponse() db_username,db_password=self.getLogin() con = mdb.connect('localhost', db_username, db_password, 'RappStore'); cur = con.cursor() returncols=self.constructCommaColumns(req.set_cols) where=self.constructAndQuery(...
IndexError
dataset/ETHPy150Open rapp-project/rapp-platform/rapp_mysql_wrapper/src/mysql_wrapper.py/MySQLdbWrapper.updateData
4,527
def fetchData(self,req,tblName): try: res = fetchDataSrvResponse() db_username,db_password=self.getLogin() con = mdb.connect('localhost', db_username, db_password, 'RappStore'); cur = con.cursor() returncols=self.constructCommaColumns(req.req_cols) where=self.constructAndQuery(re...
IndexError
dataset/ETHPy150Open rapp-project/rapp-platform/rapp_mysql_wrapper/src/mysql_wrapper.py/MySQLdbWrapper.fetchData
4,528
def whatRappsCanRun(self,req,tblName): try: res = whatRappsCanRunSrvResponse() db_username,db_password=self.getLogin() con = mdb.connect('localhost', db_username, db_password, 'RappStore'); cur = con.cursor() query="SELECT rapp_id from tblRappsModelsVersion where model_id='"+req.model_...
IOError
dataset/ETHPy150Open rapp-project/rapp-platform/rapp_mysql_wrapper/src/mysql_wrapper.py/MySQLdbWrapper.whatRappsCanRun
4,529
def apply(self, op, im1, im2=None, mode=None): im1 = self.__fixup(im1) if im2 is None: # unary operation out = Image.new(mode or im1.mode, im1.size, None) im1.load() try: op = getattr(_imagingmath, op+"_"+im1.mode) except Attrib...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/ImageMath.py/_Operand.apply
4,530
def eval(expression, _dict={}, **kw): # build execution namespace args = ops.copy() args.update(_dict) args.update(kw) for k, v in args.items(): if hasattr(v, "im"): args[k] = _Operand(v) import __builtin__ out =__builtin__.eval(expression, args) try: return...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/site-packages/PIL/ImageMath.py/eval
4,531
def get_mod_func(callback): # Converts 'django.views.news.stories.story_detail' to # ['django.views.news.stories', 'story_detail'] try: dot = callback.rindex('.') except __HOLE__: return callback, '' return callback[:dot], callback[dot+1:]
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/get_mod_func
4,532
def __call__(self, match_obj): # match_obj.group(1) is the contents of the parenthesis. # First we need to figure out whether it's a named or unnamed group. # grouped = match_obj.group(1) m = re.search(r'^\?P<(\w+)>(.*?)$', grouped) if m: # If this was a named group... ...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/MatchChecker.__call__
4,533
def _get_callback(self): if self._callback is not None: return self._callback mod_name, func_name = get_mod_func(self._callback_str) try: self._callback = getattr(__import__(mod_name, {}, {}, ['']), func_name) except __HOLE__, e: raise ViewDoesNotExist...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/RegexURLPattern._get_callback
4,534
def reverse(self, viewname, *args, **kwargs): mod_name, func_name = get_mod_func(viewname) try: lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) except (__HOLE__, AttributeError): raise NoReverseMatch if lookup_view != self.callback: ...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/RegexURLPattern.reverse
4,535
def _get_urlconf_module(self): try: return self._urlconf_module except AttributeError: try: self._urlconf_module = __import__(self.urlconf_name, {}, {}, ['']) except __HOLE__, e: # Invalid urlconf_name, such as "foo.bar." (note trailing...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/RegexURLResolver._get_urlconf_module
4,536
def _resolve_special(self, view_type): callback = getattr(self.urlconf_module, 'handler%s' % view_type) mod_name, func_name = get_mod_func(callback) try: return getattr(__import__(mod_name, {}, {}, ['']), func_name), {} except (ImportError, __HOLE__), e: raise Vie...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/RegexURLResolver._resolve_special
4,537
def reverse(self, lookup_view, *args, **kwargs): if not callable(lookup_view): mod_name, func_name = get_mod_func(lookup_view) try: lookup_view = getattr(__import__(mod_name, {}, {}, ['']), func_name) except (ImportError, __HOLE__): raise NoRev...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/urlresolvers.py/RegexURLResolver.reverse
4,538
def attach(self, timeout, wait=True): if self.skype is not None and windll.user32.IsWindow(self.skype): return self.acquire() self.skype = None try: if not self.isAlive(): try: self.start() except __HOLE__: ...
AssertionError
dataset/ETHPy150Open Skype4Py/Skype4Py/Skype4Py/api/windows.py/SkypeAPI.attach
4,539
def _is_gzip(self, response): archive = StringIO(response.body) try: body = gzip.GzipFile(fileobj=archive).read() except __HOLE__: return respcls = responsetypes.from_args(body=body) return response.replace(body=body, cls=respcls)
IOError
dataset/ETHPy150Open wcong/ants/ants/contrib_exp/downloadermiddleware/decompression.py/DecompressionMiddleware._is_gzip
4,540
def _is_bzip2(self, response): try: body = bz2.decompress(response.body) except __HOLE__: return respcls = responsetypes.from_args(body=body) return response.replace(body=body, cls=respcls)
IOError
dataset/ETHPy150Open wcong/ants/ants/contrib_exp/downloadermiddleware/decompression.py/DecompressionMiddleware._is_bzip2
4,541
def __init__(self, locale): Console.info("Parsing CLDR files for %s..." % locale) Console.indent() splits = locale.split("_") # Store for internal usage self.__locale = locale self.__language = splits[0] self.__territory = splits[1] if len(splits) > 1 else None ...
IOError
dataset/ETHPy150Open zynga/jasy/jasy/core/Locale.py/LocaleParser.__init__
4,542
def close(self): for ct in self.containers: if ct: try: self.docker.remove_container(container=ct.get('Id')) except (errors.DockerException, errors.APIError) as e: LOG.warning('Failed to remove container %s, %s' % ...
OSError
dataset/ETHPy150Open openstack/solum/solum/worker/app_handlers/base.py/BaseHandler.close
4,543
def _gen_docker_ignore(self, path, prefix=None): # Exclude .git from the docker build context content = '{}/.git'.format(prefix) if prefix else '.git' try: with open('{}/.dockerignore'.format(path), 'w') as f: f.write(content) except __HOLE__: pass
OSError
dataset/ETHPy150Open openstack/solum/solum/worker/app_handlers/base.py/BaseHandler._gen_docker_ignore
4,544
def _docker_build(self, tag, logger, timeout, limits, path=None, dockerfile=None, fileobj=None, forcerm=True, quiet=True, nocache=False, pull=True): success = 1 try: for l in self.docker.build(path=path, dockerfile=dockerfile, ...
ValueError
dataset/ETHPy150Open openstack/solum/solum/worker/app_handlers/base.py/BaseHandler._docker_build
4,545
@utils.retry def _docker_save(self, image, output): result = 1 try: lp = self.docker.get_image(image) with open(output, 'w') as f: f.write(lp.data) result = 0 except (__HOLE__, errors.DockerException, errors.APIError) as e: LOG....
OSError
dataset/ETHPy150Open openstack/solum/solum/worker/app_handlers/base.py/BaseHandler._docker_save
4,546
@utils.retry def _docker_load(self, path): result = 1 try: with open(path, 'rb') as f: self.docker.load_image(f) result = 0 except (__HOLE__, errors.DockerException, errors.APIError) as e: LOG.error('Error in loading docker image, %s' % str...
OSError
dataset/ETHPy150Open openstack/solum/solum/worker/app_handlers/base.py/BaseHandler._docker_load
4,547
def run(self): self.prepare() self.logger.store_global('start_time', str(datetime.now())) try: while True: self._perform_one_run() except __HOLE__: pass self.logger.store_global('end_time', str(datetime.now())) try: self...
StopIteration
dataset/ETHPy150Open omangin/multimodal/multimodal/experiment.py/MultimodalExperiment.run
4,548
def _setup_macros_dict(parser): """ initiates the _macros attribute on the parser object, allowing for storage of the macros in the parser. """ # Each macro is stored in a new attribute # of the 'parser' class. That way we can access it later # in the template when processing 'use_macro' tags. ...
AttributeError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/_setup_macros_dict
4,549
@register.tag(name="macro") def do_macro(parser, token): """ the function taking the parsed tag and returning a DefineMacroNode object. """ try: bits = token.split_contents() tag_name, macro_name, arguments = bits[0], bits[1], bits[2:] except __HOLE__: raise template.Template...
IndexError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/do_macro
4,550
@register.tag(name="loadmacros") def do_loadmacros(parser, token): """ The function taking a parsed tag and returning a LoadMacrosNode object, while also loading the macros into the page. """ try: tag_name, filename = token.split_contents() except __HOLE__: raise template.Templat...
ValueError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/do_loadmacros
4,551
def render(self, context): # add all of the use_macros args into context for i, arg in enumerate(self.macro.args): try: template_variable = self.args[i] context[arg] = template_variable.resolve(context) except __HOLE__: context[arg...
IndexError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/UseMacroNode.render
4,552
def parse_macro_params(token): """ Common parsing logic for both use_macro and macro_block """ try: bits = token.split_contents() tag_name, macro_name, values = bits[0], bits[1], bits[2:] except __HOLE__: raise template.TemplateSyntaxError( "{0} tag requires at le...
IndexError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/parse_macro_params
4,553
@register.tag(name="use_macro") def do_usemacro(parser, token): """ The function taking a parsed template tag and returning a UseMacroNode. """ tag_name, macro_name, args, kwargs = parse_macro_params(token) try: macro = parser._macros[macro_name] except (AttributeError, __HOLE__): ...
KeyError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/do_usemacro
4,554
@register.tag(name="macro_block") def do_macro_block(parser, token): """ Function taking parsed template tag to a MacroBlockNode. """ tag_name, macro_name, args, kwargs = parse_macro_params(token) # could add extra validation on the macro_name tag # here, but probably don't need to since we're c...
AttributeError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/do_macro_block
4,555
@register.tag(name="macro_kwarg") def do_macro_kwarg(parser, token): """ Function taking a parsed template tag to a MacroKwargNode. """ try: tag_name, keyword = token.split_contents() except __HOLE__: raise template.TemplateSyntaxError( "{0} tag requires exactly one argum...
ValueError
dataset/ETHPy150Open nalourie/django-macros/build/lib/macros/templatetags/macros.py/do_macro_kwarg
4,556
def Init(self, params): """Initializes Config. This is a separate method as it raises an exception if there is a parse error.""" generator_flags = params.get('generator_flags', {}) config_path = generator_flags.get('config_path', None) if not config_path: return try: f = open(config_...
ValueError
dataset/ETHPy150Open pyokagan/gyp/pylib/gyp/generator/analyzer.py/Config.Init
4,557
def _WriteOutput(params, **values): """Writes the output, either to stdout or a file is specified.""" if 'error' in values: print 'Error:', values['error'] if 'status' in values: print values['status'] if 'targets' in values: values['targets'].sort() print 'Supplied targets that depend on change...
IOError
dataset/ETHPy150Open pyokagan/gyp/pylib/gyp/generator/analyzer.py/_WriteOutput
4,558
def createDestination(self, dstFile=None, import_lines=None): if dstFile is None: dstFile = self.dstFile if import_lines is None: import_lines = self.import_lines try: oldData = open(dstFile, 'r').readlines() except __HOLE__, e: if e[0] == ...
IOError
dataset/ETHPy150Open anandology/pyjamas/contrib/create_imports.py/CreateImports.createDestination
4,559
def test_open_nonexistent(self): """Test that trying to open a non-existent file results in an IOError (and not some other arbitrary exception). """ try: fits.open(self.temp('foobar.fits')) except __HOLE__ as exc: assert 'No such file or directory' in str...
IOError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/tests/test_core.py/TestFileFunctions.test_open_nonexistent
4,560
def _sort_commands(cmddict, order): def keyfn(key): try: return order.index(key[1]) except __HOLE__: # unordered items should come last return 0xff return sorted(cmddict.items(), key=keyfn)
ValueError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/commands/__init__.py/_sort_commands
4,561
def post_to_server(post_data, config, auth=None): """Send the given post_data to the pypi server. Parameters ---------- post_data: dict Usually the dict returned by build_post_data config: object A PyPIConfig instance auth: object or None HTTP authentification object. ...
HTTPError
dataset/ETHPy150Open cournape/Bento/bento/pypi/register_utils.py/post_to_server
4,562
def __init__(self, file_id_mod, settings): """ The file_id_mod should be 'A' for the first of the day, 'B' for the second and so on. """ self.settings = settings try: self.header = Header( settings['immediate_dest'], settings[...
KeyError
dataset/ETHPy150Open travishathaway/python-ach/ach/builder.py/AchFile.__init__
4,563
@property def root_domain(self): try: return self.domain_set.get( ~Q(master_domain__soa=F('soa')), soa__isnull=False ) except __HOLE__: return None
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/inventory/mozdns/soa/models.py/SOA.root_domain
4,564
def readheaders(self): """Read header lines. Read header lines up to the entirely blank line that terminates them. The (normally blank) line that ends the headers is skipped, but not included in the returned list. If a non-header line ends the headers, (which is an error), an attempt is made to ba...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/dist27/gae_override/httplib.py/HTTPMessage.readheaders
4,565
def request(self, method, url, body=None, headers=None): """Send a complete request to the server.""" self._method = method self._url = url try: # 'body' can be a file. self._body = body.read() except __HOLE__: self._body = body if headers is None: headers = [] elif hasatt...
AttributeError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/dist27/gae_override/httplib.py/HTTPConnection.request
4,566
@staticmethod def _getargspec(callable_object): assert callable(callable_object) try: # Methods and lambdas. return inspect.getargspec(callable_object) except __HOLE__: # Class instances with __call__. return inspect.getargspec(callable_object.__call__)
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/dist27/gae_override/httplib.py/HTTPConnection._getargspec
4,567
def getresponse(self, buffering=False): """Get the response from the server. App Engine Note: buffering is ignored. """ # net.proto.ProcotolBuffer relies on httplib so importing urlfetch at the # module level causes a failure on prod. That means the import needs to be # lazy. from google.ap...
KeyError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/dist27/gae_override/httplib.py/HTTPConnection.getresponse
4,568
def get_tokens_unprocessed(self, data): sql = PsqlRegexLexer(**self.options) lines = lookahead(line_re.findall(data)) # prompt-output cycle while 1: # consume the lines of the command: start with an optional prompt # and continue until the end of command is det...
StopIteration
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/pygments/lexers/sql.py/PostgresConsoleLexer.get_tokens_unprocessed
4,569
@staticmethod def action_check_host(request): hostname = extract_url_hostname(request['host']) try: is_active = Host.get(Host.hostname == hostname).is_active except __HOLE__: is_active = False return { 'result': 'active' if is_active else 'inactiv...
DoesNotExist
dataset/ETHPy150Open CacheBrowser/cachebrowser/cachebrowser/api.py/APIHandler.action_check_host
4,570
def token(self): try: tok = self.next_token() return tok except __HOLE__: pass
StopIteration
dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/core/lexer.py/EnamlLexer.token
4,571
def synthesize_indentation_tokens(self, token_stream): # A stack of indentation levels; will never pop item 0 levels = [0] depth = 0 prev_was_ws = False # In case the token stream is empty for a completely # empty file. token = None for token in token_st...
ValueError
dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/core/lexer.py/EnamlLexer.synthesize_indentation_tokens
4,572
def get_tests(app_module): try: app_path = app_module.__name__.split('.')[:-1] test_module = __import__('.'.join(app_path + [TEST_MODULE]), {}, {}, TEST_MODULE) except ImportError, e: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests...
ImportError
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/runnercompat.py/get_tests
4,573
def build_suite(app_module): "Create a complete Django test suite for the provided application module" from django.test import _doctest as doctest from django.test.testcases import OutputChecker, DocTestRunner doctestOutputChecker = OutputChecker() suite = unittest.TestSuite() # Load unit and ...
ValueError
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/runnercompat.py/build_suite
4,574
def build_test(label): """Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts) > 3:...
ValueError
dataset/ETHPy150Open Almad/django-sane-testing/djangosanetesting/runnercompat.py/build_test
4,575
def _build_project(self, filename): try: with open(filename) as fp: script = fp.read() m = self.rate_re.search(script) if m: rate = float(m.group(1)) else: rate = 1 m = self.burst_re.search(script) ...
OSError
dataset/ETHPy150Open binux/pyspider/pyspider/database/local/projectdb.py/ProjectDB._build_project
4,576
def create_test_yaml(): file_loc = FILE_LOC config = \ """ queue: - name: default rate: 5/s - name: foo rate: 10/m """ try: os.mkdir("/var/apps/test_app") os.mkdir("/var/apps/test_app/app/") except __HOLE__: pass FILE = file_io.write(file_loc, config) # AppScale must already be running with R...
OSError
dataset/ETHPy150Open AppScale/appscale/AppTaskQueue/test/functional/test_tq_startworker.py/create_test_yaml
4,577
def dictRemove(dct, value): try: del dct[value] except __HOLE__: pass
KeyError
dataset/ETHPy150Open twisted/twisted/twisted/internet/_threadedselect.py/dictRemove
4,578
def _workerInThread(self): try: while 1: fn, args = self.toThreadQueue.get() #print >>sys.stderr, "worker got", fn, args fn(*args) except __HOLE__: pass # exception indicates this thread should exit except: f = f...
SystemExit
dataset/ETHPy150Open twisted/twisted/twisted/internet/_threadedselect.py/ThreadedSelectReactor._workerInThread
4,579
def _doSelectInThread(self, timeout): """Run one iteration of the I/O monitor loop. This will run all selectables who had input or output readiness waiting for them. """ reads = self.reads writes = self.writes while 1: try: r, w, ignor...
IOError
dataset/ETHPy150Open twisted/twisted/twisted/internet/_threadedselect.py/ThreadedSelectReactor._doSelectInThread
4,580
def mainLoop(self): q = Queue() self.interleave(q.put) while self.running: try: q.get()() except __HOLE__: break
StopIteration
dataset/ETHPy150Open twisted/twisted/twisted/internet/_threadedselect.py/ThreadedSelectReactor.mainLoop
4,581
def __getitem__(self, key): if key in self._cache: return self._cache[key] try: instance = self._dict[key] except __HOLE__: ctrl = self.ctrl() candidates = [] for sectionname, section in ctrl.config.items(): if key in se...
KeyError
dataset/ETHPy150Open ployground/ploy/ploy/__init__.py/LazyInstanceDict.__getitem__
4,582
@lazy def instances(self): result = LazyInstanceDict(self) try: config = self.config except __HOLE__: return result for instance_id in config.get('instance', {}): iconfig = config['instance'][instance_id] if 'master' not in iconfig: ...
SystemExit
dataset/ETHPy150Open ployground/ploy/ploy/__init__.py/Controller.instances
4,583
def cmd_debug(self, argv, help): """Prints some debug info for this script""" parser = argparse.ArgumentParser( prog="%s debug" % self.progname, description=help, ) instances = self.instances parser.add_argument("instance", nargs=1, ...
ImportError
dataset/ETHPy150Open ployground/ploy/ploy/__init__.py/Controller.cmd_debug
4,584
@classmethod def active(cls, group=None, delta=datetime.timedelta(minutes=1)): """Get the currently active encoders. Args: group: Group to get active servers for. Defaults to all groups. delta: A time delta describing how long ago the encoder must have reg...
NotImplementedError
dataset/ETHPy150Open timvideos/streaming-system/website/tracker/models.py/Endpoint.active
4,585
def _test_extracting_missing_attributes(self, include_locations): # Verify behavior from glance objects that are missing attributes # TODO(jaypipes): Find a better way of testing this crappy # glanceclient magic object stuff. class MyFakeGlanceImage(object): d...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/image/test_glance.py/TestConversions._test_extracting_missing_attributes
4,586
def autorun(self, args, loop=True): """ The accessible method for dynamically running a screen. This method will basically parse the arguments, prepare them with the method `_parse_args` that is inherited in sub-classes, and with the property `cli_opts` that holds the formatting ...
KeyboardInterrupt
dataset/ETHPy150Open brunobraga/termsaver/termsaverlib/screen/base/__init__.py/ScreenBase.autorun
4,587
def _element_to_regex(self, element, job_directory, join_on): tag = element.tag method_name = "_%s_to_regex" % tag try: method = getattr(self, method_name) except __HOLE__: raise NameError("Unknown XML validation tag [%s]" % tag) regex = method(element, jo...
NameError
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/tools/validator.py/ExpressionValidator._element_to_regex
4,588
@staticmethod def load_feature(space, path, orig_path): if not os.path.exists(path): raise space.error(space.w_LoadError, orig_path) try: f = open_file_as_stream(path, buffering=0) try: contents = f.readall() finally: f...
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/modules/kernel.py/Kernel.load_feature
4,589
@moduledef.function("exec") def method_exec(self, space, args_w): if len(args_w) > 1 and space.respond_to(args_w[0], "to_hash"): raise space.error(space.w_NotImplementedError, "exec with environment") if len(args_w) > 1 and space.respond_to(args_w[-1], "to_hash"): raise spac...
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/modules/kernel.py/Kernel.method_exec
4,590
@moduledef.function("Float") def method_Float(self, space, w_arg): if w_arg is space.w_nil: raise space.error(space.w_TypeError, "can't convert nil into Float") elif space.is_kind_of(w_arg, space.w_float): return space.newfloat(space.float_w(w_arg)) elif space.is_kind...
ValueError
dataset/ETHPy150Open topazproject/topaz/topaz/modules/kernel.py/Kernel.method_Float
4,591
def get_file_encoding(self, file_path, preferred_encoding=None): """ Gets an eventual cached encoding for file_path. Raises a KeyError if no encoding were cached for the specified file path. :param file_path: path of the file to look up :returns: The cached encoding. ...
OSError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/cache.py/Cache.get_file_encoding
4,592
def set_file_encoding(self, path, encoding): """ Cache encoding for the specified file path. :param path: path of the file to cache :param encoding: encoding to cache """ try: map = json.loads(self._settings.value('cachedFileEncodings')) except __HOLE...
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/cache.py/Cache.set_file_encoding
4,593
def get_cursor_position(self, file_path): """ Gets the cached cursor position for file_path :param file_path: path of the file in the cache :return: Cached cursor position or (0, 0) """ try: map = json.loads(self._settings.value('cachedCursorPosition')) ...
KeyError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/cache.py/Cache.get_cursor_position
4,594
def set_cursor_position(self, path, position): """ Cache encoding for the specified file path. :param path: path of the file to cache :param position: cursor position to cache """ try: map = json.loads(self._settings.value('cachedCursorPosition')) exc...
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/cache.py/Cache.set_cursor_position
4,595
def main(self): if six.PY2: stream = codecs.getwriter('utf-8')(self.output_file) else: stream = self.output_file json_kwargs = { 'ensure_ascii': False, 'indent': self.args.indent, } if six.PY2: json_kwargs['encoding'] ...
ValueError
dataset/ETHPy150Open wireservice/csvkit/csvkit/utilities/csvjson.py/CSVJSON.main
4,596
def inet_pton(af, addr): """Convert an IP address from text representation into binary form""" print('hello') if af == socket.AF_INET: return inet_aton(addr) elif af == socket.AF_INET6: # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros. # We deal with this ...
TypeError
dataset/ETHPy150Open phaethon/scapy/scapy/pton_ntop.py/inet_pton
4,597
def inet_ntop(af, addr): """Convert an IP address from binary form into text represenation""" if af == socket.AF_INET: return inet_ntoa(addr) elif af == socket.AF_INET6: # IPv6 addresses have 128bits (16 bytes) if len(addr) != 16: raise Exception("Illegal syntax for IP ad...
TypeError
dataset/ETHPy150Open phaethon/scapy/scapy/pton_ntop.py/inet_ntop
4,598
def main(): if len(sys.argv) > 1: stream_name = sys.argv[1] else: stream_name = "main" try: player = subprocess.Popen(["mplayer", streams[stream_name]], stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) except __HOLE__: print("Usage: {} [station]".fo...
KeyError
dataset/ETHPy150Open gkbrk/radioreddit-cli/radioreddit-cli.py/main
4,599
@property def next_sibling(self): """ The node immediately following the invocant in their parent's children list. If the invocant does not have a next sibling, it is None """ if self.parent is None: return None # Can't use index(); we need to test by ide...
IndexError
dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/lib2to3/pytree.py/Base.next_sibling