function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
def link_or_copy(src, dst): """link_or_copy(src:str, dst:str) -> None Tries to create a hard link to a file. If it is not possible, it will copy file src to dst """ # Links if possible, but we're across devices, we need to copy. try: os.link(src, dst) except __HOLE__, e: if ...
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/system/linux.py/link_or_copy
def test3(self): """ Test if origin of link_or_copy'ed file is deleteable. """ import tempfile import os (fd1, name1) = tempfile.mkstemp() os.close(fd1) (fd2, name2) = tempfile.mkstemp() os.close(fd2) os.unlink(name2) link_or_copy(name1, name2) ...
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/system/linux.py/TestLinux.test3
def cache_data(line): args = shlex.split(line) reqid = args[0] cached = reqid in Request.cache._cached_reqs if reqid in Request.cache._last_used: last_used = Request.cache._last_used[reqid] else: last_used = 'NOT IN _last_used' in_all = reqid in Request.cache.all_ids in_unman...
ValueError
dataset/ETHPy150Open roglew/pappy-proxy/pappyproxy/plugins/debug.py/cache_data
def pluralize(singular): """Return plural form of given lowercase singular word (English only). Based on ActiveState recipe http://code.activestate.com/recipes/413172/ >>> pluralize('') '' >>> pluralize('goose') 'geese' >>> pluralize('dolly') 'dollies' >>> pluralize('genius') 'g...
IndexError
dataset/ETHPy150Open haystack/eyebrowse-server/common/npl/pluralize.py/pluralize
def get_response(self): try: msg = smart_str(self.msg.decode()) except (__HOLE__,): msg = smart_str(self.msg) error = { 'success': False, 'data': { 'code': self.code, 'message': msg } } er...
AttributeError
dataset/ETHPy150Open joestump/django-ajax/ajax/exceptions.py/AJAXError.get_response
def parse_workflow_config(rawactions): """Given a list of options from [ticket-workflow]""" required_attrs = { 'oldstates': [], 'newstate': '', 'name': '', 'label': '', 'default': 0, 'operations': [], 'permissions': [], } optional_attrs = { ...
ValueError
dataset/ETHPy150Open edgewall/trac/trac/ticket/default_workflow.py/parse_workflow_config
def current_user_person(self): """https://familysearch.org/developers/docs/api/tree/Current_Tree_Person_resource""" try: url = self.collections["FSFT"]["response"]["collections"][0][ "links"]["current-user-person"]["href"] except __HOLE__: self.update_co...
KeyError
dataset/ETHPy150Open AmEv7Fam/familysearch-python-sdk-opensource/familysearch/user.py/User.current_user_person
def current_user_history(self): """https://familysearch.org/developers/docs/api/users/Current_User_History_resource""" try: url = self.collections["FSFT"]["response"]["collections"][0][ "links"]["current-user-history"]["href"] except __HOLE__: self.updat...
KeyError
dataset/ETHPy150Open AmEv7Fam/familysearch-python-sdk-opensource/familysearch/user.py/User.current_user_history
def validate_port(confvar): """ Validate that the value of confvar is between [0, 65535]. Returns [(confvar, error_msg)] or [] """ port_val = confvar.get() error_res = [(confvar, 'Port should be an integer between 0 and 65535 (inclusive).')] try: port = int(port_val) if port < 0 or port > 65535: ...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/lib/conf.py/validate_port
def _is_empty(self): if self.is_folder: try: dirs, files = default_storage.listdir(self.path) except __HOLE__: from mezzanine.core.exceptions import FileSystemEncodingChanged raise FileSystemEncodingChanged() if not dirs and not...
UnicodeDecodeError
dataset/ETHPy150Open stephenmcd/filebrowser-safe/filebrowser_safe/base.py/FileObject._is_empty
def _applicable_fixture(self, fixture, user_id): """Determine if this fixture is applicable for given user id.""" is_public = fixture["is_public"] try: uid = fixture["properties"]["user_id"] except __HOLE__: uid = None return uid == user_id or is_public
KeyError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/tests/api/openstack/test_images.py/ImageControllerWithGlanceServiceTest._applicable_fixture
def secure_project(self, secureops="secureops"): """Calling this does two things: It calls useradd to create a new Linux user, and it changes permissions on settings.py so only that user can access it. This is a necessary step before calling configure_apache() Pass in the path to the se...
IOError
dataset/ETHPy150Open bmbouter/Opus/opus/lib/deployer/__init__.py/ProjectDeployer.secure_project
def configure_apache(self, apache_conf_dir, httpport, sslport, servername_suffix, pythonpath="", secureops="secureops", ssl_crt=None, ssl_key=None, ssl_chain=None): """Configures apache to serve this Django project. apache_conf_dir should be apache's conf.d directory where a .con...
OSError
dataset/ETHPy150Open bmbouter/Opus/opus/lib/deployer/__init__.py/ProjectDeployer.configure_apache
def start_supervisord(self,secureops="secureops"): env = dict(os.environ) try: del env['DJANGO_SETTINGS_MODULE'] except __HOLE__: pass username = "opus"+self.projectname # Start it up log.info("Starting up supervisord for the project") pro...
KeyError
dataset/ETHPy150Open bmbouter/Opus/opus/lib/deployer/__init__.py/ProjectDeployer.start_supervisord
def _build_installer_in_docker(self, cluster, online_installer=None, unique=False): if online_installer is None: paTestOnlineInstaller = os.environ.get('PA_TEST_ONLINE_INSTALLER') online_installer = paTestOnlineInstaller is not None container_n...
OSError
dataset/ETHPy150Open prestodb/presto-admin/tests/product/prestoadmin_installer.py/PrestoadminInstaller._build_installer_in_docker
def setup_module(module): from nose import SkipTest try: tagger = Senna('/usr/share/senna-v2.0', ['pos', 'chk', 'ner']) except __HOLE__: raise SkipTest("Senna executable not found")
OSError
dataset/ETHPy150Open nltk/nltk/nltk/tag/senna.py/setup_module
def tearDown(self): super(TestCreate, self).setUp() try: self.service.event_types.delete(self.event_type_name) except __HOLE__: pass
KeyError
dataset/ETHPy150Open splunk/splunk-sdk-python/tests/test_event_type.py/TestCreate.tearDown
def tearDown(self): super(TestEventType, self).setUp() try: self.service.event_types.delete(self.event_type_name) except __HOLE__: pass
KeyError
dataset/ETHPy150Open splunk/splunk-sdk-python/tests/test_event_type.py/TestEventType.tearDown
def unzip_snap_mp4(abspath, quiet=False): zipped_snap = ZipFile(abspath) # unzip /path/to/zipfile.mp4 to /path/to/zipfile unzip_dir = os.path.splitext(abspath)[0] zipped_snap.extractall(unzip_dir) # move /path/to/zipfile.mp4 to /path/to/zipfile.zip os.rename(abspath, unzip_dir + '.zip') f...
OSError
dataset/ETHPy150Open rxw/snapy/snapy/utils.py/unzip_snap_mp4
def system_methodHelp(self, method_name): """system.methodHelp('add') => "Adds two integers together" Returns a string containing documentation for the specified method.""" method = None if method_name in self.funcs: method = self.funcs[method_name] elif sel...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/SimpleXMLRPCServer.py/SimpleXMLRPCDispatcher.system_methodHelp
def _dispatch(self, method, params): """Dispatches the XML-RPC method. XML-RPC calls are forwarded to a registered function that matches the called XML-RPC method name. If no such function exists then the call is forwarded to the registered instance, if available. ...
KeyError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/SimpleXMLRPCServer.py/SimpleXMLRPCDispatcher._dispatch
def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): ...
NotImplementedError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/SimpleXMLRPCServer.py/SimpleXMLRPCRequestHandler.do_POST
def decode_request_content(self, data): #support gzip encoding of request encoding = self.headers.get("content-encoding", "identity").lower() if encoding == "identity": return data if encoding == "gzip": try: return xmlrpclib.gzip_decode(dat...
ValueError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/SimpleXMLRPCServer.py/SimpleXMLRPCRequestHandler.decode_request_content
def handle_request(self, request_text = None): """Handle a single XML-RPC request passed through a CGI post method. If no XML data is given then it is read from stdin. The resulting XML-RPC response is printed to stdout along with the correct HTTP headers. """ i...
TypeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/SimpleXMLRPCServer.py/CGIXMLRPCRequestHandler.handle_request
@register.tag def get_object_models(parser, token): """ USAGE: {% load get_objects %} {% get_object_models "APP_NAME" "MODEL_NAME" "SORT" "NUMBER OF ITEMS" "VARIABLE_NAME" Then iterate through EXAMPLE: {% load get_objects %} {% get_object_models "django_yaba" "Story" "-created" "3...
ValueError
dataset/ETHPy150Open f4nt/djtracker/djtracker/templatetags/get_objects.py/get_object_models
def get_image(self, image_id): """ Shortcut method to retrieve a specific image (AMI). :type image_id: string :param image_id: the ID of the Image to retrieve :rtype: :class:`boto.ec2.image.Image` :return: The EC2 Image specified or None if the image is not found ...
IndexError
dataset/ETHPy150Open darcyliu/storyboard/boto/ec2/connection.py/EC2Connection.get_image
def __init__(self, nodelist): try: app_id = settings.FACEBOOK_APPLICATION_ID except __HOLE__: raise template.TemplateSyntaxError, "%r tag requires FACEBOOK_APP_ID to be configured." \ % token.contents.split()[0] self.app_id = app_id self.nodelist...
AttributeError
dataset/ETHPy150Open jgorset/fandjango/fandjango/templatetags/facebook.py/FacebookNode.__init__
def _decode_subelements(self): """Decode the stanza subelements.""" for child in self._element: if child.tag == self._show_tag: self._show = child.text elif child.tag == self._status_tag: self._status = child.text elif child.tag == self...
ValueError
dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/pyxmpp2/presence.py/Presence._decode_subelements
def tearDown(self): for recorder in self.top.recorders: recorder.close() os.chdir(self.startdir) if not os.environ.get('OPENMDAO_KEEPDIRS', False): try: shutil.rmtree(self.tempdir) except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/test/test_csvcase.py/TestCase.tearDown
def tearDown(self): for recorder in self.top.recorders: recorder.close() os.chdir(self.startdir) if not os.environ.get('OPENMDAO_KEEPDIRS', False): try: shutil.rmtree(self.tempdir) except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/test/test_csvcase.py/CSVCaseRecorderTestCase.tearDown
def extract_params(raw): """Extract parameters and return them as a list of 2-tuples. Will successfully extract parameters from urlencoded query strings, dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an empty list of parameters. Any other input will result in a return value of ...
TypeError
dataset/ETHPy150Open hzlf/openbroadcast/services/bcmon/requests/packages/oauthlib/common.py/extract_params
def open(self, port='', canonical=True): """ Opens fd on terminal console in non blocking mode. port is the serial port device path name or if '' then use os.ctermid() which returns path name of console usually '/dev/tty' canonical sets the mode for the port. Canonical ...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/ConsoleNb.open
def getLine(self,bs = 80): """Gets nonblocking line from console up to bs characters including newline. Returns empty string if no characters available else returns line. In canonical mode no chars available until newline is entered. """ line = '' try: ...
TypeError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/ConsoleNb.getLine
def receive(self): """ Reads nonblocking characters from serial device up to bs characters Returns empty bytes if no characters available else returns all available. In canonical mode no chars are available until newline is entered. """ data = b'' try: ...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/DeviceNb.receive
def send(self, data=b'\n'): """ Writes data bytes to serial device port. Returns number of bytes sent """ try: count = os.write(self.fd, data) except __HOLE__ as ex1: # ex1 is the target instance of the exception if ex1.errno == errno.EAGAIN: #BSD...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/DeviceNb.send
def receive(self): """ Reads nonblocking characters from serial device up to bs characters Returns empty bytes if no characters available else returns all available. In canonical mode no chars are available until newline is entered. """ data = b'' try: ...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/SerialNb.receive
def send(self, data=b'\n'): """ Writes data bytes to serial device port. Returns number of bytes sent """ try: count = self.serial.write(data) except __HOLE__ as ex1: # ex1 is the target instance of the exception if ex1.errno == errno.EAGAIN: #BSD...
OSError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/SerialNb.send
def __init__(self, name=u'', uid=0, port=None, speed=9600, bs=1024, server=None): """ Initialization method for instance. Parameters: name = user friendly name for driver ...
ImportError
dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/serial/serialing.py/Driver.__init__
def update(self, obj, set_fields=None, unset_fields=None, update_obj=True): collection = self.get_collection_for_cls(obj.__class__) if obj.pk == None: raise obj.DoesNotExist("update() called on document without primary key!") def serialize_fields(fields): if isinstan...
KeyError
dataset/ETHPy150Open adewes/blitzdb/blitzdb/backends/mongo/backend.py/Backend.update
def set_key(self, key, value): """ Set the given ``key`` to the given ``value``. Handles nested keys, e.g.:: d = AttrDict() d.set_key('foo.bar', 1) d.foo.bar == 1 # True """ if '.' in key: key, remainder = key.split('.', 1) ...
AttributeError
dataset/ETHPy150Open calliope-project/calliope/calliope/utils.py/AttrDict.set_key
def get_key(self, key, default=_MISSING): """ Looks up the given ``key``. Like set_key(), deals with nested keys. If default is anything but ``_MISSING``, the given default is returned if the key does not exist. """ if '.' in key: # Nested key of for...
AttributeError
dataset/ETHPy150Open calliope-project/calliope/calliope/utils.py/AttrDict.get_key
def del_key(self, key): """Delete the given key. Properly deals with nested keys.""" if '.' in key: key, remainder = key.split('.', 1) try: del self[key][remainder] except __HOLE__: self[key].del_key(remainder) else: ...
KeyError
dataset/ETHPy150Open calliope-project/calliope/calliope/utils.py/AttrDict.del_key
def __call__(self, *args, **kw): obj = args[0] try: cache = obj.__cache except AttributeError: cache = obj.__cache = {} key = (self.func, args[1:], frozenset(list(kw.items()))) try: res = cache[key] except __HOLE__: res = ca...
KeyError
dataset/ETHPy150Open calliope-project/calliope/calliope/utils.py/memoize_instancemethod.__call__
def option_getter(config_model, data): """Returns a get_option() function using the given config_model and data""" o = config_model d = data def get_option(option, x=None, default=None, ignore_inheritance=False): def _get_option(opt, fail=False): try: result = o.get...
KeyError
dataset/ETHPy150Open calliope-project/calliope/calliope/utils.py/option_getter
def _check_if_pyc(fname): """Return True if the extension is .pyc, False if .py and None if otherwise""" from imp import find_module from os.path import realpath, dirname, basename, splitext # Normalize the file-path for the find_module() filepath = realpath(fname) dirpath = dirname(filepat...
ImportError
dataset/ETHPy150Open benoitc/gunicorn/gunicorn/_compat.py/_check_if_pyc
def wrap_error(func, *args, **kw): """ Wrap socket.error, IOError, OSError, select.error to raise new specialized exceptions of Python 3.3 like InterruptedError (PEP 3151). """ try: return func(*args, **kw) except (socket.error, __HOLE__, OSError) as exc: ...
IOError
dataset/ETHPy150Open benoitc/gunicorn/gunicorn/_compat.py/wrap_error
def get_version(self, paths=None, default="unknown"): """Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the v...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/setuptools-0.6c11/setuptools/depends.py/Require.get_version
def get_module_constant(module, symbol, default=-1, paths=None): """Find 'module' by searching 'paths', and extract 'symbol' Return 'None' if 'module' does not exist on 'paths', or it does not define 'symbol'. If the module defines 'symbol' as a constant, return the constant. Otherwise, return 'defa...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/setuptools-0.6c11/setuptools/depends.py/get_module_constant
def _init_aliases(ctx): for alias, value in ctx._aliases.items(): try: setattr(ctx, alias, getattr(ctx, value)) except __HOLE__: pass
AttributeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_base.py/StandardBaseContext._init_aliases
def chop(ctx, x, tol=None): """ Chops off small real or imaginary parts, or converts numbers close to zero to exact zeros. The input can be a single number or an iterable:: >>> from mpmath import * >>> mp.dps = 15; mp.pretty = False >>> chop(5+1e-10j,...
TypeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_base.py/StandardBaseContext.chop
def __init__(self, *args, **kwargs): super(NoArgsCommand, self).__init__(*args, **kwargs) self.copied_files = [] self.symlinked_files = [] self.unmodified_files = [] self.post_processed_files = [] self.storage = storage.staticfiles_storage try: self.st...
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/staticfiles/management/commands/collectstatic.py/Command.__init__
def delete_file(self, path, prefixed_path, source_storage): """ Checks if the target file should be deleted if it already exists """ if self.storage.exists(prefixed_path): try: # When was the target file modified last time? target_last_modified...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/staticfiles/management/commands/collectstatic.py/Command.delete_file
def link_file(self, path, prefixed_path, source_storage): """ Attempt to link ``path`` """ # Skip this file if it was already copied earlier if prefixed_path in self.symlinked_files: return self.log(u"Skipping '%s' (already linked earlier)" % path) # Delete th...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/staticfiles/management/commands/collectstatic.py/Command.link_file
def copy_file(self, path, prefixed_path, source_storage): """ Attempt to copy ``path`` with storage """ # Skip this file if it was already copied earlier if prefixed_path in self.copied_files: return self.log(u"Skipping '%s' (already copied earlier)" % path) #...
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/staticfiles/management/commands/collectstatic.py/Command.copy_file
def query_api(self, data=None, endpoint='SMS'): url = self.api_url % endpoint if data: conn = Request(url, b(urlencode(data))) else: conn = Request(url) auth = b('Basic ') + b64encode(b(self.username + ':' + self.password)) conn.add_header('Authorization'...
HTTPError
dataset/ETHPy150Open 46elks/elkme/elkme/elks.py/Elks.query_api
def pprint_task(task, keys, label_size=60): """Return a nicely formatted string for a task. Parameters ---------- task: Value within dask graph to render as text keys: iterable List of keys within dask graph label_size: int (optional) Maximum size of output label, defaul...
TypeError
dataset/ETHPy150Open dask/dask/dask/diagnostics/profile_visualize.py/pprint_task
def send_to_able(self, method, args={}, to=None, **kwargs): actor = None try: actor = self.lookup(to) except __HOLE__: raise self.NoRouteError(to) if actor: return self.send(method, args, to=actor, **kwargs) r = self.scatter(method, args, prop...
KeyError
dataset/ETHPy150Open celery/cell/cell/presence.py/AwareActorMixin.send_to_able
def call_center_location_owner(user, ancestor_level): if user.location_id is None: return "" if ancestor_level == 0: owner_id = user.location_id else: location = SQLLocation.objects.get(location_id=user.location_id) ancestors = location.get_ancestors(ascending=True, include_s...
IndexError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/callcenter/utils.py/call_center_location_owner
def start(): ''' Start the saltnado! ''' try: from . import saltnado except __HOLE__ as err: logger.error('ImportError! {0}'.format(str(err))) return None mod_opts = __opts__.get(__virtualname__, {}) if 'num_processes' not in mod_opts: mod_opts['num_processe...
ImportError
dataset/ETHPy150Open saltstack/salt/salt/netapi/rest_tornado/__init__.py/start
@classmethod def MemcacheWrappedGet( cls, key_name, prop_name=None, memcache_secs=MEMCACHE_SECS, retry=False): """Fetches an entity by key name from model wrapped by Memcache. Args: key_name: str key name of the entity to fetch. prop_name: optional property name to return the value fo...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/models/base.py/BaseModel.MemcacheWrappedGet
def _SetForceInstallAfterDateStr(self, str_dt): """Sets the force_install_after_date property from a string.""" try: dt = datetime.datetime.strptime(str_dt, '%Y-%m-%d %H:%M') except ValueError: try: dt = datetime.datetime.strptime('%s 13:00' % (str_dt), '%Y-%m-%d %H:%M') except __H...
ValueError
dataset/ETHPy150Open google/simian/src/simian/mac/models/base.py/AppleSUSProduct._SetForceInstallAfterDateStr
def __contains__(self, key): with self._lock: try: self._load_key(key) except __HOLE__: pass return key in self._local
KeyError
dataset/ETHPy150Open pallets/werkzeug/examples/cupoftee/db.py/Database.__contains__
def setdefault(self, key, factory): with self._lock: try: rv = self._load_key(key) except __HOLE__: self._local[key] = rv = factory() return rv
KeyError
dataset/ETHPy150Open pallets/werkzeug/examples/cupoftee/db.py/Database.setdefault
def list(self): try: files = os.listdir(self.folder) except __HOLE__: files = [] return files
IOError
dataset/ETHPy150Open dokipen/whoosh/src/whoosh/filedb/filestore.py/FileStorage.list
def run(self): mtimes = {} while 1: for filename in chain(_iter_module_files(), self.extra_files): try: mtime = os.stat(filename).st_mtime except __HOLE__: continue old_...
OSError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/werkzeug/_reloader.py/StatReloaderLoop.run
def run(self): watches = {} observer = self.observer_class() observer.start() while not self.should_reload: to_delete = set(watches) paths = _find_observable_paths(self.extra_files) for path in paths: if path not in watches: ...
OSError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/werkzeug/_reloader.py/WatchdogReloaderLoop.run
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type='auto'): """Run the given function in an independent python interpreter.""" import signal reloader = reloader_loops[reloader_type](extra_files, interval) signal.signal(signal.SIGTERM, lambda *args: sys.exi...
KeyboardInterrupt
dataset/ETHPy150Open GoogleCloudPlatform/appengine-flask-skeleton/lib/werkzeug/_reloader.py/run_with_reloader
def get_status(name): """Get the status of an instance. Args: name: Instance name Returns: A tuple (state, extra_info). extra_info is a string only used when the instance is broken somehow. This won't ever report HADOOP_READY; that's known when we start a Hadoop daemon ourselves. """ # Do ge...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/compute-hadoop-java-python/util.py/get_status
def name_to_ip(name, data=None): """Do a DNS lookup using the Compute API. Args: name: instance name data: the result from calling getinstance, if the caller already has it. Returns: An IP address, unless some error is raised. """ if name in ip_cache: return ip_cache[name] else: if dat...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/compute-hadoop-java-python/util.py/name_to_ip
def talk_to_agent(address, method, data=None): """Make a REST call. These are described in docs/API. Args: address: IP address from name_to_ip() or a hostname (if called from an instance) method: the HTTP call to make, should include the leading / data: a Python dictionary; caller must JSO...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/compute-hadoop-java-python/util.py/talk_to_agent
def typifyFields(fields) : primary_fields = [] data_model = [] for definition in fields : try : field_type = definition['type'] except __HOLE__ : raise TypeError("Incorrect field specification: field " "specifications are dictionaries that...
TypeError
dataset/ETHPy150Open datamade/dedupe/dedupe/datamodel.py/typifyFields
def __call__(self, container): np_key = container.getNonPersistentKey() try: old_container = self.common.non_persistant_pointer_lookup[np_key] except KeyError: old_container = None if old_container is not None: try: del self.common.ca...
KeyError
dataset/ETHPy150Open hoytak/lazyrunner/lazyrunner/pnstructures.py/_PNodeNonPersistentDeleter.__call__
def decreaseResultReference(self): assert self.result_reference_count >= 1 self.result_reference_count -= 1 assert self.module_reference_count <= self.result_reference_count if self.result_reference_count == 0: try: del self.results_container ...
AttributeError
dataset/ETHPy150Open hoytak/lazyrunner/lazyrunner/pnstructures.py/PNode.decreaseResultReference
def _reportResults(self, results): if not self.results_reported: try: self.p_class.reportResults(self.parameters, self.parameters[self.name], results) except TypeError, te: rrf = self.p_class.reportResults def raiseTypeError(): ...
TypeError
dataset/ETHPy150Open hoytak/lazyrunner/lazyrunner/pnstructures.py/PNode._reportResults
def getStream(self): from PIL import Image, ImageDraw # PIL dependency # Create an image and draw something on it. image = Image.new("RGB", (270, 270)) drawable = ImageDraw.Draw(image) drawable.rectangle([0, 0, 270, 270], fill=str(Color.BLUE)) drawable.rectangle([1, 1, ...
IOError
dataset/ETHPy150Open rwl/muntjac/muntjac/addon/colorpicker/color_picker_application.py/MyImageSource.getStream
def __init__(self, command): self.args = self._split_command_line(command) self.command = self.args[0] self.exitStatus = -1 try: self.pid, self.child_fd = pty.fork() except __HOLE__, e: raise Exception("Unable to fork") if self.pi...
OSError
dataset/ETHPy150Open joehewitt/devon/devon/spawn.py/SpawnPty.__init__
def read(self): r, w, e = select.select([self.child_fd], [], [], 30) if not r: return "" if self.child_fd in r: try: txt = os.read(self.child_fd, 1000) except __HOLE__: # XXXblake Not sure why this happens on Unix ...
OSError
dataset/ETHPy150Open joehewitt/devon/devon/spawn.py/SpawnPty.read
@feature('download') def feature_download(tgen): ''' Download a file. ''' work_dir = tgen.make_node(tgen.worch.download_dir) target_filename = tgen.worch.download_target if not target_filename: target_filename = os.path.basename(tgen.worch.download_url) target_node = work_dir.make_no...
IOError
dataset/ETHPy150Open hwaf/hwaf/py-hwaftools/orch/features/feature_download.py/feature_download
def _unwrap(self, ret_fun, err_fun): """Iterate over the options in the choice type, and try to perform some action on them. If the action fails (returns None or raises either CoercionError or ValueError), then it goes on to the next type. Args: ret_fun: a function that takes a wrapped option val...
ValueError
dataset/ETHPy150Open wickman/pystachio/pystachio/choice.py/ChoiceContainer._unwrap
def _make_client(self, parsed_url, options): # Creates a kazoo client, # See: https://github.com/python-zk/kazoo/blob/2.2.1/kazoo/client.py # for what options a client takes... maybe_hosts = [parsed_url.netloc] + list(options.get('hosts', [])) hosts = list(compat_filter(None, may...
KeyError
dataset/ETHPy150Open openstack/tooz/tooz/drivers/zookeeper.py/KazooDriver._make_client
def handle_connection(self, conn): """ Handle an individual connection. """ input = conn.makefile("r") output = conn.makefile("w") environ = self.read_env(input) environ['wsgi.input'] = input environ['wsgi.errors'] = sys.stderr enviro...
IOError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/scgiserver.py/SWAP.handle_connection
def read_sock(sock): buffers = [] while True: try: buffer = sock.recv(BUFFER_SIZE) except __HOLE__ as err: if err.errno != errno.EINTR: raise continue else: if not buffer: break buffers.append(buf...
IOError
dataset/ETHPy150Open serverdensity/sd-agent-plugins/Uwsgi/Uwsgi.py/read_sock
def get_studies_by_regions(dataset, masks, threshold=0.08, remove_overlap=True, studies=None, features=None, regularization="scale"): """ Set up data for a classification task given a set of masks Given a set of masks, this function retrieves studies associated with each mask at the sp...
OSError
dataset/ETHPy150Open neurosynth/neurosynth/neurosynth/analysis/classify.py/get_studies_by_regions
def set_class_weight(self, class_weight='auto', y=None): """ Sets the class_weight of the classifier to match y """ if class_weight == None: cw = None try: self.clf.set_params(class_weight = cw) except __HOLE__: pass ...
ValueError
dataset/ETHPy150Open neurosynth/neurosynth/neurosynth/analysis/classify.py/Classifier.set_class_weight
def getOpenIDStore(filestore_path, table_prefix): """ Returns an OpenID association store object based on the database engine chosen for this Django application. * If no database engine is chosen, a filesystem-based store will be used whose path is filestore_path. * If a database engine is c...
KeyboardInterrupt
dataset/ETHPy150Open adieu/python-openid/examples/djopenid/util.py/getOpenIDStore
def handle(self, *args, **options): start_date = date(2013,6,16) end_date = date(2013,6,18) one_day = timedelta(days=1) this_date = start_date while (this_date < end_date): datestring = this_date.strftime("%Y%m%d") entry_time = datetime(t...
KeyError
dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/formdata/management/commands/enter_headers_from_archive.py/Command.handle
def make_model(name): cfgs = config.model_configs(name) try: model_class = getattr(model_types, cfgs['model']) except __HOLE__: raise AttributeError('Unable to find model \ %s in model_types.py' % cfgs['model']) logger.info('Creating model %s' % name) m...
AttributeError
dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/Miroslaw/models.py/make_model
def train_model(name): try: model = utils.load_from_cache(name) logger.info('Loading model %s from cache' % name) except __HOLE__: cfgs = config.model_configs(name) model = make_model(name) data = get_model_data(name) logger.info('Training model %s' % name) ...
IOError
dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/Miroslaw/models.py/train_model
def predict_model(name, data, model=None): if model is None: model = train_model(name) try: pred = model.predict(data) except __HOLE__: raise AttributeError("Model %s does not implement a predict function" % name) cfgs = config.model_configs(name) if 'postpr...
AttributeError
dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/Miroslaw/models.py/predict_model
def get_validation_errors(outfile, app=None): """ Validates all models that are part of the specified app. If no app name is provided, validates all models of all installed apps. Writes errors, if any, to outfile. Returns number of errors. """ from django.db import models, connection from dj...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/core/management/validation.py/get_validation_errors
def custom_message_validator(validator, error_message=None): def _validator(raw_value): try: return validator(raw_value) except __HOLE__ as e: if error_message: e.args = (error_message,) raise return _validator
ValueError
dataset/ETHPy150Open sodastsai/taskr/taskr/contrib/validators.py/custom_message_validator
@classmethod def create(cls, entry): """ Factory that creates an app config from an entry in INSTALLED_APPS. """ try: # If import_module succeeds, entry is a path to an app module, # which may specify an app config class with default_app_config. # ...
AttributeError
dataset/ETHPy150Open django/django/django/apps/config.py/AppConfig.create
def get_model(self, model_name): """ Returns the model with the given case-insensitive model_name. Raises LookupError if no model exists with this name. """ self.check_models_ready() try: return self.models[model_name.lower()] except __HOLE__: ...
KeyError
dataset/ETHPy150Open django/django/django/apps/config.py/AppConfig.get_model
def __init__(self, colorscheme_config, colors_config): '''Initialize a colorscheme.''' self.colors = {} self.gradients = {} self.groups = colorscheme_config['groups'] self.translations = colorscheme_config.get('mode_translations', {}) # Create a dict of color tuples with both a cterm and hex value for c...
TypeError
dataset/ETHPy150Open powerline/powerline/powerline/colorscheme.py/Colorscheme.__init__
def get_group_props(self, mode, trans, group, translate_colors=True): if isinstance(group, (str, unicode)): try: group_props = trans['groups'][group] except KeyError: try: group_props = self.groups[group] except KeyError: return None else: return self.get_group_props(mode, trans, ...
KeyError
dataset/ETHPy150Open powerline/powerline/powerline/colorscheme.py/Colorscheme.get_group_props
def truncatechars(value, arg): """ Truncates a string after a certain number of characters, but respects word boundaries. Argument: Number of characters to truncate after. """ try: length = int(arg) except __HOLE__: # If the argument is not a valid integer. return value # Fail s...
ValueError
dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/etc/templatetags/tags.py/truncatechars
@register.filter def partition(my_list, n): ''' Partitions a list into sublists, each with n (or fewer) elements. my_list = [1,2,3,4,5] partion(my_list, 2) => [[1,2],[3,4],[5]] ''' try: n = int(n) my_list = list(my_list) except __HOLE__: return [my_list] return [...
ValueError
dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/etc/templatetags/tags.py/partition
def get_hexdigest(algorithm, salt, raw_password): """ Returns a string of the hexdigest of the given plaintext password and salt using the given algorithm ('md5', 'sha1' or 'crypt'). """ raw_password, salt = smart_str(raw_password), smart_str(salt) if algorithm == 'crypt': try: ...
ImportError
dataset/ETHPy150Open adieu/django-nonrel/django/contrib/auth/models.py/get_hexdigest
def create_user(self, username, email, password=None): """ Creates and saves a User with the given username, e-mail and password. """ now = datetime.datetime.now() # Normalize the address by lowercasing the domain part of the email # address. try: ema...
ValueError
dataset/ETHPy150Open adieu/django-nonrel/django/contrib/auth/models.py/UserManager.create_user
def get_profile(self): """ Returns site-specific profile for this user. Raises SiteProfileNotAvailable if this site does not allow profiles. """ if not hasattr(self, '_profile_cache'): from django.conf import settings if not getattr(settings, 'AUTH_PROFILE...
ImportError
dataset/ETHPy150Open adieu/django-nonrel/django/contrib/auth/models.py/User.get_profile