Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,300
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except __HOLE__: err = sys.exc_info()[1] if err.errno in (errno.EPERM, e...
OSError
dataset/ETHPy150Open packages/psutil/psutil/_common.py/isfile_strict
8,301
def get_provider(self, cloud_prop): """ Return a suitable cloud Provider object for the given cloud properties input and specifically the 'provider' type attribute. """ provider_id = cloud_prop.get("provider") if not provider_id: raise errors.CloudError("cloud...
KeyError
dataset/ETHPy150Open ohmu/poni/poni/cloud.py/Sky.get_provider
8,302
def unquote_string(string): """Unquote a string with JavaScript rules. The string has to start with string delimiters (``'`` or ``"``.) :return: a string """ assert string and string[0] == string[-1] and string[0] in '"\'', \ 'string provided is not properly delimited' string = line_jo...
ValueError
dataset/ETHPy150Open mbr/Babel-CLDR/babel/messages/jslexer.py/unquote_string
8,303
@classmethod def build_soft_chain(cls, files): """ Build a list of nodes "soft" linked. This means that each has an id (an integer value) and possibly a backref which is also an integer. Not a truly "linked" list Returns an array of SimpleNodes :rtype : list ...
OSError
dataset/ETHPy150Open appnexus/schema-tool/schematool/util/chain.py/ChainUtil.build_soft_chain
8,304
def visit_uiexample_html(self, node): global should_export_flexx_deps # Fix for rtd if not hasattr(node, 'code'): return # Get code code = ori_code = node.code.strip() + '\n' ori_code = '\n'.join([' '*8 + x for x in ori_code.splitlines()]) # for reporting # Is this a ...
ImportError
dataset/ETHPy150Open zoofIO/flexx/docs/scripts/uiexample.py/visit_uiexample_html
8,305
def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0) self.ftest('cos(0)', math.cos(0), 1) self.ftest('cos(pi/2)', math.cos(math.pi/2), 0) self.ftest('cos(pi)', math.cos(math.pi), -1) try: self.assertTrue(m...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.testCos
8,306
@requires_IEEE_754 @unittest.skipIf(HAVE_DOUBLE_ROUNDING, "fsum is not exact on machines with double rounding") def testFsum(self): # math.fsum relies on exact rounding for correct operation. # There's a known problem with IA32 floating-point that causes # inexac...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.testFsum
8,307
def testSin(self): self.assertRaises(TypeError, math.sin) self.ftest('sin(0)', math.sin(0), 0) self.ftest('sin(pi/2)', math.sin(math.pi/2), 1) self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1) try: self.assertTrue(math.isnan(math.sin(INF))) self.assertTru...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.testSin
8,308
def test_exceptions(self): try: x = math.exp(-1000000000) except: # mathmodule.c is failing to weed out underflows from libm, or # we've got an fp format with huge dynamic range self.fail("underflowing exp() should not have raised "...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.test_exceptions
8,309
@unittest.skip("testfile not supported") @requires_IEEE_754 def test_testfile(self): for id, fn, ar, ai, er, ei, flags in parse_testfile(test_file): # Skip if either the input or result is complex, or if # flags is nonempty if ai != 0. or ei != 0. or flags: ...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.test_testfile
8,310
@unittest.skip("mtestfile not supported") @requires_IEEE_754 def test_mtestfile(self): fail_fmt = "{}:{}({!r}): expected {!r}, got {!r}" failures = [] for id, fn, arg, expected, flags in parse_mtestfile(math_testcases): func = getattr(math, fn) if 'invalid' in f...
ValueError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_math.py/MathTests.test_mtestfile
8,311
def try_ipv6_socket(): """Determine if system really supports IPv6""" if not socket.has_ipv6: return False try: socket.socket(socket.AF_INET6).close() return True except __HOLE__ as error: logger.debug( 'Platform supports IPv6, but socket creation failed, ' ...
IOError
dataset/ETHPy150Open mopidy/mopidy/mopidy/internal/network.py/try_ipv6_socket
8,312
def struct(typename, field_names, verbose=False): """Returns a new class with named fields. >>> Point = struct('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p...
ValueError
dataset/ETHPy150Open probcomp/bayeslite/external/lemonade/dist/lemonade/ccruft.py/struct
8,313
def search_fields_to_dict(fields): """ In ``SearchableQuerySet`` and ``SearchableManager``, search fields can either be a sequence, or a dict of fields mapped to weights. This function converts sequences to a dict mapped to even weights, so that we're consistently dealing with a dict of fields mappe...
TypeError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/managers.py/search_fields_to_dict
8,314
def search(self, *args, **kwargs): """ Proxy to queryset's search method for the manager's model and any models that subclass from this manager's model if the model is abstract. """ if not settings.SEARCH_MODEL_CHOICES: # No choices defined - build a list of l...
AttributeError
dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/core/managers.py/SearchableManager.search
8,315
def get_default(key): """Get a default value from the current app's configuration. Currently returns None when no app is in context: >>> get_default('NO_APP_IS_LOADED') is None True >>> """ try: return current_app.config.get(key, None) except (__HOLE__, RuntimeError): # ...
AttributeError
dataset/ETHPy150Open willowtreeapps/tango-core/tango/filters.py/get_default
8,316
def get(self, key, default=Empty, creator=Empty, expire=None): """ :para default: if default is callable then invoke it, save it and return it """ try: return self.storage.get(key) except __HOLE__ as e: if creator is not Empty: if callable(...
KeyError
dataset/ETHPy150Open limodou/uliweb/uliweb/lib/weto/cache.py/Cache.get
8,317
def cache(self, k=None, expire=None): def _f(func): def f(*args, **kwargs): if not k: r = repr(args) + repr(sorted(kwargs.items())) key = func.__module__ + '.' + func.__name__ + r else: key = k ...
KeyError
dataset/ETHPy150Open limodou/uliweb/uliweb/lib/weto/cache.py/Cache.cache
8,318
def get_constr_generator(args): feats = get_feat_cls(args)(args.actionfile) try: feats.set_landmark_file(args.landmarkfile) except __HOLE__: pass marg = BatchCPMargin(feats) constr_gen = ConstraintGenerator(feats, marg, args.actionfile) return constr_gen
AttributeError
dataset/ETHPy150Open rll/lfd/lfd/mmqe/build.py/get_constr_generator
8,319
def optimize_model(args): print 'Found model: {}'.format(args.modelfile) actions = get_actions(args) feat_cls = get_feat_cls(args) mm_model = get_model_cls(args).read(args.modelfile, actions, feat_cls.get_size(len(actions))) try: mm_model.scale_objective(args.C, args.D) except __HOLE__: ...
TypeError
dataset/ETHPy150Open rll/lfd/lfd/mmqe/build.py/optimize_model
8,320
def id_map_type(val): maps = val.split(',') id_maps = [] for m in maps: map_vals = m.split(':') if len(map_vals) != 3: msg = ('Invalid id map %s, correct syntax is ' 'guest-id:host-id:count.') raise argparse.ArgumentTypeError(msg % val) tr...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cmd/idmapshift.py/id_map_type
8,321
def get_hash(path, form='sha1', chunk_size=4096): """Generate a hash digest string for a file.""" try: hash_type = getattr(hashlib, form) except __HOLE__: raise ValueError('Invalid hash type: {0}'.format(form)) with open(path, 'rb') as ifile: hash_obj = hash_type() # read...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/client/ssh/ssh_py_shim.py/get_hash
8,322
def handle(self, *args, **options): datapath = options['datapath'][0] with open(datapath, 'rU') as csvfile: filereader = csv.reader(csvfile, delimiter=',') for row in filereader: acr_id = row[0] name = row[1] order = row[2] ...
ObjectDoesNotExist
dataset/ETHPy150Open upconsulting/IsisCB/isiscb/isisdata/management/commands/missing_acr_data_cmd.py/Command.handle
8,323
@signalcommand def handle(self, *args, **options): if args: appname, = args style = color_style() if getattr(settings, 'ADMIN_FOR', None): settings_modules = [__import__(m, {}, {}, ['']) for m in settings.ADMIN_FOR] else: settings_modules = [sett...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/django-extensions-1.5.0/django_extensions/management/commands/show_templatetags.py/Command.handle
8,324
def dump(typ, val, tb, include_local_traceback): """Dumps the given exceptions info, as returned by ``sys.exc_info()`` :param typ: the exception's type (class) :param val: the exceptions' value (instance) :param tb: the exception's traceback (a ``traceback`` object) :param include_local_traceba...
AttributeError
dataset/ETHPy150Open tomerfiliba/rpyc/rpyc/core/vinegar.py/dump
8,325
def collect(self): for host in self.config['hosts']: matches = re.search( '^([^:]*):([^@]*)@([^:]*):?([^/]*)/([^/]*)/?(.*)$', host) if not matches: continue params = {} params['host'] = matches.group(3) try: ...
ValueError
dataset/ETHPy150Open python-diamond/Diamond/src/collectors/mysqlstat/mysql55.py/MySQLPerfCollector.collect
8,326
@user_view def emailchange(request, user, token, hash): try: _uid, newemail = EmailResetCode.parse(token, hash) except __HOLE__: return http.HttpResponse(status=400) if _uid != user.id: # I'm calling this a warning because invalid hashes up to this point # could be any numbe...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/users/views.py/emailchange
8,327
@never_cache @anonymous_csrf def password_reset_confirm(request, uidb64=None, token=None): """ Pulled from django contrib so that we can add user into the form so then we can show relevant messages about the user. """ assert uidb64 is not None and token is not None user = None try: u...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/users/views.py/password_reset_confirm
8,328
@never_cache def unsubscribe(request, hash=None, token=None, perm_setting=None): """ Pulled from django contrib so that we can add user into the form so then we can show relevant messages about the user. """ assert hash is not None and token is not None user = None try: email = Unsu...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/users/views.py/unsubscribe
8,329
def monitor_query_queue(self, job_id, job_metadata, query_object=None, callback_function=None): query_object = query_object or self started_checking = datetime.datetime.utcnow() not...
AttributeError
dataset/ETHPy150Open m-lab/telescope/telescope/external.py/BigQueryCall.monitor_query_queue
8,330
def set_charset(self, charset): """Set the charset of the payload to a given character set. charset can be a Charset instance, a string naming a character set, or None. If it is a string it will be converted to a Charset instance. If charset is None, the charset parameter will be ...
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/email/message.py/Message.set_charset
8,331
def _get_params_preserve(self, failobj, header): # Like get_params() but preserves the quoting of values. BAW: # should this be part of the public interface? missing = object() value = self.get(header, missing) if value is missing: return failobj param...
ValueError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/email/message.py/Message._get_params_preserve
8,332
def _compile(self, name, tmplPath): ## @@ consider adding an ImportError raiser here code = str(Compiler(file=tmplPath, moduleName=name, mainClassName=name)) if _cacheDir: __file__ = os.path.join(_cacheDir[0], conv...
OSError
dataset/ETHPy150Open skyostil/tracy/src/generator/Cheetah/ImportHooks.py/CheetahDirOwner._compile
8,333
@property def position(self): """ Gets the marker position (line number) :type: int """ try: return self.block.blockNumber() except __HOLE__: return self._position # not added yet
AttributeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/panels/marker.py/Marker.position
8,334
def get_owned(self, user_id): try: user = CouchUser.get_by_user_id(user_id, self.domain) except KeyError: user = None try: owner_ids = user.get_owner_ids() except __HOLE__: owner_ids = [user_id] closed = { CASE_STATUS_O...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/cloudcare/api.py/CaseAPIHelper.get_owned
8,335
def read_csv(user_id, records_path, antennas_path=None, attributes_path=None, network=False, describe=True, warnings=True, errors=False): """ Load user records from a CSV file. Parameters ---------- user_id : str ID of the user (filename) records_path : str Path of the directo...
IOError
dataset/ETHPy150Open yvesalexandre/bandicoot/bandicoot/io.py/read_csv
8,336
def read_orange(user_id, records_path, antennas_path=None, attributes_path=None, network=False, describe=True, warnings=True, errors=False): """ Load user records from a CSV file in *orange* format: ``call_record_type;basic_service;user_msisdn;call_partner_identity;datetime;call_duration;longitude;latitude...
IOError
dataset/ETHPy150Open yvesalexandre/bandicoot/bandicoot/io.py/read_orange
8,337
def print_iterate(dataset, gql, namespace=None, msg=''): it = iterate(dataset, gql, namespace) loaded = 0 try: while True: loaded += 1 if loaded % 1000 == 0: print >> sys.stderr, 'loaded', msg, loaded string = json.dumps(it.next()) print string except __HOLE__: pass print >> sys.stderr, 'Done',...
StopIteration
dataset/ETHPy150Open murer/dsopz/dsopz/reader.py/print_iterate
8,338
@staticmethod def _convert_legacy_ipv6_netmask(netmask): """Handle netmask_v6 possibilities from the database. Historically, this was stored as just an integral CIDR prefix, but in the future it should be stored as an actual netmask. Be tolerant of either here. """ t...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/objects/network.py/Network._convert_legacy_ipv6_netmask
8,339
def is_authenticated(self, request, **kwargs): """ Copypasted from tastypie, modified to avoid issues with app-loading and custom user model. """ User = get_user_model() username_field = User.USERNAME_FIELD try: username, api_key = self.extract_creden...
ValueError
dataset/ETHPy150Open python/pythondotorg/pydotorg/resources.py/ApiKeyOrGuestAuthentication.is_authenticated
8,340
@slow_test @testing.requires_testing_data def test_volume_stc(): """Test volume STCs """ tempdir = _TempDir() N = 100 data = np.arange(N)[:, np.newaxis] datas = [data, data, np.arange(2)[:, np.newaxis]] vertno = np.arange(N) vertnos = [vertno, vertno[:, np.newaxis], np.arange(2)[:, np.ne...
ImportError
dataset/ETHPy150Open mne-tools/mne-python/mne/tests/test_source_estimate.py/test_volume_stc
8,341
def load_plugins(self, directory): plugins = {} sys.path.insert(0, directory) try: to_load = [p.strip() for p in self.config['porkchop']['plugins'].split(',')] except: to_load = [] for infile in glob.glob(os.path.join(directory, '*.py')): mod...
ImportError
dataset/ETHPy150Open disqus/porkchop/porkchop/plugin.py/PorkchopPluginHandler.load_plugins
8,342
def set_exec_by_id(self, exec_id): if not self.log: return False try: workflow_execs = [e for e in self.log if e.id == int(str(exec_id))] except __HOLE__: return False if len(workflow_execs): self.notify_app...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/gui/collection/vis_log.py/QLogView.set_exec_by_id
8,343
def _from_json(self, datastring): try: return jsonutils.loads(datastring) except __HOLE__: msg = _("cannot understand JSON") raise exception.MalformedRequestBody(reason=msg)
ValueError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/JSONDeserializer._from_json
8,344
def get_serializer(self, content_type, default_serializers=None): """Returns the serializer for the wrapped object. Returns the serializer for the wrapped object subject to the indicated content type. If no serializer matching the content type is attached, an appropriate serializer dra...
KeyError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/ResponseObject.get_serializer
8,345
def action_peek_json(body): """Determine action to invoke.""" try: decoded = jsonutils.loads(body) except __HOLE__: msg = _("cannot understand JSON") raise exception.MalformedRequestBody(reason=msg) # Make sure there's exactly one key... if len(decoded) != 1: msg = ...
ValueError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/action_peek_json
8,346
def get_action_args(self, request_environment): """Parse dictionary created by routes library.""" # NOTE(Vek): Check for get_action_args() override in the # controller if hasattr(self.controller, 'get_action_args'): return self.controller.get_action_args(request_environment)...
KeyError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Resource.get_action_args
8,347
def deserialize(self, meth, content_type, body): meth_deserializers = getattr(meth, 'wsgi_deserializers', {}) try: mtype = _MEDIA_TYPE_MAP.get(content_type, content_type) if mtype in meth_deserializers: deserializer = meth_deserializers[mtype] else: ...
KeyError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Resource.deserialize
8,348
def post_process_extensions(self, extensions, resp_obj, request, action_args): for ext in extensions: response = None if inspect.isgenerator(ext): # If it's a generator, run the second half of # processing tr...
StopIteration
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Resource.post_process_extensions
8,349
def _process_stack(self, request, action, action_args, content_type, body, accept): """Implement the processing stack.""" # Get the implementing method try: meth, extensions = self.get_method(request, action, cont...
TypeError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Resource._process_stack
8,350
def _get_method(self, request, action, content_type, body): """Look up the action-specific method and its extensions.""" # Look up the method try: if not self.controller: meth = getattr(self, action) else: meth = getattr(self.controller, a...
AttributeError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Resource._get_method
8,351
@staticmethod def is_valid_body(body, entity_name): if not (body and entity_name in body): return False def is_dict(d): try: d.get(None) return True except __HOLE__: return False if not is_dict(body[entity_...
AttributeError
dataset/ETHPy150Open openstack/rack/rack/api/wsgi.py/Controller.is_valid_body
8,352
def decode_json_body(): """ Decode ``bottle.request.body`` to JSON. Returns: obj: Structure decoded by ``json.loads()``. Raises: HTTPError: 400 in case the data was malformed. """ raw_data = request.body.read() try: return json.loads(raw_data) except __HOLE__ a...
ValueError
dataset/ETHPy150Open Bystroushaak/bottle-rest/src/bottle_rest/bottle_rest.py/decode_json_body
8,353
def handle_type_error(fn): """ Convert ``TypeError`` to ``bottle.HTTPError`` with ``400`` code and message about wrong parameters. Raises: HTTPError: 400 in case too many/too little function parameters were \ given. """ @wraps(fn) def handle_type_error_wrapper(*ar...
TypeError
dataset/ETHPy150Open Bystroushaak/bottle-rest/src/bottle_rest/bottle_rest.py/handle_type_error
8,354
@staticmethod def new_by_type(build_name, *args, **kwargs): """Find BuildRequest with the given name.""" # Compatibility if build_name in (PROD_WITHOUT_KOJI_BUILD_TYPE, PROD_WITH_SECRET_BUILD_TYPE): build_name = PROD_BUILD_TYPE try: ...
KeyError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/BuildRequest.new_by_type
8,355
@property def template(self): if self._template is None: path = os.path.join(self.build_json_store, "%s.json" % self.key) logger.debug("loading template from path %s", path) try: with open(path, "r") as fp: self._template = json.load(fp...
OSError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/BuildRequest.template
8,356
def render_store_metadata_in_osv3(self, use_auth=None): try: self.dj.dock_json_set_arg('exit_plugins', "store_metadata_in_osv3", "url", self.spec.builder_openshift_url.value) if use_auth is not None: ...
RuntimeError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/CommonBuild.render_store_metadata_in_osv3
8,357
def set_params(self, **kwargs): """ set parameters according to specification these parameters are accepted: :param pulp_secret: str, resource name of pulp secret :param pdc_secret: str, resource name of pdc secret :param koji_target: str, koji tag with packages used to...
KeyError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/ProductionBuild.set_params
8,358
def adjust_for_registry_api_versions(self): """ Enable/disable plugins depending on supported registry API versions """ versions = self.spec.registry_api_versions.value try: push_conf = self.dj.dock_json_get_plugin_conf('postbuild_plugins', ...
IndexError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/ProductionBuild.adjust_for_registry_api_versions
8,359
def render(self, validate=True): if validate: self.spec.validate() super(SimpleBuild, self).render() try: self.dj.dock_json_set_arg('exit_plugins', "store_metadata_in_osv3", "url", self.spec.builder_openshift_url.value) except...
RuntimeError
dataset/ETHPy150Open projectatomic/osbs-client/osbs/build/build_request.py/SimpleBuild.render
8,360
def __getattr__(self, attr): try: return self[self.attrs.index(attr)] except __HOLE__: raise AttributeError
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pwd.py/struct_passwd.__getattr__
8,361
def iter_errback(iterable, errback, *a, **kw): """Wraps an iterable calling an errback if an error is caught while iterating it. """ it = iter(iterable) while 1: try: yield next(it) except __HOLE__: break except: errback(failure.Failure(), ...
StopIteration
dataset/ETHPy150Open wcong/ants/ants/utils/defer.py/iter_errback
8,362
def dict_to_table(ava, lev=0, width=1): txt = ['<table border=%s bordercolor="black">\n' % width] for prop, valarr in ava.items(): txt.append("<tr>\n") if isinstance(valarr, basestring): txt.append("<th>%s</th>\n" % str(prop)) try: txt.append("<td>%s</td>\...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/example/sp-repoze/sp.py/dict_to_table
8,363
def slo(environ, start_response, user): # so here I might get either a LogoutResponse or a LogoutRequest client = environ['repoze.who.plugins']["saml2auth"] sc = client.saml_client if "QUERY_STRING" in environ: query = parse_qs(environ["QUERY_STRING"]) logger.info("query: %s" % query) ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/example/sp-repoze/sp.py/slo
8,364
def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above and store the regular expression captures in the WSGI environment as `myapp.url_args` so that the functions from above can access the url placeholders. If nothing ma...
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/example/sp-repoze/sp.py/application
8,365
def main(self, options, args): """ Main routine for running the reference viewer. `options` is a OptionParser object that has been populated with values from parsing the command line. It should at least include the options from add_default_options() `args` is a list of...
KeyboardInterrupt
dataset/ETHPy150Open ejeschke/ginga/ginga/main.py/ReferenceViewer.main
8,366
def main_search(): from optparse import OptionParser parser = OptionParser( usage="%prog [options] [<bandit> <bandit_algo>]") parser.add_option('--load', default='', dest="load", metavar='FILE', help="unpickle experiment from here on startup") ...
IOError
dataset/ETHPy150Open hyperopt/hyperopt/hyperopt/main.py/main_search
8,367
def main(cmd, fn_pos = 1): """ Entry point for bin/* scripts XXX """ logging.basicConfig( stream=sys.stderr, level=logging.INFO) try: runner = dict( search='main_search', dryrun='main_dryrun', plot_history='main_plot...
KeyError
dataset/ETHPy150Open hyperopt/hyperopt/hyperopt/main.py/main
8,368
def execute(*cmd, **kwargs): """Helper method to shell out and execute a command through subprocess. Allows optional retry. :param cmd: Passed to subprocess.Popen. :type cmd: string :param process_input: Send to opened process. :type process_input: string :par...
OSError
dataset/ETHPy150Open openstack/rack/rack/openstack/common/processutils.py/execute
8,369
def getBodyJson(): """ For requests that are expected to contain a JSON body, this returns the parsed value, or raises a :class:`girder.api.rest.RestException` for invalid JSON. """ try: return json.loads(cherrypy.request.body.read().decode('utf8')) except __HOLE__: raise Res...
ValueError
dataset/ETHPy150Open girder/girder/girder/api/rest.py/getBodyJson
8,370
def find_commands(management_dir): """ Given a path to a management directory, returns a list of all the command names that are available. Returns an empty list if no commands are defined. """ command_dir = os.path.join(management_dir, 'commands') try: return [f[:-3] for f in os.lis...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/find_commands
8,371
def find_management_module(app_name): """ Determines the path to the management module for the given app_name, without actually importing the application or the management module. Raises ImportError if the management module cannot be found for any reason. """ parts = app_name.split('.') par...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/find_management_module
8,372
def get_commands(): """ Returns a dictionary mapping command names to their callback applications. This works by looking for a management.commands package in django.core, and in each installed application -- if a commands package exists, all commands in that package are registered. Core comman...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/get_commands
8,373
def call_command(name, *args, **options): """ Calls the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. Some examples: call_command('syncdb') call_command('shell', plain=True) call_command('sqlall', 'm...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/call_command
8,374
def fetch_command(self, subcommand): """ Tries to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin.py" or "manage.py") if it can't be found. """ try: app_name = get_commands()[subco...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/ManagementUtility.fetch_command
8,375
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/ManagementUtility.autocomplete
8,376
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands t...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/core/management/__init__.py/ManagementUtility.execute
8,377
def remove_rule(self, chain, rule, wrap=True, top=False): """Remove a rule from a chain. Note: The rule must be exactly identical to the one that was added. You cannot switch arguments around like you can with the iptables CLI tool. """ try: self.rules.remov...
ValueError
dataset/ETHPy150Open openstack/nova/nova/network/linux_net.py/IptablesTable.remove_rule
8,378
def _find_table(self, lines, table_name): if len(lines) < 3: # length only <2 when fake iptables return (0, 0) try: start = lines.index('*%s' % table_name) - 1 except __HOLE__: # Couldn't find table_name return (0, 0) end = line...
ValueError
dataset/ETHPy150Open openstack/nova/nova/network/linux_net.py/IptablesManager._find_table
8,379
@utils.synchronized('lock_gateway', external=True) def initialize_gateway_device(dev, network_ref): if not network_ref: return _enable_ipv4_forwarding() # NOTE(vish): The ip for dnsmasq has to be the first address on the # bridge for it to respond to requests properly try: ...
AttributeError
dataset/ETHPy150Open openstack/nova/nova/network/linux_net.py/initialize_gateway_device
8,380
def _dnsmasq_pid_for(dev): """Returns the pid for prior dnsmasq instance for a bridge/device. Returns None if no pid file exists. If machine has rebooted pid might be incorrect (caller should check). """ pid_file = _dhcp_file(dev, 'pid') if os.path.exists(pid_file): try: ...
IOError
dataset/ETHPy150Open openstack/nova/nova/network/linux_net.py/_dnsmasq_pid_for
8,381
def update_portSpec(old_obj, translate_dict): global id_scope sigstring = old_obj.db_sigstring sigs = [] if sigstring and sigstring != '()': for sig in sigstring[1:-1].split(','): sigs.append(sig.split(':', 2)) # not great to use eval... defaults = literal_eval(old_obj.db_def...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/db/versions/v1_0_3/translate/v1_0_2.py/update_portSpec
8,382
def _getdb(scheme, host, params): try: module = import_module('stdnet.backends.%sb' % scheme) except __HOLE__: raise NotImplementedError return getattr(module, 'BackendDataServer')(scheme, host, **params)
ImportError
dataset/ETHPy150Open lsbardel/python-stdnet/stdnet/backends/__init__.py/_getdb
8,383
def execute_generator(gen): exc_info = None result = None while True: try: if exc_info: result = failure.throw(*exc_info) exc_info = None else: result = gen.send(result) except __HOLE__: break ...
StopIteration
dataset/ETHPy150Open lsbardel/python-stdnet/stdnet/backends/__init__.py/execute_generator
8,384
def dpll_satisfiable(expr, all_models=False): """ Check satisfiability of a propositional sentence. It returns a model rather than True when it succeeds. Returns a generator of all models if all_models is True. Examples ======== >>> from sympy.abc import A, B >>> from sympy.logic.algor...
StopIteration
dataset/ETHPy150Open sympy/sympy/sympy/logic/algorithms/dpll2.py/dpll_satisfiable
8,385
def _all_models(models): satisfiable = False try: while True: yield next(models) satisfiable = True except __HOLE__: if not satisfiable: yield False
StopIteration
dataset/ETHPy150Open sympy/sympy/sympy/logic/algorithms/dpll2.py/_all_models
8,386
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except __HOLE__ as e: self._logger.warn('Event callback failed: {}'....
OSError
dataset/ETHPy150Open harvimt/quamash/quamash/_windows.py/_ProactorEventLoop._process_events
8,387
def _poll(self, timeout=None): """Override in order to handle events in a threadsafe manner.""" if timeout is None: ms = UINT32_MAX # wait for eternity elif timeout < 0: raise ValueError("negative timeout") else: # GetQueuedCompletionStatus() has a resolution of 1 millisecond, # round away from zer...
KeyError
dataset/ETHPy150Open harvimt/quamash/quamash/_windows.py/_IocpProactor._poll
8,388
def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): if what == 'module': # Strip top title title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', re.I|re.S) lines[:] = title_re.sub('', "\n".join(li...
ValueError
dataset/ETHPy150Open cigroup-ol/windml/doc/sphinxext/numpy_ext_old/numpydoc.py/mangle_docstrings
8,389
def get_local_ip(self): """ Gets the local IP of the current node. Returns: The local IP """ try: local_ip = self.__local_ip except __HOLE__: local_ip = None if local_ip is None: local_ip = os.environ.get("LOCAL_DB_IP") if local_ip is None: raise E...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppDB/dbinterface_batch.py/AppDBInterface.get_local_ip
8,390
def get_master_ip(self): """ Gets the master database IP of the current AppScale deployment. Returns: The master DB IP """ try: master_ip = self.__master_ip except __HOLE__: master_ip = None if master_ip is None: master_ip = os.environ.get("MASTER_IP") if m...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppDB/dbinterface_batch.py/AppDBInterface.get_master_ip
8,391
def main(argv): if len(argv) < 2: print "Usage: %s com.apple.LaunchServices.QuarantineEvents" % __program__ sys.exit(1) encoding = locale.getpreferredencoding() if encoding.upper() != "UTF-8": print "%s requires an UTF-8 capable console/terminal" % __program__ sys.exit(1) files_to_process = [...
ValueError
dataset/ETHPy150Open google/grr/grr/parsers/osx_quarantine.py/main
8,392
def test_missing_tnull(self): """Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/197""" c = fits.Column('F1', 'A3', null='---', array=np.array(['1.0', '2.0', '---', '3.0']), ascii=True) table = fits.TableHDU.from_columns([c]) ...
ValueError
dataset/ETHPy150Open spacetelescope/PyFITS/pyfits/tests/test_table.py/TestTableFunctions.test_missing_tnull
8,393
def _apply_inplace(self, x, **kwargs): r""" Applies this transform to a :map:`Transformable` ``x`` destructively. Any ``kwargs`` will be passed to the specific transform :meth:`_apply` method. Note that this is an inplace operation that should be used sparingly, by inte...
AttributeError
dataset/ETHPy150Open menpo/menpo/menpo/transform/base/__init__.py/Transform._apply_inplace
8,394
def apply(self, x, batch_size=None, **kwargs): r""" Applies this transform to ``x``. If ``x`` is :map:`Transformable`, ``x`` will be handed this transform object to transform itself non-destructively (a transformed copy of the object will be returned). If not, ``x`` is ...
AttributeError
dataset/ETHPy150Open menpo/menpo/menpo/transform/base/__init__.py/Transform.apply
8,395
def do_GET(self): print "Processing %s" % self.path if "/success" in self.path: print "Stopping embedded HTTP server" self.send_response(200) self.end_headers() try: self.wfile.write(open("login_success.html").read()) except __H...
IOError
dataset/ETHPy150Open PhysicalGraph/SmartThings-Alfred/alfredworkflow/http_server.py/StoppableHttpRequestHandler.do_GET
8,396
def listdir(path): """List directory contents, using cache.""" try: cached_mtime, list = cache[path] del cache[path] except __HOLE__: cached_mtime, list = -1, [] mtime = os.stat(path).st_mtime if mtime != cached_mtime: list = os.listdir(path) list.so...
KeyError
dataset/ETHPy150Open Southpaw-TACTIC/TACTIC/src/context/client/tactic-api-python-4.0.api04/Lib/dircache.py/listdir
8,397
def _attr_get_(obj, attr): '''Returns an attribute's value, or None (no error) if undefined. Analagous to .get() for dictionaries. Useful when checking for value of options that may not have been defined on a given method.''' try: return getattr(obj, attr) except __HOLE__: ...
AttributeError
dataset/ETHPy150Open jookies/jasmin/jasmin/protocols/cli/options.py/_attr_get_
8,398
def test_access_zipped_assets_integration(): test_executable = dedent(''' import os from _pex.util import DistributionHelper temp_dir = DistributionHelper.access_zipped_assets('my_package', 'submodule') with open(os.path.join(temp_dir, 'mod.py'), 'r') as fp: for line in fp: p...
ValueError
dataset/ETHPy150Open pantsbuild/pex/tests/test_util.py/test_access_zipped_assets_integration
8,399
def _reload_config_data(self): """Reload the data from config file into ``self._list`` and ``self._set``. Note: When changing the managed list using add() and remove() from command line, the DataWatcher's greenlet does not work, you need to call this explicitly to update the list so as ...
IOError
dataset/ETHPy150Open pinterest/kingpin/kingpin/manageddata/managed_datastructures.py/ManagedList._reload_config_data