Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
7,800
def get_from_dictionary(self, dictionary, key): """Returns a value from the given `dictionary` based on the given `key`. If the given `key` cannot be found from the `dictionary`, this keyword fails. The given dictionary is never altered by this keyword. Example: | ${va...
KeyError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/Collections.py/_Dictionary.get_from_dictionary
7,801
def _yield_dict_diffs(self, keys, dict1, dict2): for key in keys: try: assert_equals(dict1[key], dict2[key], msg='Key %s' % (key,)) except __HOLE__, err: yield unic(err)
AssertionError
dataset/ETHPy150Open shellderp/sublime-robot-plugin/lib/robot/libraries/Collections.py/_Dictionary._yield_dict_diffs
7,802
def get_output(self, variation): # We import this here, so App Engine Helper users don't get import # errors. from subprocess import Popen, PIPE for input in self.get_input(variation): args = ['uglifyjs'] try: args = args + settings.UGLIFIER_OPTION...
AttributeError
dataset/ETHPy150Open adieu/django-mediagenerator/mediagenerator/filters/uglifier.py/Uglifier.get_output
7,803
def _auto_fn(name): """default dialect importer. plugs into the :class:`.PluginLoader` as a first-hit system. """ if "." in name: dialect, driver = name.split(".") else: dialect = name driver = "base" try: module = __import__('sqlalchemy.dialects.%s' % (dial...
ImportError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/dialects/__init__.py/_auto_fn
7,804
@login_required def inspect(request, id=None, tube_prefix='', tube=''): if request.method == 'POST': id = request.POST['id'] try: id = int(id) except (__HOLE__, TypeError): id = None try: client = Client(request) except ConnectionError: return render_una...
ValueError
dataset/ETHPy150Open andreisavu/django-jack/jack/beanstalk/views.py/inspect
7,805
def _redirect_to_referer_or(request, dest): referer = request.META.get('HTTP_REFERER', None) if referer is None: return redirect(dest) try: redirect_to = urlsplit(referer, 'http', False)[2] except __HOLE__: redirect_to = dest return redirect(redirect_to)
IndexError
dataset/ETHPy150Open andreisavu/django-jack/jack/beanstalk/views.py/_redirect_to_referer_or
7,806
def test_create_raises_exception_with_bad_keys(self): try: Subscription.create({"bad_key": "value"}) self.assertTrue(False) except __HOLE__ as e: self.assertEquals("'Invalid keys: bad_key'", str(e))
KeyError
dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_subscription.py/TestSubscription.test_create_raises_exception_with_bad_keys
7,807
def test_update_raises_exception_with_bad_keys(self): try: Subscription.update("id", {"bad_key": "value"}) self.assertTrue(False) except __HOLE__ as e: self.assertEquals("'Invalid keys: bad_key'", str(e))
KeyError
dataset/ETHPy150Open braintree/braintree_python/tests/unit/test_subscription.py/TestSubscription.test_update_raises_exception_with_bad_keys
7,808
def test_make_json_error_response(self): response = self.provider._make_json_error_response('some_error') self.assertEquals(400, response.status_code) try: response_json = response.json() except __HOLE__: response_json = response.json self.assertEquals({'...
TypeError
dataset/ETHPy150Open NateFerrero/oauth2lib/oauth2lib/tests/test_provider.py/AuthorizationProviderTest.test_make_json_error_response
7,809
def IsPythonFile(filename): """Return True if filename is a Python file.""" if os.path.splitext(filename)[1] == '.py': return True try: with open(filename, 'rb') as fd: encoding = tokenize.detect_encoding(fd.readline)[0] # Check for correctness of encoding. with py3compat.open_with_encodin...
IOError
dataset/ETHPy150Open google/yapf/yapf/yapflib/file_resources.py/IsPythonFile
7,810
def read_pid(pidfile, logger): """Returns the pid in `pidfile` or None if the file doesn't exist.""" _using_pidfile(pidfile, logger) try: return int(readfile(pidfile)) except __HOLE__ as e: if e.errno == errno.ENOENT: logger.info("Daemon not running (no lockfile)") ...
IOError
dataset/ETHPy150Open facebook/sparts/sparts/daemon.py/read_pid
7,811
def kill(pidfile, logger, signum=signal.SIGTERM): """Sends `signum` to the pid specified by `pidfile`. Logs messages to `logger`. Returns True if the process is not running, or signal was sent successfully. Returns False if the process for the pidfile was running and there was an error sending the si...
OSError
dataset/ETHPy150Open facebook/sparts/sparts/daemon.py/kill
7,812
def status(pidfile, logger): """Checks to see if the process for the pid in `pidfile` is running. Logs messages to `logger`. Returns True if there is a program for the running pid. Returns False if not or if there was an error polling the pid.""" daemon_pid = read_pid(pidfile, logger) if daem...
OSError
dataset/ETHPy150Open facebook/sparts/sparts/daemon.py/status
7,813
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...
OSError
dataset/ETHPy150Open leonjza/hogar/hogar/Utils/Daemon.py/Daemon.daemonize
7,814
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()) ...
SystemExit
dataset/ETHPy150Open leonjza/hogar/hogar/Utils/Daemon.py/Daemon.start
7,815
def stop (self): ''' Stop the daemon ''' if self.verbose >= 1: print 'Stopping...' # Get the pid from the pidfile pid = self.get_pid() if not pid: message = 'pidfile %s does not exist. Not running?\n' sys.stderr.write(m...
OSError
dataset/ETHPy150Open leonjza/hogar/hogar/Utils/Daemon.py/Daemon.stop
7,816
def get_pid (self): try: pf = file(self.pidfile, 'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None except __HOLE__: pid = None return pid
SystemExit
dataset/ETHPy150Open leonjza/hogar/hogar/Utils/Daemon.py/Daemon.get_pid
7,817
def _set_initial(self, initial): self._value = None try: self.value = initial[0] except __HOLE__: pass
IndexError
dataset/ETHPy150Open jmcarp/robobrowser/robobrowser/forms/fields.py/MultiOptionField._set_initial
7,818
def load_records(context, database, table, xml_dirpath, recursive=False, force_update=False): """Load metadata records from directory of files to database""" repo = repository.Repository(database, context, table=table) file_list = [] if os.path.isfile(xml_dirpath): file_list.append(xml_dirpath...
RuntimeError
dataset/ETHPy150Open geopython/pycsw/pycsw/core/admin.py/load_records
7,819
def export_records(context, database, table, xml_dirpath): """Export metadata records from database to directory of files""" repo = repository.Repository(database, context, table=table) LOGGER.info('Querying database %s, table %s ....', database, table) records = repo.session.query(repo.dataset) L...
OSError
dataset/ETHPy150Open geopython/pycsw/pycsw/core/admin.py/export_records
7,820
def get_sysprof(): """Get versions of dependencies""" none = 'Module not found' try: import sqlalchemy vsqlalchemy = sqlalchemy.__version__ except ImportError: vsqlalchemy = none try: import pyproj vpyproj = pyproj.__version__ except __HOLE__: v...
ImportError
dataset/ETHPy150Open geopython/pycsw/pycsw/core/admin.py/get_sysprof
7,821
def __init__(self, bindaddr, sinkspecs, interval, percent, debug=0, key_prefix=''): _, host, port = parse_addr(bindaddr) if port is None: self.exit(E_BADADDR % bindaddr) self._bindaddr = (host, port) # TODO: generalize to support more than one sink type. cu...
ValueError
dataset/ETHPy150Open phensley/gstatsd/gstatsd/service.py/StatsDaemon.__init__
7,822
def grid_one(request, year=datetime.now().year, month=datetime.now().month, day=None, calendar_slug=None, page=1): """ Shows a grid (similar in appearance to a physical calendar) of upcoming events for either a specific calendar or no calendar at all. """ try: page = int(page) if ye...
ValueError
dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/events/views.py/grid_one
7,823
def event_list(request, year=None, month=None, day=None, calendar_slug=None, page=1): """ Shows a list of upcoming events for either a specific calendar or no calendar at all. """ try: page = int(page) if year: year = int(year) if month: month = int(m...
ValueError
dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/events/views.py/event_list
7,824
def event_detail(request, year=None, month=None, day=None, event_slug=None): """ Shows a specific event. """ try: if year: year = int(year) if month: month = int(month) if day: day = int(day) except __HOLE__: raise Http404 ...
ValueError
dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/events/views.py/event_detail
7,825
def _diff_to_hdf(self, difflines, tabwidth): """ Translate a diff file into something suitable for inclusion in HDF. The result is [(filename, revname_old, revname_new, changes)], where changes has the same format as the result of `trac.versioncontrol.diff.hdf_diff`. If ...
StopIteration
dataset/ETHPy150Open edgewall/trac/trac/mimeview/patch.py/PatchRenderer._diff_to_hdf
7,826
def _assert_saved(self, subj): try: node = subj.__node__ if node is None: raise NotSaved(subj) except __HOLE__: raise NotSaved(subj)
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/ext/ogm/store.py/Store._assert_saved
7,827
def authenticate(self, force=False): reqbody = json.dumps({'auth': { 'passwordCredentials': { 'username': self.user_id, 'password': self.key }, 'tenantId': self._ex_tenant_id }}) resp = self.request('/tokens', data=reqbody, head...
KeyError
dataset/ETHPy150Open apache/libcloud/libcloud/compute/drivers/cloudwatt.py/CloudwattAuthConnection.authenticate
7,828
def parse_pajek(lines): """Parse Pajek format graph from string or iterable. Parameters ---------- lines : string or iterable Data in Pajek format. Returns ------- G : NetworkX graph See Also -------- read_pajek() """ import shlex # multigraph=False if ...
ValueError
dataset/ETHPy150Open networkx/networkx/networkx/readwrite/pajek.py/parse_pajek
7,829
def CreateFromPackage(self, filename, description, display_name, catalogs): """Create package info from a live package stored at filename. Args: filename: str description: str, like "Security update for Foo Software" display_name: str, like "Munki Client" catalogs: list of str catalog n...
OSError
dataset/ETHPy150Open google/simian/src/simian/mac/munki/pkgs.py/MunkiPackageInfo.CreateFromPackage
7,830
def run(self, result=None): if result is None: result = self.defaultTestResult() result.startTest(self) test_method = getattr(self, self._testMethodName) self._test_method = test_method try: ok = False self._set_up() try: ...
KeyboardInterrupt
dataset/ETHPy150Open horejsek/python-webdriverwrapper/webdriverwrapper/unittest/testcase.py/WebdriverTestCase.run
7,831
@csv.DictReader.fieldnames.getter def fieldnames(self): if self._fieldnames is None: try: self._fieldnames = self.reader.next() except __HOLE__: pass self.line_num = self.reader.line_num self.__mv_fieldnames = [] sel...
StopIteration
dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/splunk_csv/dict_reader.py/DictReader.fieldnames
7,832
def _hack_at_distutils(): # Windows-only workaround for some configurations: see # https://bugs.python.org/issue23246 (Python 2.7 with # a specific MS compiler suite download) if sys.platform == "win32": try: import setuptools # for side-effects, patches distutils except ...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/_hack_at_distutils
7,833
def _locate_module(self): if not os.path.isfile(self.modulefilename): if self.ext_package: try: pkg = __import__(self.ext_package, None, None, ['__doc__']) except __HOLE__: return # cannot import the package itself, give up...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/Verifier._locate_module
7,834
def _compile_module(self): # compile this C source tmpdir = os.path.dirname(self.sourcefilename) outputfilename = ffiplatform.compile(tmpdir, self.get_extension()) try: same = ffiplatform.samefile(outputfilename, self.modulefilename) except __HOLE__: same ...
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/Verifier._compile_module
7,835
def _locate_engine_class(ffi, force_generic_engine): if _FORCE_GENERIC_ENGINE: force_generic_engine = True if not force_generic_engine: if '__pypy__' in sys.builtin_module_names: force_generic_engine = True else: try: import _cffi_backend ...
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/_locate_engine_class
7,836
def cleanup_tmpdir(tmpdir=None, keep_so=False): """Clean up the temporary directory by removing all files in it called `_cffi_*.{c,so}` as well as the `build` subdirectory.""" tmpdir = tmpdir or _caller_dir_pycache() try: filelist = os.listdir(tmpdir) except __HOLE__: return if k...
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/cleanup_tmpdir
7,837
def _ensure_dir(filename): try: os.makedirs(os.path.dirname(filename)) except __HOLE__: pass
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/verifier.py/_ensure_dir
7,838
def _fork(self, fid): ''' fid - fork id ''' try: pid = os.fork() except __HOLE__, e: self.logger.error( "service._fork(), fork #%d failed: %d (%s)\n" % (fid, e.errno, e.strerror)) raise OSError(e) return pid
OSError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/Service._fork
7,839
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 ''' def _maxfd(limit=1024): ''' Use the getrlimit method ...
OSError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/Service.daemonize
7,840
def start(self): ''' Start the service ''' # Check for a pidfile to see if the service already runs current_pid = self.pidfile.validate() if current_pid: message = "pidfile %s exists. Service is running already" self.logger.error(message % current_...
RuntimeError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/Service.start
7,841
def stop(self): ''' Stop the service ''' pid = self.pidfile.validate() if not pid: message = "pidfile %s does not exist. Service is not running" self.logger.error(message % self.pidfile.fname) return # not an error in a restart # Try k...
OSError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/Service.stop
7,842
def status(self): srv = Service(self.process) pid = srv.pidfile.validate() if pid: try: os.kill(pid, 0) print 'Process {} is running, pid: {}'.format(srv.process.__name__, pid) return except (__HOLE__, TypeError): ...
OSError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/ServiceControl.status
7,843
def validate(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return try: ...
OSError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/Pidfile.validate
7,844
def load_process(process_path): ''' load process PEP 338 - Executing modules as scripts http://www.python.org/dev/peps/pep-0338 ''' if '.' not in process_path: raise RuntimeError("Invalid process path: {}".format(process_path)) module_name, process_name = process_path.rsplit('.', ...
KeyError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/load_process
7,845
def service(process=None, action=None): ''' control service ''' try: getattr(ServiceControl(process), action)() except __HOLE__, e: print >> sys.stderr, e
RuntimeError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/service
7,846
def main(): import argparse parser = argparse.ArgumentParser(prog="pyservice", add_help=False) parser.add_argument("-v", "--version", action="version", version="%(prog)s, v.{}".format(__version__)) parser.add_argument("-h", "--help", action="store_true", help="show program's help text ...
TypeError
dataset/ETHPy150Open ownport/pyservice/pyservice.py/main
7,847
def parse_hours_flag(args): """ If the `--hours` flag was used, get the time, and remove the flag and the time from the args list. Return FALSE if the flag was not present. """ try: pos = args.index('--hours') except __HOLE__: return False else: hours = args[...
ValueError
dataset/ETHPy150Open jongoodnow/gitime/gitime/commit.py/parse_hours_flag
7,848
def update(self): """Get the Efergy monitor data from the web service.""" try: if self.type == 'instant_readings': url_string = _RESOURCE + 'getInstant?token=' + self.app_token response = get(url_string) self._state = response.json()['reading']...
ValueError
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/sensor/efergy.py/EfergySensor.update
7,849
@staticmethod def _read_arg(args, key, default): try: return args[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open CacheBrowser/cachebrowser/cachebrowser/settings.py/CacheBrowserSettings._read_arg
7,850
def walk_all_tags(): for namespace_path in store.list_directory(store.repositories): for repos_path in store.list_directory(namespace_path): try: for tag in store.list_directory(repos_path): fname = tag.split('/').pop() if not fname.startsw...
OSError
dataset/ETHPy150Open docker/docker-registry/scripts/dump_repos_data.py/walk_all_tags
7,851
def __getattr__(self, name): try: return self[name] except __HOLE__: raise AttributeError("Attribute '%s' doesn't exists. " % name)
KeyError
dataset/ETHPy150Open klen/muffin/muffin/utils.py/Struct.__getattr__
7,852
def __init__(self, params, offset=0): agents.Agent.__init__(self, params, offset) try: self.maxprice = self.args[0] except (__HOLE__, IndexError): raise MissingParameter, 'maxprice' try: self.maxbuy = self.args[1] except IndexError: ...
AttributeError
dataset/ETHPy150Open jcbagneris/fms/fms/contrib/coleman/agents/avgbuyselltrader.py/AvgBuySellTrader.__init__
7,853
def is_password_usable(pw): # like Django's is_password_usable, but only checks for unusable # passwords, not invalidly encoded passwords too. try: # 1.5 from django.contrib.auth.hashers import UNUSABLE_PASSWORD return pw != UNUSABLE_PASSWORD except __HOLE__: # 1.6 ...
ImportError
dataset/ETHPy150Open fusionbox/django-authtools/authtools/forms.py/is_password_usable
7,854
def render(self, name, value, attrs): try: from django.forms.utils import flatatt except ImportError: from django.forms.util import flatatt # Django < 1.7 final_attrs = flatatt(self.build_attrs(attrs)) if not value or not is_password_usable(value): s...
ValueError
dataset/ETHPy150Open fusionbox/django-authtools/authtools/forms.py/BetterReadOnlyPasswordHashWidget.render
7,855
def iter_json(self, _path=None, requests_params=None, **apiparams): """Reliably iterate through all data as json strings""" requests_params = dict(requests_params or {}) requests_params.setdefault('method', 'GET') requests_params.setdefault('stream', True) lastexc = None ...
ValueError
dataset/ETHPy150Open scrapinghub/python-hubstorage/hubstorage/resourcetype.py/DownloadableResource.iter_json
7,856
@property def _data(self): if self._cached is None: r = self.apiget() try: self._cached = r.next() except __HOLE__: self._cached = {} return self._cached
StopIteration
dataset/ETHPy150Open scrapinghub/python-hubstorage/hubstorage/resourcetype.py/MappingResourceType._data
7,857
def start(self): """ Start the server. """ s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', config.socketport)) s.listen(1) try: while 1: conn, addr = s.accept() print('Con...
KeyboardInterrupt
dataset/ETHPy150Open adngdb/python-websocket-server/websocketserver.py/WebSocketServer.start
7,858
def _get_explicit_connections(self): """ Returns ------- dict Explicit connections in this `Group`, represented as a mapping from the pathname of the target to the pathname of the source. """ connections = {} for sub in self.subgroups(): ...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/core/group.py/Group._get_explicit_connections
7,859
def _build(self, *parameters): paths_to_add = self.prepare_build_path() with CustomEnvPath(paths_to_add=paths_to_add): paths = self.bii.bii_paths if len(parameters) == 1: # It's tuple, first element is list with actual parameters parameters = parameters[0] ...
IOError
dataset/ETHPy150Open biicode/client/dev/cmake/cmake_tool_chain.py/CMakeToolChain._build
7,860
def keep_alive(self): """ """ self._p0 = False self.handle_signals() with self.setup_output() as (stdout, stderr): self._terminating = False startretries = self.data.get('startretries', 3) initial_startretries = self.data.get('startretries',...
OSError
dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/program/base.py/ProgramBase.keep_alive
7,861
def stop_daemonlog(self): logger = logging.getLogger('chalmers') logger.removeHandler(self._daemonlog_hdlr) try: self._log_stream.close() except __HOLE__: # Ignore: # close() called during concurrent operation on the same file object. pass
IOError
dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/program/base.py/ProgramBase.stop_daemonlog
7,862
def push_to_device(device_or_devices): # get an iterable list of devices even if one wasn't specified try: iter(device_or_devices) except __HOLE__: devices = (device_or_devices, ) else: devices = device_or_devices # keyed access to topics for which we'll have an APNs connect...
TypeError
dataset/ETHPy150Open jessepeterson/commandment/commandment/push.py/push_to_device
7,863
def _dispatch(self, request): try: try: method = self.get_method(request.method) except __HOLE__ as e: return request.error_respond(MethodNotFoundError(e)) # we found the method try: result = method(*request.args, *...
KeyError
dataset/ETHPy150Open mbr/tinyrpc/tinyrpc/dispatch/__init__.py/RPCDispatcher._dispatch
7,864
def get_method(self, name): """Retrieve a previously registered method. Checks if a method matching ``name`` has been registered. If :py:func:`get_method` cannot find a method, every subdispatcher with a prefix matching the method name is checked as well. If a method isn't fou...
KeyError
dataset/ETHPy150Open mbr/tinyrpc/tinyrpc/dispatch/__init__.py/RPCDispatcher.get_method
7,865
def captureException(self, *args, **kwargs): assert self.client, 'captureException called before application configured' data = kwargs.get('data') if data is None: try: kwargs['data'] = get_data_from_request(request) except __HOLE__: # app ...
RuntimeError
dataset/ETHPy150Open getsentry/raven-python/raven/contrib/bottle/__init__.py/Sentry.captureException
7,866
def captureMessage(self, *args, **kwargs): assert self.client, 'captureMessage called before application configured' data = kwargs.get('data') if data is None: try: kwargs['data'] = get_data_from_request(request) except __HOLE__: # app is p...
RuntimeError
dataset/ETHPy150Open getsentry/raven-python/raven/contrib/bottle/__init__.py/Sentry.captureMessage
7,867
def do_update_translations(target=("t", ""), lang=("l", ""), statistics=("s", False), i18n_dir=("i", ""), all=("a", False)): """ Update existing translations with updated pot files. """ if not target and not all: print_status('Please specify target.') ...
IOError
dataset/ETHPy150Open IanLewis/kay/kay/management/update_translations.py/do_update_translations
7,868
def _setargs(self): """Copy func parameter names to obj attributes.""" try: for arg in _getargs(self.callable): setattr(self, arg, None) except (TypeError, AttributeError): if hasattr(self.callable, "__call__"): for arg in _getargs(self.cal...
IndexError
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/_cptools.py/Tool._setargs
7,869
def _configure(self, config_filename): """ Configure manager instance. """ self._logger.debug('Configuring from %r', config_filename) with open(config_filename, 'r') as inp: cfg = ConfigParser.ConfigParser() cfg.readfp(inp) for name in cfg.sections(): ...
ImportError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ResourceAllocationManager._configure
7,870
def _release(self, server): """ Release a server (proxy). """ with ResourceAllocationManager._lock: try: allocator, server, server_info = self._deployed_servers[id(server)] # Just being defensive. except __HOLE__: #pragma no cover self...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ResourceAllocationManager._release
7,871
@staticmethod def validate_resources(resource_desc): """ Validate that `resource_desc` is legal. resource_desc: dict Description of required resources. """ for key, value in resource_desc.items(): try: if not _VALIDATORS[key](value): ...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ResourceAllocationManager.validate_resources
7,872
def check_orphan_modules(self, resource_value): """ Returns a list of 'orphan' modules that are not available. resource_value: list List of 'orphan' module names. """ #FIXME: shouldn't pollute the environment like this does. not_found = [] for module in sorte...
ImportError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ResourceAllocator.check_orphan_modules
7,873
def __init__(self, name='LocalAllocator', total_cpus=0, max_load=1.0, authkey=None, allow_shell=False, server_limit=0): super(LocalAllocator, self).__init__(name, authkey, allow_shell) if total_cpus > 0: self.total_cpus = total_cpus else: try: ...
NotImplementedError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/LocalAllocator.__init__
7,874
@rbac('*') def max_servers(self, resource_desc, load_adjusted=False): """ Returns `total_cpus` * `max_load` if `resource_desc` is supported; otherwise, zero. The return value may be limited by `server_limit`. resource_desc: dict Description of required resources. ...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/LocalAllocator.max_servers
7,875
@rbac('*') def time_estimate(self, resource_desc): """ Returns ``(estimate, criteria)`` indicating how well this allocator can satisfy the `resource_desc` request. The estimate will be: - >0 for an estimate of walltime (seconds). - 0 for no estimate. - -1 for no re...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/LocalAllocator.time_estimate
7,876
def max_servers(self, resource_desc): """ Returns the total of :meth:`max_servers` across all :class:`LocalAllocator` in the cluster. resource_desc: dict Description of required resources. """ credentials = get_credentials() rdesc, info = self._check...
IndexError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ClusterAllocator.max_servers
7,877
def _load_average(self, rdesc): """ Time estimate using load averages. """ credentials = get_credentials() min_cpus = rdesc.get('min_cpus', 0) if min_cpus: # Spread across LocalAllocators. rdesc['min_cpus'] = 1 avail_cpus = 0 with self._lock: ...
IndexError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ClusterAllocator._load_average
7,878
def release(self, server): """ Release a server (proxy). server: :class:`OpenMDAO_Proxy` Server to be released. """ with self._lock: try: host = self._deployed_servers[id(server)][0] except __HOLE__: self._logge...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/resource.py/ClusterAllocator.release
7,879
def _make_bound_method(func, self): """ Magic for creating bound methods (used for _unload). """ class Foo(object): def meth(self): pass f = Foo() bound_method = type(f.meth) try: return bound_method(func, self, self.__class__) except __HOLE__: # python3 return b...
TypeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/util.py/_make_bound_method
7,880
def __call__(self, env, start_response): try: # /v1/a/c or /v1/a/c/o split_path(env['PATH_INFO'], 3, 4, True) is_container_or_object_req = True except __HOLE__: is_container_or_object_req = False headers = [('Content-Type', 'text/plain'), ...
ValueError
dataset/ETHPy150Open openstack/swift/test/unit/common/middleware/test_proxy_logging.py/FakeApp.__call__
7,881
def test_disconnect_on_readline(self): app = proxy_logging.ProxyLoggingMiddleware(FakeAppReadline(), {}) app.access_logger = FakeLogger() req = Request.blank('/', environ={'REQUEST_METHOD': 'GET', 'wsgi.input': FileLikeExceptor()}) try: ...
IOError
dataset/ETHPy150Open openstack/swift/test/unit/common/middleware/test_proxy_logging.py/TestProxyLogging.test_disconnect_on_readline
7,882
def test_disconnect_on_read(self): app = proxy_logging.ProxyLoggingMiddleware( FakeApp(['some', 'stuff']), {}) app.access_logger = FakeLogger() req = Request.blank('/', environ={'REQUEST_METHOD': 'GET', 'wsgi.input': FileLikeExceptor()}) ...
IOError
dataset/ETHPy150Open openstack/swift/test/unit/common/middleware/test_proxy_logging.py/TestProxyLogging.test_disconnect_on_read
7,883
@expose('/add/', methods=('GET', 'POST')) def add(self): if not self.can_create: abort(403) Form = self.get_add_form() if request.method == 'POST': form = Form() if form.validate_on_submit(): try: instance = self.save_m...
TypeError
dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/base.py/BaseModelAdmin.add
7,884
def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents if 'HTTP_USER_AGENT' in request.META: for user_agent_regex in settings.DISALLOW...
UnicodeDecodeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/middleware/common.py/CommonMiddleware.process_request
7,885
def FindOutgoingInterface(source): """XXX Describe the strategy that is used...""" # If the COM object implements IProvideClassInfo2, it is easy to # find the default outgoing interface. try: pci = source.QueryInterface(comtypes.typeinfo.IProvideClassInfo2) guid = pci.GetGUID(1) exce...
KeyError
dataset/ETHPy150Open enthought/comtypes/comtypes/client/_events.py/FindOutgoingInterface
7,886
def find_single_connection_interface(source): # Enumerate the connection interfaces. If we find a single one, # return it, if there are more, we give up since we cannot # determine which one to use. cpc = source.QueryInterface(comtypes.connectionpoints.IConnectionPointContainer) enum = cpc.EnumConn...
StopIteration
dataset/ETHPy150Open enthought/comtypes/comtypes/client/_events.py/find_single_connection_interface
7,887
def find_method(self, fq_name, mthname): impl = self._find_method(fq_name, mthname) # Caller of this method catches AttributeError, # so we need to be careful in the following code # not to raise one... try: # impl is a bound method, dissect it... im_self,...
AttributeError
dataset/ETHPy150Open enthought/comtypes/comtypes/client/_events.py/_SinkMethodFinder.find_method
7,888
def _find_method(self, fq_name, mthname): try: return super(_SinkMethodFinder, self).find_method(fq_name, mthname) except __HOLE__: try: return getattr(self.sink, fq_name) except AttributeError: return getattr(self.sink, mthname)
AttributeError
dataset/ETHPy150Open enthought/comtypes/comtypes/client/_events.py/_SinkMethodFinder._find_method
7,889
def test_odict(self): o = util.OrderedDict() o['a'] = 1 o['b'] = 2 o['snack'] = 'attack' o['c'] = 3 eq_(list(o.keys()), ['a', 'b', 'snack', 'c']) eq_(list(o.values()), [1, 2, 'attack', 3]) o.pop('snack') eq_(list(o.keys()), ['a', 'b', 'c']) ...
KeyError
dataset/ETHPy150Open zzzeek/sqlalchemy/test/base/test_utils.py/OrderedDictTest.test_odict
7,890
def test_basic_sanity(self): IdentitySet = util.IdentitySet o1, o2, o3 = object(), object(), object() ids = IdentitySet([o1]) ids.discard(o1) ids.discard(o1) ids.add(o1) ids.remove(o1) assert_raises(KeyError, ids.remove, o1) eq_(ids.copy(), ids) ...
TypeError
dataset/ETHPy150Open zzzeek/sqlalchemy/test/base/test_utils.py/IdentitySetTest.test_basic_sanity
7,891
def test_is_produced(self): """ test is_produced function """ class ChildNotOkContext(base.Context): __swagger_ref_object__ = ChildObj @classmethod def is_produced(kls, obj): return False class TestOkContext(base.Context): __swagg...
ValueError
dataset/ETHPy150Open mission-liao/pyswagger/pyswagger/tests/test_base.py/SwaggerBaseTestCase.test_is_produced
7,892
def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None): """Executes a given commmand and returns Response. Blocks until process is complete, or timeout is reached. """ command = expand_args(command) history = [] for c in command: if len(history): ...
OSError
dataset/ETHPy150Open kennethreitz/envoy/envoy/core.py/run
7,893
def compute(self): """ compute() -> None Translate input ports into (row, column) location """ loc = CellLocation.Location() def set_row_col(row, col): try: loc.col = ord(col) - ord('A') loc.row = int(row) - 1 except (Type...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/spreadsheet/basic_widgets.py/CellLocation.compute
7,894
def verify_challenge(self, entity, response): try: token = response.decode('utf-8') except __HOLE__ as exc: return self.state(False, entity, None) try: result = self.verify(token) if result: entity = entity or self.auth.username() ...
ValueError
dataset/ETHPy150Open HenryHu/pybbs/bbsauth.py/BBSAuth.verify_challenge
7,895
def set_value(self, value): """The value have to be in the form '10px' or '10%', so numeric value plus measure unit """ v = 0 measure_unit = 'px' try: v = int(float(value.replace('px', ''))) except ValueError: try: v = int(float(va...
ValueError
dataset/ETHPy150Open dddomodossola/remi/editor/editor_widgets.py/CssSizeInput.set_value
7,896
@register.simple_tag(takes_context=True) def associated(context, backend): user = context.get('user') context['association'] = None if user and user.is_authenticated(): try: context['association'] = user.social_auth.filter( provider=backend.name )[0] e...
IndexError
dataset/ETHPy150Open omab/python-social-auth/examples/django_example/example/app/templatetags/backend_utils.py/associated
7,897
def do_parallel_inference(args): """Perform inference in parallel on several observations matrices with joint parameters """ from treehmm import random_params, do_inference, plot_params, plot_energy, load_params from treehmm.vb_mf import normalize_trans from treehmm.static import float_type ...
KeyError
dataset/ETHPy150Open uci-cbcl/tree-hmm/treehmm/do_parallel.py/do_parallel_inference
7,898
def __length(self, collection): try: return len(collection) except __HOLE__: return sum(1 for i in collection)
TypeError
dataset/ETHPy150Open jaimegildesagredo/expects/expects/matchers/built_in/have_len.py/have_length.__length
7,899
def geocode(self, address, restriction): try: locs = self._geocode(address, restriction) rlocs = self._geocode(restriction) if locs: if rlocs: restriction_latlon = rlocs[0][1] locs.sort(key=lambda loc: distance_func(loc[...
KeyboardInterrupt
dataset/ETHPy150Open sirrice/dbtruck/dbtruck/analyze/geocode.py/DBTruckGeocoder.geocode