Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,400
@classdef.method("atime") def method_atime(self, space): try: stat_val = os.stat(self.filename) except __HOLE__ as e: raise error_for_oserror(space, e) return self._time_at(space, stat_val.st_atime)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_atime
3,401
@classdef.method("ctime") def method_ctime(self, space): try: stat_val = os.stat(self.filename) except __HOLE__ as e: raise error_for_oserror(space, e) return self._time_at(space, stat_val.st_ctime)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_ctime
3,402
@classdef.method("chmod", mode="int") def method_chmod(self, space, mode): try: fchmod(self.fd, mode) except __HOLE__ as e: raise error_for_oserror(space, e) return space.newint(0)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.method_chmod
3,403
@classdef.singleton_method("chmod", mode="int") def singleton_method_chmod(self, space, mode, args_w): for arg_w in args_w: path = Coerce.path(space, arg_w) try: os.chmod(path, mode) except __HOLE__ as e: raise error_for_oserror(space, e) return space.newint(len(args_w))
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_chmod
3,404
@classdef.singleton_method("stat", filename="path") def singleton_method_stat(self, space, filename): try: stat_val = os.stat(filename) except __HOLE__ as e: raise error_for_oserror(space, e) stat_obj = W_FileStatObject(space) stat_obj.set_stat(stat_val) return stat_obj
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_stat
3,405
@classdef.singleton_method("lstat", filename="path") def singleton_method_lstat(self, space, filename): try: stat_val = os.lstat(filename) except __HOLE__ as e: raise error_for_oserror(space, e) stat_obj = W_FileStatObject(space) stat_obj.set_stat(stat_val) return stat_obj
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_lstat
3,406
@classdef.singleton_method("symlink", old_name="path", new_name="path") def singleton_method_symlink(self, space, old_name, new_name): try: os.symlink(old_name, new_name) except __HOLE__ as e: raise error_for_oserror(space, e) return space.newint(0)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_symlink
3,407
@classdef.singleton_method("link", old_name="path", new_name="path") def singleton_method_link(self, space, old_name, new_name): try: os.link(old_name, new_name) except __HOLE__ as e: raise error_for_oserror(space, e) return space.newint(0)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileObject.singleton_method_link
3,408
@classdef.method("initialize", filename="path") def method_initialize(self, space, filename): try: self.set_stat(os.stat(filename)) except __HOLE__ as e: raise error_for_oserror(space, e)
OSError
dataset/ETHPy150Open topazproject/topaz/topaz/objects/fileobject.py/W_FileStatObject.method_initialize
3,409
def update_address_book(self, user, shipping_addr): """ Update the user's address book based on the new shipping address """ try: user_addr = user.addresses.get( hash=shipping_addr.generate_hash()) except __HOLE__: # Create a new user address user_addr = UserAddress(user=user) shipping_addr.populate_alternative_model(user_addr) user_addr.num_orders += 1 user_addr.save()
ObjectDoesNotExist
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/checkout/mixins.py/OrderPlacementMixin.update_address_book
3,410
def test_prevent_configuring_two_storages_with_same_name(self): DepotManager.configure('first', {'depot.storage_path': './lfs'}) try: DepotManager.configure('first', {'depot.storage_path': './lfs2'}) except __HOLE__: pass else: assert False, 'Should have raised RunetimeError here'
RuntimeError
dataset/ETHPy150Open amol-/depot/tests/test_depot_manager.py/TestDepotManager.test_prevent_configuring_two_storages_with_same_name
3,411
def readFile(self): ''' Read the data from the file specified in the global object path. The data readed is encoded with the format specified in the global object encoding, by default this object is UTF-8. Use this method if you don't want to modify the data received from the file. Returns: text {string} -- encoded text readed from file ''' text = '' try: with codecs.open(self.path, 'r', self.encoding) as file: text = file.read() except (__HOLE__, UnicodeError): pass return text
IOError
dataset/ETHPy150Open gepd/Deviot/libs/JSONFile.py/JSONFile.readFile
3,412
def writeFile(self, text, append=False): '''Write File Write the data passed in a file specified in the global object path. This method is called automatically by saveData, and encode the text in the format specified in the global object encoding, by default this object is UTF-8. Use this method if you don't want to modify the data to write. Arguments: text {string} -- Text to write in the file append {boolean} -- Set to True if you want to append the data in the file (default: False) ''' mode = 'w' if append: mode = 'a' try: with codecs.open(self.path, mode, self.encoding) as file: file.write(text) except (__HOLE__, UnicodeError): pass
IOError
dataset/ETHPy150Open gepd/Deviot/libs/JSONFile.py/JSONFile.writeFile
3,413
def display_for_field(value, field, empty_value_display=None): try: return _display_for_field(value, field, empty_value_display) except __HOLE__: return _display_for_field(value, field)
TypeError
dataset/ETHPy150Open callowayproject/django-categories/categories/editor/utils.py/display_for_field
3,414
def lower(self, key): try: return key.lower() except __HOLE__: return key
AttributeError
dataset/ETHPy150Open ejeschke/ginga/ginga/misc/Bunch.py/caselessDict.lower
3,415
def _votes(self, val): """ Returns cleaned version of votes or 0 if it's a non-numeric value. """ if type(val) is str: if val.strip() == '': return 0 try: return int(float(val)) except __HOLE__: # Count'y convert value from string return 0
ValueError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/nh/load.py/NHBaseLoader._votes
3,416
def test_unique_for_date_with_nullable_date(self): FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() except ValidationError: self.fail("unique_for_date checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(slug="Django 1.0") try: p.full_clean() except __HOLE__: self.fail("unique_for_year checks shouldn't trigger when the associated DateField is None.") p = FlexibleDatePost(subtitle="Finally") try: p.full_clean() except ValidationError: self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
ValidationError
dataset/ETHPy150Open django/django/tests/validation/test_unique.py/PerformUniqueChecksTest.test_unique_for_date_with_nullable_date
3,417
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: os.kill(wpid, 0) return wpid except OSError, e: if e[0] == errno.ESRCH: return raise except __HOLE__, e: if e[0] == errno.ENOENT: return raise
IOError
dataset/ETHPy150Open benoitc/tproxy/tproxy/pidfile.py/Pidfile.validate
3,418
def main(): with CementDevtoolsApp() as app: try: app.run() except __HOLE__ as e: print("AssertionError => %s" % e.args[0])
AssertionError
dataset/ETHPy150Open datafolklabs/cement/scripts/devtools.py/main
3,419
def __str__(self): """Prints string with field name if present on exception.""" message = Error.__str__(self) try: field_name = self.field_name except __HOLE__: return message else: return message # Attributes that are reserved by a class definition that # may not be used by either Enum or Message class definitions.
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/ValidationError.__str__
3,420
def message_definition(cls): """Get outer Message definition that contains this definition. Returns: Containing Message definition if definition is contained within one, else None. """ try: return cls._message_definition() except __HOLE__: return None
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/_DefinitionClass.message_definition
3,421
def __new__(cls, index): """Acts as look-up routine after class is initialized. The purpose of overriding __new__ is to provide a way to treat Enum subclasses as casting types, similar to how the int type functions. A program can pass a string or an integer and this method with "convert" that value in to an appropriate Enum instance. Args: index: Name or number to look up. During initialization this is always the name of the new enum value. Raises: TypeError: When an inappropriate index value is passed provided. """ # If is enum type of this class, return it. if isinstance(index, cls): return index # If number, look up by number. if isinstance(index, (int, long)): try: return cls.lookup_by_number(index) except KeyError: pass # If name, look up by name. if isinstance(index, basestring): try: return cls.lookup_by_name(index) except __HOLE__: pass raise TypeError('No such value for %s in Enum %s' % (index, cls.__name__))
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Enum.__new__
3,422
def check_initialized(self): """Check class for initialization status. Check that all required fields are initialized Raises: ValidationError: If message is not initialized. """ for name, field in self.__by_name.iteritems(): value = getattr(self, name) if value is None: if field.required: raise ValidationError("Message %s is missing required field %s" % (type(self).__name__, name)) else: try: if (isinstance(field, MessageField) and issubclass(field.type, MessageField)): if field.repeated: for item in value: item.check_initialized() else: value.check_initialized() except __HOLE__, err: if not hasattr(err, 'message_name'): err.message_name = type(self).__name__ raise
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Message.check_initialized
3,423
def is_initialized(self): """Get initialization status. Returns: True if message is valid, else False. """ try: self.check_initialized() except __HOLE__: return False else: return True
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Message.is_initialized
3,424
def get_assigned_value(self, name): """Get the assigned value of an attribute. Get the underlying value of an attribute. If value has not been set, will not return the default for the field. Args: name: Name of attribute to get. Returns: Value of attribute, None if it has not been set. """ message_type = type(self) try: field = message_type.field_by_name(name) except __HOLE__: raise AttributeError('Message %s has no field %s' % ( message_type.__name__, name)) return self.__tags.get(field.number)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Message.get_assigned_value
3,425
def reset(self, name): """Reset assigned value for field. Resetting a field will return it to its default value or None. Args: name: Name of field to reset. """ message_type = type(self) try: field = message_type.field_by_name(name) except __HOLE__: if name not in message_type.__by_name: raise AttributeError('Message %s has no field %s' % ( message_type.__name__, name)) self.__tags.pop(field.number, None)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Message.reset
3,426
@util.positional(2) def __init__(self, number, required=False, repeated=False, variant=None, default=None): """Constructor. The required and repeated parameters are mutually exclusive. Setting both to True will raise a FieldDefinitionError. Sub-class Attributes: Each sub-class of Field must define the following: VARIANTS: Set of variant types accepted by that field. DEFAULT_VARIANT: Default variant type if not specified in constructor. Args: number: Number of field. Must be unique per message class. required: Whether or not field is required. Mutually exclusive with 'repeated'. repeated: Whether or not field is repeated. Mutually exclusive with 'required'. variant: Wire-format variant hint. default: Default value for field if not found in stream. Raises: InvalidVariantError when invalid variant for field is provided. InvalidDefaultError when invalid default for field is provided. FieldDefinitionError when invalid number provided or mutually exclusive fields are used. InvalidNumberError when the field number is out of range or reserved. """ if not isinstance(number, int) or not 1 <= number <= MAX_FIELD_NUMBER: raise InvalidNumberError('Invalid number for field: %s\n' 'Number must be 1 or greater and %d or less' % (number, MAX_FIELD_NUMBER)) if FIRST_RESERVED_FIELD_NUMBER <= number <= LAST_RESERVED_FIELD_NUMBER: raise InvalidNumberError('Tag number %d is a reserved number.\n' 'Numbers %d to %d are reserved' % (number, FIRST_RESERVED_FIELD_NUMBER, LAST_RESERVED_FIELD_NUMBER)) if repeated and required: raise FieldDefinitionError('Cannot set both repeated and required') if variant is None: variant = self.DEFAULT_VARIANT if repeated and default is not None: raise FieldDefinitionError('Repeated fields may not have defaults') if variant not in self.VARIANTS: raise InvalidVariantError( 'Invalid variant: %s\nValid variants for %s are %r' % (variant, type(self).__name__, sorted(self.VARIANTS))) self.number = number self.required = required self.repeated = repeated self.variant = variant if default is not None: try: self.validate_default(default) except __HOLE__, err: try: name = self.name except AttributeError: # For when raising error before name initialization. raise InvalidDefaultError('Invalid default value for %s: %s: %s' % (self.__class__.__name__, default, err)) else: raise InvalidDefaultError('Invalid default value for field %s: ' '%s: %s' % (name, default, err)) self.__default = default self.__initialized = True
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Field.__init__
3,427
def validate_element(self, value): """Validate single element of field. This is different from validate in that it is used on individual values of repeated fields. Args: value: Value to validate. Raises: ValidationError if value is not expected type. """ if not isinstance(value, self.type): if value is None: if self.required: raise ValidationError('Required field is missing') else: try: name = self.name except __HOLE__: raise ValidationError('Expected type %s for %s, ' 'found %s (type %s)' % (self.type, self.__class__.__name__, value, type(value))) else: raise ValidationError('Expected type %s for field %s, ' 'found %s (type %s)' % (self.type, name, value, type(value)))
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Field.validate_element
3,428
def __validate(self, value, validate_element): """Internal validation function. Validate an internal value using a function to validate individual elements. Args: value: Value to validate. validate_element: Function to use to validate individual elements. Raises: ValidationError if value is not expected type. """ if not self.repeated: validate_element(value) else: # Must be a list or tuple, may not be a string. if isinstance(value, (list, tuple)): for element in value: if element is None: try: name = self.name except __HOLE__: raise ValidationError('Repeated values for %s ' 'may not be None' % self.__class__.__name__) else: raise ValidationError('Repeated values for field %s ' 'may not be None' % name) validate_element(element) elif value is not None: try: name = self.name except AttributeError: raise ValidationError('%s is repeated. Found: %s' % ( self.__class__.__name__, value)) else: raise ValidationError('Field %s is repeated. Found: %s' % (name, value))
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Field.__validate
3,429
def message_definition(self): """Get Message definition that contains this Field definition. Returns: Containing Message definition for Field. Will return None if for some reason Field is defined outside of a Message class. """ try: return self._message_definition() except __HOLE__: return None
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/Field.message_definition
3,430
def validate_element(self, value): """Validate StringField allowing for str and unicode. Raises: ValidationError if a str value is not 7-bit ascii. """ # If value is str is it considered valid. Satisfies "required=True". if isinstance(value, str): try: unicode(value) except __HOLE__, err: try: name = self.name except AttributeError: validation_error = ValidationError( 'Field encountered non-ASCII string %s: %s' % (value, err)) else: validation_error = ValidationError( 'Field %s encountered non-ASCII string %s: %s' % (self.name, value, err)) validation_error.field_name = self.name raise validation_error else: super(StringField, self).validate_element(value)
UnicodeDecodeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/StringField.validate_element
3,431
@property def default(self): """Default for enum field. Will cause resolution of Enum type and unresolved default value. """ try: return self.__resolved_default except __HOLE__: resolved_default = super(EnumField, self).default if isinstance(resolved_default, (basestring, int, long)): resolved_default = self.type(resolved_default) self.__resolved_default = resolved_default return self.__resolved_default
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/EnumField.default
3,432
@util.positional(2) def find_definition(name, relative_to=None, importer=__import__): """Find definition by name in module-space. The find algorthm will look for definitions by name relative to a message definition or by fully qualfied name. If no definition is found relative to the relative_to parameter it will do the same search against the container of relative_to. If relative_to is a nested Message, it will search its message_definition(). If that message has no message_definition() it will search its module. If relative_to is a module, it will attempt to look for the containing module and search relative to it. If the module is a top-level module, it will look for the a message using a fully qualified name. If no message is found then, the search fails and DefinitionNotFoundError is raised. For example, when looking for any definition 'foo.bar.ADefinition' relative to an actual message definition abc.xyz.SomeMessage: find_definition('foo.bar.ADefinition', SomeMessage) It is like looking for the following fully qualified names: abc.xyz.SomeMessage. foo.bar.ADefinition abc.xyz. foo.bar.ADefinition abc. foo.bar.ADefinition foo.bar.ADefinition When resolving the name relative to Message definitions and modules, the algorithm searches any Messages or sub-modules found in its path. Non-Message values are not searched. A name that begins with '.' is considered to be a fully qualified name. The name is always searched for from the topmost package. For example, assume two message types: abc.xyz.SomeMessage xyz.SomeMessage Searching for '.xyz.SomeMessage' relative to 'abc' will resolve to 'xyz.SomeMessage' and not 'abc.xyz.SomeMessage'. For this kind of name, the relative_to parameter is effectively ignored and always set to None. For more information about package name resolution, please see: http://code.google.com/apis/protocolbuffers/docs/proto.html#packages Args: name: Name of definition to find. May be fully qualified or relative name. relative_to: Search for definition relative to message definition or module. None will cause a fully qualified name search. importer: Import function to use for resolving modules. Returns: Enum or Message class definition associated with name. Raises: DefinitionNotFoundError if no definition is found in any search path. """ # Check parameters. if not (relative_to is None or isinstance(relative_to, types.ModuleType) or isinstance(relative_to, type) and issubclass(relative_to, Message)): raise TypeError('relative_to must be None, Message definition or module. ' 'Found: %s' % relative_to) name_path = name.split('.') # Handle absolute path reference. if not name_path[0]: relative_to = None name_path = name_path[1:] def search_path(): """Performs a single iteration searching the path from relative_to. This is the function that searches up the path from a relative object. fully.qualified.object . relative.or.nested.Definition ----------------------------> ^ | this part of search --+ Returns: Message or Enum at the end of name_path, else None. """ next = relative_to for node in name_path: # Look for attribute first. attribute = getattr(next, node, None) if attribute is not None: next = attribute else: # If module, look for sub-module. if next is None or isinstance(next, types.ModuleType): if next is None: module_name = node else: module_name = '%s.%s' % (next.__name__, node) try: fromitem = module_name.split('.')[-1] next = importer(module_name, '', '', [str(fromitem)]) except __HOLE__: return None else: return None if (not isinstance(next, types.ModuleType) and not (isinstance(next, type) and issubclass(next, (Message, Enum)))): return None return next while True: found = search_path() if isinstance(found, type) and issubclass(found, (Enum, Message)): return found else: # Find next relative_to to search against. # # fully.qualified.object . relative.or.nested.Definition # <--------------------- # ^ # | # does this part of search if relative_to is None: # Fully qualified search was done. Nothing found. Fail. raise DefinitionNotFoundError('Could not find definition for %s' % (name,)) else: if isinstance(relative_to, types.ModuleType): # Find parent module. module_path = relative_to.__name__.split('.')[:-1] if not module_path: relative_to = None else: # Should not raise ImportError. If it does... weird and # unexepected. Propagate. relative_to = importer( '.'.join(module_path), '', '', [module_path[-1]]) elif (isinstance(relative_to, type) and issubclass(relative_to, Message)): parent = relative_to.message_definition() if parent is None: last_module_name = relative_to.__module__.split('.')[-1] relative_to = importer( relative_to.__module__, '', '', [last_module_name]) else: relative_to = parent
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/messages.py/find_definition
3,433
def test_lists_plus_nonlists(self): def f(): try: return [] + 10 except __HOLE__: return None self.equivalentEvaluationTestThatHandlesExceptions(f)
TypeError
dataset/ETHPy150Open ufora/ufora/ufora/FORA/python/PurePython/ListTestCases.py/ListTestCases.test_lists_plus_nonlists
3,434
def safe_input(): '''Prompts the user for an integer and return only when a valid value is entered ''' while True: try: guess = int(input(prompt)) return guess except __HOLE__: print("You must enter a valid value.")
ValueError
dataset/ETHPy150Open aroberge/pyproj/guess_number/guess_2.py/safe_input
3,435
def _cachedfunc(cache, makekey, lock): def decorator(func): stats = [0, 0] def wrapper(*args, **kwargs): key = makekey(args, kwargs) with lock: try: result = cache[key] stats[0] += 1 return result except __HOLE__: stats[1] += 1 result = func(*args, **kwargs) with lock: cache[key] = result return result def cache_info(): with lock: hits, misses = stats maxsize = cache.maxsize currsize = cache.currsize return CacheInfo(hits, misses, maxsize, currsize) def cache_clear(): with lock: cache.clear() wrapper.cache_info = cache_info wrapper.cache_clear = cache_clear return functools.update_wrapper(wrapper, func) return decorator
KeyError
dataset/ETHPy150Open PressLabs/gitfs/gitfs/cache/decorators/lru.py/_cachedfunc
3,436
def parse_payload(payload): if not isinstance(payload, str): payload = ' '.join(payload) try: json.loads(payload) except __HOLE__: kv = payload.split(' ', 1) if len(kv) > 1: payload = '{"%s": "%s"}' % (kv[0], kv[1]) else: payload = '%s' % kv[0] return payload
ValueError
dataset/ETHPy150Open 46elks/elkme/elkme/helpers.py/parse_payload
3,437
def test_bad_pack(self): try: session = ss.Session(pack=_bad_packer) except __HOLE__ as e: self.assertIn("could not serialize", str(e)) self.assertIn("don't work", str(e)) else: self.fail("Should have raised ValueError")
ValueError
dataset/ETHPy150Open jupyter/jupyter_client/jupyter_client/tests/test_session.py/TestSession.test_bad_pack
3,438
def test_bad_unpack(self): try: session = ss.Session(unpack=_bad_unpacker) except __HOLE__ as e: self.assertIn("could not handle output", str(e)) self.assertIn("don't work either", str(e)) else: self.fail("Should have raised ValueError")
ValueError
dataset/ETHPy150Open jupyter/jupyter_client/jupyter_client/tests/test_session.py/TestSession.test_bad_unpack
3,439
def test_bad_packer(self): try: session = ss.Session(packer=__name__ + '._bad_packer') except __HOLE__ as e: self.assertIn("could not serialize", str(e)) self.assertIn("don't work", str(e)) else: self.fail("Should have raised ValueError")
ValueError
dataset/ETHPy150Open jupyter/jupyter_client/jupyter_client/tests/test_session.py/TestSession.test_bad_packer
3,440
def test_bad_unpacker(self): try: session = ss.Session(unpacker=__name__ + '._bad_unpacker') except __HOLE__ as e: self.assertIn("could not handle output", str(e)) self.assertIn("don't work either", str(e)) else: self.fail("Should have raised ValueError")
ValueError
dataset/ETHPy150Open jupyter/jupyter_client/jupyter_client/tests/test_session.py/TestSession.test_bad_unpacker
3,441
def to_string(s): """Convert ``bytes`` to ``str``, leaving ``unicode`` unchanged. (This means on Python 2, ``to_string()`` does nothing.) Use this if you need to ``print()`` or log bytes of an unknown encoding, or to parse strings out of bytes of unknown encoding (e.g. a log file). """ if not isinstance(s, string_types + (bytes,)): raise TypeError if PY2 or isinstance(s, str): return s try: return s.decode('utf_8') except __HOLE__: return s.decode('latin_1')
UnicodeDecodeError
dataset/ETHPy150Open Yelp/mrjob/mrjob/py2.py/to_string
3,442
def call_and_wait_tool(command, tool_name, input = '', on_result = None, filename = None, on_line = None, check_enabled = True, **popen_kwargs): tool_enabled = 'enable_{0}'.format(tool_name) if check_enabled and get_setting_async(tool_enabled) != True: return None extended_env = get_extended_env() source_dir = get_source_dir(filename) def mk_result(s): return on_result(s) if on_result else s try: if on_line: p = call_and_wait_with_input(command, input, wait = False, cwd = source_dir, **popen_kwargs) for l in p.stdout: on_line(mk_result(crlf2lf(decode_bytes(l)))) exit_code = p.wait() if exit_code != 0: raise Exception('{0} exited with exit code {1} and stderr: {2}'.format(tool_name, exit_code, p.stderr.read())) else: exit_code, out, err = call_and_wait_with_input(command, input, cwd = source_dir, **popen_kwargs) out = crlf2lf(out) if exit_code != 0: raise Exception('{0} exited with exit code {1} and stderr: {2}'.format(tool_name, exit_code, err)) return mk_result(out) except __HOLE__ as e: if e.errno == errno.ENOENT: output_error_async(sublime.active_window(), "SublimeHaskell: {0} was not found!\n'{1}' is set to False".format(tool_name, tool_enabled)) set_setting_async(tool_enabled, False) else: log('{0} fails with {1}, command: {2}'.format(tool_name, e, command), log_error) return None except Exception as e: log('{0} fails with {1}, command: {2}'.format(tool_name, e, command), log_error) return None
OSError
dataset/ETHPy150Open SublimeHaskell/SublimeHaskell/sublime_haskell_common.py/call_and_wait_tool
3,443
def call_ghcmod_and_wait(arg_list, filename=None, cabal = None): """ Calls ghc-mod with the given arguments. Shows a sublime error message if ghc-mod is not available. """ ghc_opts_args = get_ghc_opts_args(filename, add_package_db = False, cabal = cabal) try: command = ['ghc-mod'] + ghc_opts_args + arg_list # log('running ghc-mod: {0}'.format(command)) # Set cwd to user directory # Otherwise ghc-mod will fail with 'cannot satisfy package...' # Seems, that user directory works well # Current source directory is set with -i argument in get_ghc_opts_args # # When cabal project is available current directory is set to the project root # to avoid troubles with possible template haskell openFile calls ghc_mod_current_dir = get_source_dir(filename) if filename: cabal_project_dir = get_cabal_project_dir_of_file(filename) if cabal_project_dir: ghc_mod_current_dir = cabal_project_dir exit_code, out, err = call_and_wait(command, cwd=ghc_mod_current_dir) if exit_code != 0: raise Exception("%s exited with status %d and stderr: %s" % (' '.join(command), exit_code, err)) return crlf2lf(out) except __HOLE__ as e: if e.errno == errno.ENOENT: output_error_async(sublime.active_window(), "SublimeHaskell: ghc-mod was not found!\n" + "It is used for LANGUAGE and import autocompletions and type inference.\n" + "Try adjusting the 'add_to_PATH' setting.\n" + "You can also turn this off using the 'enable_ghc_mod' setting.") # Re-raise so that calling code doesn't try to work on the `None` return value raise e
OSError
dataset/ETHPy150Open SublimeHaskell/SublimeHaskell/sublime_haskell_common.py/call_ghcmod_and_wait
3,444
def _wrapped_operation(exc_class): def decorator(fn): def inner(*args, **kwargs): try: return fn(*args, **kwargs) except (KeyboardInterrupt, __HOLE__): raise except: wrap_exception(exc_class) return inner return decorator
RuntimeError
dataset/ETHPy150Open coleifer/huey/huey/api.py/Huey._wrapped_operation
3,445
def block_collapse(expr): """Evaluates a block matrix expression >>> from sympy import MatrixSymbol, BlockMatrix, symbols, \ Identity, Matrix, ZeroMatrix, block_collapse >>> n,m,l = symbols('n m l') >>> X = MatrixSymbol('X', n, n) >>> Y = MatrixSymbol('Y', m ,m) >>> Z = MatrixSymbol('Z', n, m) >>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]]) >>> print(B) Matrix([ [X, Z], [0, Y]]) >>> C = BlockMatrix([[Identity(n), Z]]) >>> print(C) Matrix([[I, Z]]) >>> print(block_collapse(C*B)) Matrix([[X, Z*Y + Z]]) """ hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix) rule = exhaust( bottom_up(exhaust(condition(hasbm, typed( {MatAdd: do_one(bc_matadd, bc_block_plus_ident), MatMul: do_one(bc_matmul, bc_dist), Transpose: bc_transpose, Inverse: bc_inverse, BlockMatrix: do_one(bc_unpack, deblock)}))))) result = rule(expr) try: return result.doit() except __HOLE__: return result
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/matrices/expressions/blockmatrix.py/block_collapse
3,446
def run(self): # Get config file location s = sublime.load_settings("WordPressDev.sublime-settings") config_file_location = s.get("wp_config_file") try: # Open up config file with open(config_file_location, 'r') as wp_config: pass window = sublime.active_window() window.open_file(config_file_location) except __HOLE__: # Couldn't open config file, alert user # Open the settings file db_names.append("wp-config file doesn't exist, " + 'check your settings') sublime.status_message("wp-config file doesn't exist, " + 'check your settings')
IOError
dataset/ETHPy150Open huntlyc/Sublime-Wordpress-Dev-Plugin/wordpress_dev.py/WordpressOpenConfigCommand.run
3,447
def extract_wp_db_defs(self): db_names = [] try: with open(self.config_file_location, 'r') as wp_config: file_contents = wp_config.read() wp_config.close() # DB's are defined as define('DB_NAME', 'wp_default'); repatt = '(?:\/\/)?(define\(\'DB_NAME\'.*)' dbs = re.findall(repatt, file_contents) # For each database def we've found, pull out the name # and optional comment to show a nice list to the user for db in dbs: dbrepat = "define\('DB_NAME\',\s+'([^']*)'\);\s*(\/\/(.*))?" match = re.search(dbrepat, db) if match.group(3) is not None: db_names.append("%s - %s" % (match.group(1), match.group(3))) else: db_names.append(match.group(1)) except __HOLE__: # Couldn't open config file, alert user #Open the settings file db_names.append("wp-config file doesn't exist, " + 'check your settings') sublime.status_message("wp-config file doesn't exist, " + 'check your settings') return db_names
IOError
dataset/ETHPy150Open huntlyc/Sublime-Wordpress-Dev-Plugin/wordpress_dev.py/WordpressDbSwitcherCommand.extract_wp_db_defs
3,448
def switch_active_database(self, dbname): try: # open the wordpress config file with open(self.config_file_location, 'r') as wp_config: file_contents = wp_config.read() wp_config.close() # Comment out all uncommented db uncommentedDB = r'([^\/\/])define\(\'DB_NAME\'' commentedDB = r"\1//define('DB_NAME'" file_contents = re.sub(uncommentedDB, commentedDB, file_contents) # Un-comment our our chosen database commentedDB = r'\/\/define\(\'DB_NAME\',\s+\'%s\'' % dbname uncommentedDB = "define('DB_NAME', '%s'" % dbname file_contents = re.sub(commentedDB, uncommentedDB, file_contents) # Overwrite the config file with our new config with open(self.config_file_location, 'w') as wp_config: wp_config.write(file_contents) wp_config.close() message = "Switched database to %s" % dbname sublime.status_message(message) except __HOLE__: # Couldn't open config file, alert user sublime.status_message("wp-config file doesn't exist, " + 'check your settings')
IOError
dataset/ETHPy150Open huntlyc/Sublime-Wordpress-Dev-Plugin/wordpress_dev.py/WordpressDbSwitcherCommand.switch_active_database
3,449
def run(self): s = sublime.load_settings("WordPressDev.sublime-settings") config_file_location = s.get("wp_config_file") try: # open the wordpress config file with open(config_file_location, 'r') as wp_config: file_contents = wp_config.read() wp_config.close() # Toggle the WP_DEBUG value debugpat = "define\('WP_DEBUG\',\s+(true|false)\);" match = re.search(debugpat, file_contents) debugStatus = match.group(1) if debugStatus == 'true': debugStatus = 'false' else: debugStatus = 'true' currentDebugValue = r'define\(\'WP_DEBUG\', (true|false)' newDebugValue = r"define('WP_DEBUG', %s" % debugStatus file_contents = re.sub(currentDebugValue, newDebugValue, file_contents) # Overwrite the config file with our new config with open(config_file_location, 'w') as wp_config: wp_config.write(file_contents) wp_config.close() message = "Toggled WP_DEBUG to %s" % debugStatus sublime.status_message(message) except __HOLE__: # Couldn't open config file, alert user sublime.status_message("wp-config file doesn't exist, " + 'check your settings')
IOError
dataset/ETHPy150Open huntlyc/Sublime-Wordpress-Dev-Plugin/wordpress_dev.py/WordpressDebugToggleCommand.run
3,450
def get(self, path, default=None): """ Return the :class:`Page` object at ``path``, or ``default`` if there is no such page. """ # This may trigger the property. Do it outside of the try block. pages = self._pages try: return pages[path] except __HOLE__: return default
KeyError
dataset/ETHPy150Open SimonSapin/Flask-FlatPages/flask_flatpages/flatpages.py/FlatPages.get
3,451
def reload(self): """Forget all pages. All pages will be reloaded next time they're accessed. """ try: # This will "unshadow" the cached_property. # The property will be re-executed on next access. del self.__dict__['_pages'] except __HOLE__: pass
KeyError
dataset/ETHPy150Open SimonSapin/Flask-FlatPages/flask_flatpages/flatpages.py/FlatPages.reload
3,452
def _smart_html_renderer(self, html_renderer): """ Wrap the rendering function in order to allow the use of rendering functions with differing signatures. We stay backwards compatible by using reflection, i.e. we inspect the given rendering function's signature in order to find out how many arguments the function takes. .. versionchanged:: 0.6 Support for HTML renderer functions with signature ``f(body, flatpages, page)``, where ``page`` is an instance of :class:`Page`. .. versionchanged:: 0.5 Support for HTML renderer functions with signature ``f(body, flatpages)``, where ``flatpages`` is an instance of :class:`FlatPages`. """ def wrapper(page): """Simple wrapper to inspect the HTML renderer function and pass arguments to it based on the number of arguments. * 1 argument -> page body * 2 arguments -> page body, flatpages instance * 3 arguments -> page body, flatpages instance, page instance """ body = page.body try: args_length = len(getargspec(html_renderer).args) except __HOLE__: return html_renderer(body) if args_length == 1: return html_renderer(body) elif args_length == 2: return html_renderer(body, self) elif args_length == 3: return html_renderer(body, self, page) raise ValueError( 'HTML renderer function {0!r} not supported by ' 'Flask-FlatPages, wrong number of arguments: {1}.'. format(html_renderer, args_length) ) return wrapper
TypeError
dataset/ETHPy150Open SimonSapin/Flask-FlatPages/flask_flatpages/flatpages.py/FlatPages._smart_html_renderer
3,453
@classmethod def is_valid_transition(cls, from_value, to_value): """ Will check if to_value is a valid transition from from_value. Returns true if it is a valid transition. :param from_value: Start transition point :param to_value: End transition point :type from_value: int :type to_value: int :return: Success flag :rtype: bool """ try: return from_value == to_value or from_value in cls.transition_origins(to_value) except __HOLE__: return False
KeyError
dataset/ETHPy150Open 5monkeys/django-enumfield/django_enumfield/enum.py/Enum.is_valid_transition
3,454
def get_internal_wsgi_application(): """ Loads and returns the WSGI application as configured by the user in ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout, this will be the ``application`` object in ``projectname/wsgi.py``. This function, and the ``WSGI_APPLICATION`` setting itself, are only useful for Django's internal servers (runserver, runfcgi); external WSGI servers should just be configured to point to the correct application object directly. If settings.WSGI_APPLICATION is not set (is ``None``), we just return whatever ``django.core.wsgi.get_wsgi_application`` returns. """ from django.conf import settings app_path = getattr(settings, 'WSGI_APPLICATION') if app_path is None: return get_wsgi_application() module_name, attr = app_path.rsplit('.', 1) try: mod = import_module(module_name) except ImportError, e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "could not import module '%s': %s" % (app_path, module_name, e)) try: app = getattr(mod, attr) except __HOLE__, e: raise ImproperlyConfigured( "WSGI application '%s' could not be loaded; " "can't find '%s' in module '%s': %s" % (app_path, attr, module_name, e)) return app
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/servers/basehttp.py/get_internal_wsgi_application
3,455
def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except __HOLE__: # mimic os.cpu_count() behavior return None
ValueError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/cpu_count_logical
3,456
@wrap_exceptions def exe(self): try: return os.readlink( "%s/%s/path/a.out" % (self._procfs_path, self.pid)) except __HOLE__: pass # continue and guess the exe name from the cmdline # Will be guessed later from cmdline but we want to explicitly # invoke cmdline here in order to get an AccessDenied # exception if the user has not enough privileges. self.cmdline() return ""
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/Process.exe
3,457
@wrap_exceptions def terminal(self): procfs_path = self._procfs_path hit_enoent = False tty = wrap_exceptions( cext.proc_basic_info(self.pid, self._procfs_path)[0]) if tty != cext.PRNODEV: for x in (0, 1, 2, 255): try: return os.readlink( '%s/%d/path/%d' % (procfs_path, self.pid, x)) except __HOLE__ as err: if err.errno == errno.ENOENT: hit_enoent = True continue raise if hit_enoent: # raise NSP if the process disappeared on us os.stat('%s/%s' % (procfs_path, self.pid))
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/Process.terminal
3,458
@wrap_exceptions def cwd(self): # /proc/PID/path/cwd may not be resolved by readlink() even if # it exists (ls shows it). If that's the case and the process # is still alive return None (we can return None also on BSD). # Reference: http://goo.gl/55XgO procfs_path = self._procfs_path try: return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid)) except __HOLE__ as err: if err.errno == errno.ENOENT: os.stat("%s/%s" % (procfs_path, self.pid)) return None raise
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/Process.cwd
3,459
@wrap_exceptions def open_files(self): retlist = [] hit_enoent = False procfs_path = self._procfs_path pathdir = '%s/%d/path' % (procfs_path, self.pid) for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)): path = os.path.join(pathdir, fd) if os.path.islink(path): try: file = os.readlink(path) except __HOLE__ as err: # ENOENT == file which is gone in the meantime if err.errno == errno.ENOENT: hit_enoent = True continue raise else: if isfile_strict(file): retlist.append(_common.popenfile(file, int(fd))) if hit_enoent: # raise NSP if the process disappeared on us os.stat('%s/%s' % (procfs_path, self.pid)) return retlist
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/Process.open_files
3,460
@wrap_exceptions def memory_maps(self): def toaddr(start, end): return '%s-%s' % (hex(start)[2:].strip('L'), hex(end)[2:].strip('L')) procfs_path = self._procfs_path retlist = [] rawlist = cext.proc_memory_maps(self.pid, procfs_path) hit_enoent = False for item in rawlist: addr, addrsize, perm, name, rss, anon, locked = item addr = toaddr(addr, addrsize) if not name.startswith('['): try: name = os.readlink( '%s/%s/path/%s' % (procfs_path, self.pid, name)) except __HOLE__ as err: if err.errno == errno.ENOENT: # sometimes the link may not be resolved by # readlink() even if it exists (ls shows it). # If that's the case we just return the # unresolved link path. # This seems an incosistency with /proc similar # to: http://goo.gl/55XgO name = '%s/%s/path/%s' % (procfs_path, self.pid, name) hit_enoent = True else: raise retlist.append((addr, perm, name, rss, anon, locked)) if hit_enoent: # raise NSP if the process disappeared on us os.stat('%s/%s' % (procfs_path, self.pid)) return retlist
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_pssunos.py/Process.memory_maps
3,461
def load_macros(self, version): vsbase = r"Software\Microsoft\VisualStudio\%0.1f" % version self.set_macro("VCInstallDir", vsbase + r"\Setup\VC", "productdir") self.set_macro("VSInstallDir", vsbase + r"\Setup\VS", "productdir") net = r"Software\Microsoft\.NETFramework" self.set_macro("FrameworkDir", net, "installroot") try: if version > 7.0: self.set_macro("FrameworkSDKDir", net, "sdkinstallrootv1.1") else: self.set_macro("FrameworkSDKDir", net, "sdkinstallroot") except __HOLE__: raise DistutilsPlatformError, \ ("""Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py.""") p = r"Software\Microsoft\NET Framework Setup\Product" for base in HKEYS: try: h = RegOpenKeyEx(base, p) except RegError: continue key = RegEnumKey(h, 0) d = read_values(base, r"%s\%s" % (p, key)) self.macros["$(FrameworkVersion)"] = d["version"]
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/msvccompiler.py/MacroExpander.load_macros
3,462
def initialize(self): self.__paths = [] if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter self.cc = "cl.exe" self.linker = "link.exe" self.lib = "lib.exe" self.rc = "rc.exe" self.mc = "mc.exe" else: self.__paths = self.get_msvc_paths("path") if len (self.__paths) == 0: raise DistutilsPlatformError, \ ("Python was built with %s, " "and extensions need to be built with the same " "version of the compiler, but it isn't installed." % self.__product) self.cc = self.find_exe("cl.exe") self.linker = self.find_exe("link.exe") self.lib = self.find_exe("lib.exe") self.rc = self.find_exe("rc.exe") # resource compiler self.mc = self.find_exe("mc.exe") # message compiler self.set_path_env_var('lib') self.set_path_env_var('include') # extend the MSVC path with the current path try: for p in string.split(os.environ['path'], ';'): self.__paths.append(p) except __HOLE__: pass self.__paths = normalize_and_reduce_paths(self.__paths) os.environ['path'] = string.join(self.__paths, ';') self.preprocess_options = None if self.__arch == "Intel": self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GX' , '/DNDEBUG'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GX', '/Z7', '/D_DEBUG'] else: # Win64 self.compile_options = [ '/nologo', '/Ox', '/MD', '/W3', '/GS-' , '/DNDEBUG'] self.compile_options_debug = ['/nologo', '/Od', '/MDd', '/W3', '/GS-', '/Z7', '/D_DEBUG'] self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO'] if self.__version >= 7: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG' ] else: self.ldflags_shared_debug = [ '/DLL', '/nologo', '/INCREMENTAL:no', '/pdb:None', '/DEBUG' ] self.ldflags_static = [ '/nologo'] self.initialized = True # -- Worker methods ------------------------------------------------
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/msvccompiler.py/MSVCCompiler.initialize
3,463
def compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): if not self.initialized: self.initialize() macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, depends, extra_postargs) compile_opts = extra_preargs or [] compile_opts.append ('/c') if debug: compile_opts.extend(self.compile_options_debug) else: compile_opts.extend(self.compile_options) for obj in objects: try: src, ext = build[obj] except __HOLE__: continue if debug: # pass the full pathname to MSVC in debug mode, # this allows the debugger to find the source file # without asking the user to browse for it src = os.path.abspath(src) if ext in self._c_extensions: input_opt = "/Tc" + src elif ext in self._cpp_extensions: input_opt = "/Tp" + src elif ext in self._rc_extensions: # compile .RC to .RES file input_opt = src output_opt = "/fo" + obj try: self.spawn ([self.rc] + pp_opts + [output_opt] + [input_opt]) except DistutilsExecError, msg: raise CompileError, msg continue elif ext in self._mc_extensions: # Compile .MC to .RC file to .RES file. # * '-h dir' specifies the directory for the # generated include file # * '-r dir' specifies the target directory of the # generated RC file and the binary message resource # it includes # # For now (since there are no options to change this), # we use the source-directory for the include file and # the build directory for the RC file and message # resources. This works at least for win32all. h_dir = os.path.dirname (src) rc_dir = os.path.dirname (obj) try: # first compile .MC to .RC and .H file self.spawn ([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src]) base, _ = os.path.splitext (os.path.basename (src)) rc_file = os.path.join (rc_dir, base + '.rc') # then compile .RC to .RES file self.spawn ([self.rc] + ["/fo" + obj] + [rc_file]) except DistutilsExecError, msg: raise CompileError, msg continue else: # how to handle this file? raise CompileError ( "Don't know how to compile %s to %s" % \ (src, obj)) output_opt = "/Fo" + obj try: self.spawn ([self.cc] + compile_opts + pp_opts + [input_opt, output_opt] + extra_postargs) except DistutilsExecError, msg: raise CompileError, msg return objects # compile ()
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/msvccompiler.py/MSVCCompiler.compile
3,464
def _adjust_child_weights(self, child_results, zones): """Apply the Scale and Offset values from the Zone definition to adjust the weights returned from the child zones. Alters child_results in place. """ for zone_id, result in child_results: if not result: continue for zone_rec in zones: if zone_rec['id'] != zone_id: continue for item in result: try: offset = zone_rec['weight_offset'] scale = zone_rec['weight_scale'] raw_weight = item['weight'] cooked_weight = offset + scale * raw_weight item['weight'] = cooked_weight item['raw_weight'] = raw_weight except __HOLE__: LOG.exception(_("Bad child zone scaling values " "for Zone: %(zone_id)s") % locals())
KeyError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/scheduler/abstract_scheduler.py/AbstractScheduler._adjust_child_weights
3,465
def xpath_tokenizer(pattern, namespaces=None): for token in xpath_tokenizer_re.findall(pattern): tag = token[1] if tag and tag[0] != "{" and ":" in tag: try: prefix, uri = tag.split(":", 1) if not namespaces: raise KeyError yield token[0], "{%s}%s" % (namespaces[prefix], uri) except __HOLE__: raise SyntaxError("prefix %r not found in prefix map" % prefix) else: yield token
KeyError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/xml/etree/ElementPath.py/xpath_tokenizer
3,466
def prepare_predicate(next, token): # FIXME: replace with real parser!!! refs: # http://effbot.org/zone/simple-iterator-parser.htm # http://javascript.crockford.com/tdop/tdop.html signature = [] predicate = [] while 1: token = next() if token[0] == "]": break if token[0] and token[0][:1] in "'\"": token = "'", token[0][1:-1] signature.append(token[0] or "-") predicate.append(token[1]) signature = "".join(signature) # use signature to determine predicate type if signature == "@-": # [@attribute] predicate key = predicate[1] def select(context, result): for elem in result: if elem.get(key) is not None: yield elem return select if signature == "@-='": # [@attribute='value'] key = predicate[1] value = predicate[-1] def select(context, result): for elem in result: if elem.get(key) == value: yield elem return select if signature == "-" and not re.match("\d+$", predicate[0]): # [tag] tag = predicate[0] def select(context, result): for elem in result: if elem.find(tag) is not None: yield elem return select if signature == "-='" and not re.match("\d+$", predicate[0]): # [tag='value'] tag = predicate[0] value = predicate[-1] def select(context, result): for elem in result: for e in elem.findall(tag): if "".join(e.itertext()) == value: yield elem break return select if signature == "-" or signature == "-()" or signature == "-()-": # [index] or [last()] or [last()-index] if signature == "-": index = int(predicate[0]) - 1 else: if predicate[0] != "last": raise SyntaxError("unsupported function") if signature == "-()-": try: index = int(predicate[2]) - 1 except ValueError: raise SyntaxError("unsupported expression") else: index = -1 def select(context, result): parent_map = get_parent_map(context) for elem in result: try: parent = parent_map[elem] # FIXME: what if the selector is "*" ? elems = list(parent.findall(elem.tag)) if elems[index] is elem: yield elem except (__HOLE__, KeyError): pass return select raise SyntaxError("invalid predicate")
IndexError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/xml/etree/ElementPath.py/prepare_predicate
3,467
def iterfind(elem, path, namespaces=None): # compile selector pattern if path[-1:] == "/": path = path + "*" # implicit all (FIXME: keep this?) try: selector = _cache[path] except KeyError: if len(_cache) > 100: _cache.clear() if path[:1] == "/": raise SyntaxError("cannot use absolute path on element") next = iter(xpath_tokenizer(path, namespaces)).__next__ token = next() selector = [] while 1: try: selector.append(ops[token[0]](next, token)) except StopIteration: raise SyntaxError("invalid path") try: token = next() if token[0] == "/": token = next() except __HOLE__: break _cache[path] = selector # execute selector pattern result = [elem] context = _SelectorContext(elem) for select in selector: result = select(context, result) return result ## # Find first matching object.
StopIteration
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/xml/etree/ElementPath.py/iterfind
3,468
def find(elem, path, namespaces=None): try: return next(iterfind(elem, path, namespaces)) except __HOLE__: return None ## # Find all matching objects.
StopIteration
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/xml/etree/ElementPath.py/find
3,469
def findtext(elem, path, default=None, namespaces=None): try: elem = next(iterfind(elem, path, namespaces)) return elem.text or "" except __HOLE__: return default
StopIteration
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/xml/etree/ElementPath.py/findtext
3,470
def get_output(self, cmd): try: fnull = open(os.devnull, "w") process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=fnull) fnull.close() except (__HOLE__, EnvironmentError): # can't use FileNotFoundError in Python 2 self.logger.debug("Subprocess failed.") return False out, err = process.communicate() return out
OSError
dataset/ETHPy150Open richrd/suplemon/suplemon/modules/linter.py/BaseLint.get_output
3,471
def is_accessible(self): try: return login.current_user.is_admin() except __HOLE__: pass return False
AttributeError
dataset/ETHPy150Open dchaplinsky/unshred-tag/admin/views.py/BaseAdminIndexView.is_accessible
3,472
def updateMessages(self, parameters): """Modifies the messages created by internal validation for each tool parameter. This method is called after internal validation.""" zone_parameter = parameters[0] input_parameter = parameters[1] variable_parameter = parameters[2] output_parameter = parameters[3] type_parameter = parameters[4] ignore_parameter = parameters[5] zonefield_parameter = parameters[6] dataset = None if zone_parameter.value is not None: valid_raster_types = ["RasterLayer", "RasterDataset"] valid_feature_types = ["ShapeFile","FeatureLayer", "FeatureDataset"] desc = arcpy.Describe(zone_parameter.value) if desc.dataType in valid_raster_types: # Check that raster is of an integer data type if not hasattr(desc, 'isInteger') or not desc.isInteger: zone_parameter.setErrorMessage( mds.messages.ZONE_RASTER_NOT_INTEGER.format( zone_parameter.valueAsText)) else: # Fill zone field parameter for raster if hasattr(desc, 'fields'): zonefield_parameter.filter.type = "ValueList" validtypes = ['Integer','SmallInteger','String'] zonefield_parameter.filter.list = [zonefield.name for \ zonefield in desc.fields if zonefield.type in validtypes] else: zonefield_parameter.filter.type = "ValueList" zonefield_parameter.filter.list = ['Value'] elif desc.dataType in valid_feature_types: # Fill zone field parameter for feature class zonefield_parameter.filter.type = "ValueList" validtypes = ['OID','Integer','SmallInteger','String'] zonefield_parameter.filter.list = [zonefield.name for \ zonefield in desc.fields if zonefield.type in validtypes] else: zonefield_parameter.filter.type = "ValueList" zonefield_parameter.filter.list = [] else: # Clear zone field list if no zone dataset specified zonefield_parameter.filter.type = "ValueList" zonefield_parameter.filter.list = [] # Open netCDF dataset if input_parameter.value is not None: try: dataset = mds.netcdf.Dataset(input_parameter.valueAsText, '') except __HOLE__, exception: if "No such file or directory" in str(exception) or \ "Invalid argument" in str(exception): input_parameter.setErrorMessage( mds.messages.INPUT_FILE_DOES_NOT_EXIST.format( input_parameter.valueAsText)) elif "Malformed or inaccessible DAP DDS" in str(exception): input_parameter.setErrorMessage( mds.messages.INPUT_DATASET_URL_MALFORMED.format( input_parameter.valueAsText)) else: input_parameter.setErrorMessage( mds.messages.INPUT_DATASET_GENERIC_ERROR.format( input_parameter.valueAsText, str(exception))) except Exception, exception: input_parameter.setErrorMessage( mds.messages.INPUT_DATASET_GENERIC_ERROR.format( input_parameter.valueAsText, str(exception))) if dataset is not None: # Try to fill variable list with spatial variables var_list = list(dataset.spatial_data_variable_names()) if var_list != []: # If successful, we likely have a gridded dataset. We # will check regular gridding on execution. variable_parameter.filter.type = "ValueList" variable_parameter.filter.list = var_list else: # If unsuccessful, try to fill variable list assuming # dataset is of a discrete geometry type. var_list = list(dataset.data_variable_names()) var_filter = [] for var_item in var_list: var_stat, var_x, var_y = self.get_dependent_variables(dataset, var_item) if (var_stat is not None) and (var_x is not None) and ( var_y is not None): var_filter = self.get_variables_by_dimension(dataset, var_stat) break variable_parameter.filter.type = "ValueList" variable_parameter.filter.list = var_filter else: # Clear variable list if no input dataset specified variable_parameter.filter.type = "ValueList" variable_parameter.filter.list = [] variable_parameter.value = "" # Modify statistic choices so that, if any variable is not of integer # type, categorical statistics are not offered. if variable_parameter.value is not None: if (dataset is not None) and (variable_parameter.value in \ dataset.variable_names()): var = dataset.variable(variable_parameter.value) ispacked = hasattr(var,'scale_factor') or hasattr(var, 'add_offset') flag = ('int' in str(var.dtype)) and not ispacked type_parameter.filter.list = sorted([key for stat in \ self.statistics if flag or not stat[2] for key in \ stat[1].keys()]) else: # When variable parameter is cleared, make all statistics available type_parameter.filter.list = sorted([key for stat in \ self.statistics for key in stat[1].keys()]) # Ensure output file has a .nc extension if output_parameter.value is not None: output_filename = output_parameter.valueAsText if os.path.splitext(output_filename)[1] != ".nc": output_parameter.setErrorMessage( mds.messages.OUTPUT_FILE_EXTENSION_MUST_BE_NC) return
RuntimeError
dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/multidimensional_zonal_statistics.py/MultidimensionalZonalStatistics.updateMessages
3,473
def execute(self, parameters, messages): """The source code of the tool.""" zone_parameter = parameters[0] input_parameter = parameters[1] variable_parameter = parameters[2] output_parameter = parameters[3] type_parameter = parameters[4] ignore_parameter = parameters[5] zonefield_parameter = parameters[6] # Grab the parameter values dataset_name = input_parameter.valueAsText # input netCDF filename output_filename = output_parameter.valueAsText # output filename var_name = variable_parameter.valueAsText # netCDF variable name # Try to open the netCDF dataset try: dataset = mds.netcdf.Dataset(dataset_name,'') except __HOLE__, exception: messages.addErrorMessage(str(exception)) raise arcpy.ExecuteError # Based on same criteria used to populate variable_parameter in # updateMessages(), check if input dataset is gridded or contains # discrete geometries and branch code appropriately. if list(dataset.spatial_data_variable_names()) != []: self.zonal_statistics_for_grid(parameters, messages, dataset) else: self.zonal_statistics_for_discrete(parameters, messages, dataset) return
RuntimeError
dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/multidimensional_zonal_statistics.py/MultidimensionalZonalStatistics.execute
3,474
def get_object(self, queryset=None): """ Returns the object the view is displaying. By default this requires `self.queryset` and a `pk` or `slug` argument in the URLconf, but subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg, None) slug = self.kwargs.get(self.slug_url_kwarg, None) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. elif slug is not None: slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. else: raise AttributeError(u"Generic detail view %s must be called with " u"either an object pk or a slug." % self.__class__.__name__) try: obj = queryset.get() except __HOLE__: raise Http404(_(u"No %(verbose_name)s found matching the query") % {'verbose_name': queryset.model._meta.verbose_name}) return obj
ObjectDoesNotExist
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/views/generic/detail.py/SingleObjectMixin.get_object
3,475
def read_char_no_blocking(): ''' Read a character in nonblocking mode, if no characters are present in the buffer, return an empty string ''' fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) old_flags = fcntl.fcntl(fd, fcntl.F_GETFL) try: tty.setraw(fd, termios.TCSADRAIN) fcntl.fcntl(fd, fcntl.F_SETFL, old_flags | os.O_NONBLOCK) return sys.stdin.read(1) except __HOLE__ as e: ErrorNumber = e[0] # IOError with ErrorNumber 11(35 in Mac) is thrown when there is nothing to read(Resource temporarily unavailable) if (sys.platform.startswith("linux") and ErrorNumber != 11) or (sys.platform == "darwin" and ErrorNumber != 35): raise return "" finally: fcntl.fcntl(fd, fcntl.F_SETFL, old_flags) termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
IOError
dataset/ETHPy150Open pindexis/qfc/qfc/readchar.py/read_char_no_blocking
3,476
def command_schema(self, name=None): ''' Prints current database schema (according sqlalchemy database model):: ./manage.py sqla:schema [name] ''' meta_name = table_name = None if name: if isinstance(self.metadata, MetaData): table_name = name elif '.' in name: meta_name, table_name = name.split('.', 1) else: meta_name = name def _print_metadata_schema(metadata): if table_name is None: for table in metadata.sorted_tables: print(self._schema(table)) else: try: table = metadata.tables[table_name] except __HOLE__: sys.exit('Table {} is not found'.format(name)) print(self._schema(table)) if isinstance(self.metadata, MetaData): _print_metadata_schema(self.metadata) else: for current_meta_name, metadata in self.metadata.items(): if meta_name not in (current_meta_name, None): continue _print_metadata_schema(metadata)
KeyError
dataset/ETHPy150Open SmartTeleMax/iktomi/iktomi/cli/sqla.py/Sqla.command_schema
3,477
def e(self): "Timezone name if available" try: if hasattr(self.data, 'tzinfo') and self.data.tzinfo: # Have to use tzinfo.tzname and not datetime.tzname # because datatime.tzname does not expect Unicode return self.data.tzinfo.tzname(self.data) or "" except __HOLE__: pass return ""
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/utils/dateformat.py/DateFormat.e
3,478
def get_diamond_version(): try: from diamond.version import __VERSION__ return __VERSION__ except __HOLE__: return "Unknown"
ImportError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/diamond/util.py/get_diamond_version
3,479
@classmethod def convert_to_requested_unit_applier(cls, compatibles): def apply_requested_unit(target, _graph_config): tags = target['tags'] try: scale, extra_op = compatibles[tags['unit']] except (KeyError, __HOLE__): # this probably means ES didn't respect the query we made, # or we didn't make it properly, or something? issue a warning # but let things go on warnings.warn("Found a target with unit %r which wasn't in our " "list of compatible units (%r) for this query." % (tags.get('unit'), compatibles.keys()), RuntimeWarning) return if extra_op == 'derive': cls.apply_derivative_to_target(target, scale) else: if scale != 1.0: cls.apply_graphite_function_to_target(target, 'scale', scale) if extra_op == 'integrate': # graphite assumes that anything you integrate is per minute. # hitcount assumes that incoming data is per second. cls.apply_graphite_function_to_target(target, 'hitcount', '1min') cls.apply_graphite_function_to_target(target, 'integral') return apply_requested_unit
ValueError
dataset/ETHPy150Open vimeo/graph-explorer/graph_explorer/query.py/Query.convert_to_requested_unit_applier
3,480
def pipedpath_constructor(loader, node): path = loader.construct_python_str(node) original_path = path package = piped # the path may be an empty string, which should be the root piped package path. if path: paths = path.split(os.path.sep) for i in range(1, len(paths)+1): package_name = '.'.join(['piped'] + paths[:i]) try: any = reflect.namedAny(package_name) except (__HOLE__, reflect.ObjectNotFound) as e: # AttributeErrors may occur if we look a file that has the # same prefix as an existing module or package break # we don't want to start looking into modules: if not is_package(any): break package = any # update the remaining path path = os.path.sep.join(paths[i:]) root = filepath.FilePath(package.__file__).parent() fp = root.preauthChild(util.expand_filepath(path)) # add markers for dumping the configuration fp.origpath = original_path fp.pipedpath = True return fp
AttributeError
dataset/ETHPy150Open foundit/Piped/piped/yamlutil.py/pipedpath_constructor
3,481
def get_screenshot_as_file(self, filename): """ Gets the screenshot of the current window. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. :Usage: driver.get_screenshot_as_file('/Screenshots/foo.png') """ png = self.get_screenshot_as_png() try: with open(filename, 'wb') as f: f.write(png) except __HOLE__: return False finally: del png return True
IOError
dataset/ETHPy150Open apiad/sublime-browser-integration/selenium/webdriver/remote/webdriver.py/WebDriver.get_screenshot_as_file
3,482
def collect_posts(post_types, before_ts, per_page, tag, search=None, include_hidden=False): query = Post.query query = query.options( sqlalchemy.orm.subqueryload(Post.tags), sqlalchemy.orm.subqueryload(Post.mentions), sqlalchemy.orm.subqueryload(Post.reply_contexts), sqlalchemy.orm.subqueryload(Post.repost_contexts), sqlalchemy.orm.subqueryload(Post.like_contexts), sqlalchemy.orm.subqueryload(Post.bookmark_contexts)) if tag: query = query.filter(Post.tags.any(Tag.name == tag)) if not include_hidden: query = query.filter_by(hidden=False) query = query.filter_by(deleted=False, draft=False) if post_types: query = query.filter(Post.post_type.in_(post_types)) if search: query = query.filter( sqlalchemy.func.concat(Post.title, ' ', Post.content) .op('@@')(sqlalchemy.func.plainto_tsquery(search))) try: if before_ts: before_dt = datetime.datetime.strptime(before_ts, BEFORE_TS_FORMAT) before_dt = TIMEZONE.normalize(TIMEZONE.localize(before_dt)) before_dt = before_dt.astimezone(pytz.utc) before_dt = before_dt.replace(tzinfo=None) query = query.filter(Post.published < before_dt) except __HOLE__: current_app.logger.warn('Could not parse before timestamp: %s', before_ts) query = query.order_by(Post.published.desc()) query = query.limit(per_page) posts = query.all() posts = [post for post in posts if check_audience(post)] if posts: last_ts = posts[-1].published last_ts = pytz.utc.localize(last_ts) last_ts = TIMEZONE.normalize(last_ts.astimezone(TIMEZONE))\ .replace(tzinfo=None) view_args = request.view_args.copy() view_args['before_ts'] = last_ts.strftime(BEFORE_TS_FORMAT) for k, v in request.args.items(): view_args[k] = v older = url_for(request.endpoint, **view_args) else: older = None return posts, older
ValueError
dataset/ETHPy150Open kylewm/redwind/redwind/views.py/collect_posts
3,483
def tearDown(self): super(TestAdministrativeFlows, self).tearDown() try: self.tempdir_overrider.Stop() except __HOLE__: pass
AttributeError
dataset/ETHPy150Open google/grr/grr/lib/flows/general/administrative_test.py/TestAdministrativeFlows.tearDown
3,484
def _make_text_safeish(text, fallback_encoding, method='decode'): # The unicode decode here is because sublime converts to unicode inside # insert in such a way that unknown characters will cause errors, which is # distinctly non-ideal... and there's no way to tell what's coming out of # git in output. So... try: unitext = getattr(text, method)('utf-8') except (UnicodeEncodeError, __HOLE__): unitext = getattr(text, method)(fallback_encoding) except AttributeError: # strongly implies we're already unicode, but just in case let's cast # to string unitext = str(text) return unitext
UnicodeDecodeError
dataset/ETHPy150Open kemayo/sublime-text-git/git/__init__.py/_make_text_safeish
3,485
def run(self): # Ignore directories that no longer exist if not os.path.isdir(self.working_dir): return self.command_lock.acquire() output = '' callback = self.on_done try: if self.working_dir != "": os.chdir(self.working_dir) # Windows needs startupinfo in order to start process in background startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW env = os.environ.copy() shell = False if sublime.platform() == 'windows': shell = True if 'HOME' not in env: env[str('HOME')] = str(env['USERPROFILE']) # universal_newlines seems to break `log` in python3 proc = subprocess.Popen(self.command, stdout=self.stdout, stderr=subprocess.STDOUT, stdin=subprocess.PIPE, startupinfo=startupinfo, shell=shell, universal_newlines=False, env=env) output = proc.communicate(self.stdin)[0] if self.error_suppresses_output and proc.returncode is not None and proc.returncode > 0: output = False if not output: output = '' output = _make_text_safeish(output, self.fallback_encoding) except subprocess.CalledProcessError as e: if self.error_suppresses_output: output = '' else: output = e.returncode except __HOLE__ as e: callback = sublime.error_message if e.errno == 2: global _has_warned if not _has_warned: _has_warned = True output = "{cmd} binary could not be found in PATH\n\nConsider using the {cmd_setting}_command setting for the Git plugin\n\nPATH is: {path}".format(cmd=self.command[0], cmd_setting=self.command[0].replace('-', '_'), path=os.environ['PATH']) else: output = e.strerror finally: self.command_lock.release() main_thread(callback, output, **self.kwargs) # A base for all commands
OSError
dataset/ETHPy150Open kemayo/sublime-text-git/git/__init__.py/CommandThread.run
3,486
def get_working_dir(self): file_name = self._active_file_name() if file_name: return os.path.realpath(os.path.dirname(file_name)) try: # handle case with no open folder return self.window.folders()[0] except __HOLE__: return ''
IndexError
dataset/ETHPy150Open kemayo/sublime-text-git/git/__init__.py/GitWindowCommand.get_working_dir
3,487
def _check_tile_metadata(path1, path2): """Given two tile paths, check that the projections, geotransforms and dimensions agree. Returns a message in string msg which, if empty, indicates agreement on the metadata.""" # pylint:disable=too-many-branches # pylint:disable=too-many-statements gdal.UseExceptions() msg = "" data1 = None data2 = None # Open the tile files try: dset1 = gdal.Open(path1) data1 = dset1.ReadAsArray() except RuntimeError: msg += "ERROR:\tBenchmark tile %s does not exist\n" %path1 dset1 = None data1 = None try: dset2 = gdal.Open(path2) data2 = dset2.ReadAsArray() except RuntimeError: msg += "ERROR:\tTest Ingest tile %s does not exist\n" %path2 dset2 = None data2 = None # Check geotransforms present try: geotransform1 = dset1.GetGeoTransform() except RuntimeError: if dset1: # file exists but geotransform not present msg += "\tError:\tGeotransform for %s not present\n" %path1 geotransform1 = None try: geotransform2 = dset2.GetGeoTransform() except RuntimeError: if dset2: # file exists but geotransform not present msg += "\tError:\tGeotransform for %s not present\n" %path2 geotransform2 = None # Check geotransforms equal if geotransform1 and geotransform2: if geotransform1 != geotransform2: msg += "\tError:\tGeotransforms disagree for %s and %s\n"\ %(path1, path2) # Check projections present try: projection1 = dset1.GetProjection() except RuntimeError: if dset1: # file exists but projections not present msg += "\tError:\tProjection for %s not present\n" %path1 projection1 = None try: projection2 = dset2.GetProjection() except __HOLE__: if dset2: # file exists but projection not present msg += "\tError:\tProjection for %s not present\n" %path2 projection2 = None # Check projections equal if projection1 and projection2: if projection1 != projection2: msg += "\tError:\tProjections disagree for %s and %s\n"\ %(path1, path2) # Check the dimensions of the arrays if dset1 and dset2: if data1.shape != data2.shape: msg += "\tError:\tDimensions of arrays disagree for %s and %s\n" \ %(path1, path2) if dset1 and data1 is None: msg += "\tError:\tArray data for %s not present\n" %path1 if dset2 and data2 is None: msg += "\tError:\tArray data for %s not present\n" %path2 return (data1, data2, msg)
RuntimeError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/tilecompare.py/_check_tile_metadata
3,488
def action_task_saved(sender, instance, created, **kwargs): if created: instance.project.create_action("created new task", author=instance.editor, action_object=instance) else: try: last_rev = instance.taskrevision_set\ .select_related('status')\ .order_by('-created_at')[1] if instance.status.is_resolved and not last_rev.status.is_resolved: verb = "resolved" elif not instance.status.is_resolved and last_rev.status.is_resolved: verb = "reopened" else: verb = "updated" instance.project.create_action(verb, action_object=instance, author=instance.editor) except __HOLE__: pass
IndexError
dataset/ETHPy150Open lukaszb/django-projector/projector/actions.py/action_task_saved
3,489
def get_etree(): ''' Returns an elementtree implementation. Searches for `lxml.etree`, then `xml.etree.cElementTree`, then `xml.etree.ElementTree`. ''' global _etree if _etree is None: try: from lxml import etree _etree = etree except ImportError: try: from xml.etree import cElementTree _etree = cElementTree except ImportError: try: from xml.etree import ElementTree _etree = ElementTree except __HOLE__: pass return _etree
ImportError
dataset/ETHPy150Open joelverhagen/flask-rauth/flask_rauth.py/get_etree
3,490
def __init__(self, filename): try: self.fp = open(filename, "rb") except __HOLE__ as err: Console.error("Could not open file: %s" % filename) raise err
IOError
dataset/ETHPy150Open zynga/jasy/jasy/asset/ImageInfo.py/ImgFile.__init__
3,491
def size(self): self.fp.seek(0) self.fp.read(2) b = self.fp.read(1) try: while (b and ord(b) != 0xDA): while (ord(b) != 0xFF): b = self.fp.read(1) while (ord(b) == 0xFF): b = self.fp.read(1) if (ord(b) >= 0xC0 and ord(b) <= 0xC3): self.fp.read(3) h, w = struct.unpack(">HH", self.fp.read(4)) break else: self.fp.read(int(struct.unpack(">H", self.fp.read(2))[0])-2) b = self.fp.read(1) width = int(w) height = int(h) return (width, height) except struct.error: pass except __HOLE__: pass
ValueError
dataset/ETHPy150Open zynga/jasy/jasy/asset/ImageInfo.py/JpegFile.size
3,492
def get_xy_rotation_and_scale(header): """ CREDIT: See IDL code at http://www.astro.washington.edu/docs/idl/cgi-bin/getpro/library32.html?GETROT """ def calc_from_cd(cd1_1, cd1_2, cd2_1, cd2_2): # TODO: Check if first coordinate in CTYPE is latitude # if (ctype EQ 'DEC-') or (strmid(ctype, 1) EQ 'LAT') then $ # cd = reverse(cd,1) det = cd1_1*cd2_2 - cd1_2*cd2_1 if det < 0: sgn = -1 else: sgn = 1 ## if det > 0: ## raise ValueError("Astrometry is for a right-handed coordinate system") if (cd2_1 == 0.0) or (cd1_2 == 0.0): # Unrotated coordinates? xrot = 0.0 yrot = 0.0 cdelt1 = cd1_1 cdelt2 = cd2_2 else: xrot = math.atan2(sgn * cd1_2, sgn * cd1_1) yrot = math.atan2(-cd2_1, cd2_2) cdelt1 = sgn * math.sqrt(cd1_1**2 + cd1_2**2) cdelt2 = math.sqrt(cd1_1**2 + cd2_1**2) return xrot, yrot, cdelt1, cdelt2 def calc_from_crota(): try: crota1 = float(header['CROTA1']) xrot = crota1 except __HOLE__: xrot = None try: crota2 = float(header['CROTA2']) yrot = crota2 except KeyError: yrot = 0.0 if xrot is None: xrot = yrot cdelt1 = float(header.get('CDELT1', 1.0)) cdelt2 = float(header.get('CDELT2', 1.0)) return xrot, yrot, cdelt1, cdelt2 # 1st, check for presence of PC matrix try: pc1_1 = header['PC1_1'] pc1_2 = header['PC1_2'] pc2_1 = header['PC2_1'] pc2_2 = header['PC2_2'] cdelt1 = float(header['CDELT1']) cdelt2 = float(header['CDELT2']) cd1_1, cd1_2 = pc1_1 * cdelt1, pc1_2 * cdelt1 cd2_1, cd2_2 = pc2_1 * cdelt2, pc2_2 * cdelt2 xrot, yrot, cdelt1p, cdelt2p = calc_from_cd(pc1_1, pc1_2, pc2_1, pc2_2) except KeyError: # 2nd, check for presence of CD matrix try: cd1_1 = header['CD1_1'] cd1_2 = header['CD1_2'] cd2_1 = header['CD2_1'] cd2_2 = header['CD2_2'] xrot, yrot, cdelt1, cdelt2 = calc_from_cd(cd1_1, cd1_2, cd2_1, cd2_2) except KeyError: # 3rd, check for presence of CROTA keyword # (or default is north=up) xrot, yrot, cdelt1, cdelt2 = calc_from_crota() xrot, yrot = math.degrees(xrot), math.degrees(yrot) return ((xrot, yrot), (cdelt1, cdelt2))
KeyError
dataset/ETHPy150Open ejeschke/ginga/ginga/util/wcs.py/get_xy_rotation_and_scale
3,493
@patch("sys.stdout") def test_clt_fetch_dlo(self, mock_stdout): clt = self.client mgr = clt._manager cont = self.container ctype = "text/fake" num_objs = random.randint(1, 3) objs = [StorageObject(cont.object_manager, {"name": "obj%s" % num, "content_type": ctype, "bytes": 42}) for num in range(num_objs)] clt.get_container_objects = Mock(return_value=objs) name = utils.random_unicode() clt.method_get = Mock(side_effect=[(None, "aaa"), (None, "bbb"), (None, "ccc"), (None, "")] * num_objs) def fake_get(obj_name): return [obj for obj in objs if obj.name == obj_name][0] cont.object_manager.get = Mock(side_effect=fake_get) job = clt.fetch_dlo(cont, name, chunk_size=None) self.assertTrue(isinstance(job, list)) self.assertEqual(len(job), num_objs) for name, chunker in job: txt = "" chunker.interval = 2 chunker.verbose = True while True: try: txt += chunker.read() except __HOLE__: break self.assertEqual(txt, "aaabbbccc")
StopIteration
dataset/ETHPy150Open rackspace/pyrax/tests/unit/test_object_storage.py/ObjectStorageTest.test_clt_fetch_dlo
3,494
@verbose def read_ica(fname): """Restore ICA solution from fif file. Parameters ---------- fname : str Absolute path to fif file containing ICA matrices. The file name should end with -ica.fif or -ica.fif.gz. Returns ------- ica : instance of ICA The ICA estimator. """ check_fname(fname, 'ICA', ('-ica.fif', '-ica.fif.gz')) logger.info('Reading %s ...' % fname) fid, tree, _ = fiff_open(fname) try: # we used to store bads that weren't part of the info... info, meas = read_meas_info(fid, tree, clean_bads=True) except __HOLE__: logger.info('Could not find the measurement info. \n' 'Functionality requiring the info won\'t be' ' available.') info = None else: info['filename'] = fname ica_data = dir_tree_find(tree, FIFF.FIFFB_MNE_ICA) if len(ica_data) == 0: ica_data = dir_tree_find(tree, 123) # Constant 123 Used before v 0.11 if len(ica_data) == 0: fid.close() raise ValueError('Could not find ICA data') my_ica_data = ica_data[0] for d in my_ica_data['directory']: kind = d.kind pos = d.pos if kind == FIFF.FIFF_MNE_ICA_INTERFACE_PARAMS: tag = read_tag(fid, pos) ica_init = tag.data elif kind == FIFF.FIFF_MNE_ROW_NAMES: tag = read_tag(fid, pos) ch_names = tag.data elif kind == FIFF.FIFF_MNE_ICA_WHITENER: tag = read_tag(fid, pos) pre_whitener = tag.data elif kind == FIFF.FIFF_MNE_ICA_PCA_COMPONENTS: tag = read_tag(fid, pos) pca_components = tag.data elif kind == FIFF.FIFF_MNE_ICA_PCA_EXPLAINED_VAR: tag = read_tag(fid, pos) pca_explained_variance = tag.data elif kind == FIFF.FIFF_MNE_ICA_PCA_MEAN: tag = read_tag(fid, pos) pca_mean = tag.data elif kind == FIFF.FIFF_MNE_ICA_MATRIX: tag = read_tag(fid, pos) unmixing_matrix = tag.data elif kind == FIFF.FIFF_MNE_ICA_BADS: tag = read_tag(fid, pos) exclude = tag.data elif kind == FIFF.FIFF_MNE_ICA_MISC_PARAMS: tag = read_tag(fid, pos) ica_misc = tag.data fid.close() ica_init, ica_misc = [_deserialize(k) for k in (ica_init, ica_misc)] current_fit = ica_init.pop('current_fit') if ica_init['noise_cov'] == Covariance.__name__: logger.info('Reading whitener drawn from noise covariance ...') logger.info('Now restoring ICA solution ...') # make sure dtypes are np.float64 to satisfy fast_dot def f(x): return x.astype(np.float64) ica_init = dict((k, v) for k, v in ica_init.items() if k in _get_args(ICA.__init__)) ica = ICA(**ica_init) ica.current_fit = current_fit ica.ch_names = ch_names.split(':') ica._pre_whitener = f(pre_whitener) ica.pca_mean_ = f(pca_mean) ica.pca_components_ = f(pca_components) ica.n_components_ = unmixing_matrix.shape[0] ica.pca_explained_variance_ = f(pca_explained_variance) ica.unmixing_matrix_ = f(unmixing_matrix) ica.mixing_matrix_ = linalg.pinv(ica.unmixing_matrix_) ica.exclude = [] if exclude is None else list(exclude) ica.info = info if 'n_samples_' in ica_misc: ica.n_samples_ = ica_misc['n_samples_'] if 'labels_' in ica_misc: ica.labels_ = ica_misc['labels_'] logger.info('Ready.') return ica
ValueError
dataset/ETHPy150Open mne-tools/mne-python/mne/preprocessing/ica.py/read_ica
3,495
def create(config_id, raw_configs, set_defaults=False): sections = {} all_values = defaultdict(set) def init_section(section_name, section_dto=None): try: return sections[section_name] except __HOLE__: section_dto = section_dto or {} section_dto['dbo_id'] = '{}:{}'.format(config_id, section_name) section = create_object(ConfigSection, section_dto) sections[section_name] = section return section def add_raw(raw_config): for section_name, section_dto in raw_config.pop('sections', {}).items(): init_section(section_name, section_dto) for section_name, settings in raw_config.items(): section = init_section(section_name) setting_map = {setting.name: setting for setting in section.settings} for raw_setting in settings: new_setting = Setting().hydrate(raw_setting) if set_defaults: new_setting.default = new_setting.value try: existing = setting_map[new_setting.name] warn("Setting {} with value {} overwritten by {}", setting.name, existing.value, setting.value) except KeyError: pass setting_map[new_setting.name] = new_setting all_values[new_setting.name].add(section_name) section.settings = setting_map.values() save_object(section) for rc in raw_configs: add_raw(rc) for setting_name, section_names in all_values.items(): if len(section_names) > 1: warn("Setting name {} found in multiple sections: {}", setting_name, ' '.join(section_names)) return create_object(Config, {'dbo_id': config_id})
KeyError
dataset/ETHPy150Open genzgd/Lampost-Mud/lampost/gameops/dbconfig.py/create
3,496
def real_root(arg, n=None): """Return the real nth-root of arg if possible. If n is omitted then all instances of (-n)**(1/odd) will be changed to -n**(1/odd); this will only create a real root of a principle root -- the presence of other factors may cause the result to not be real. Examples ======== >>> from sympy import root, real_root, Rational >>> from sympy.abc import x, n >>> real_root(-8, 3) -2 >>> root(-8, 3) 2*(-1)**(1/3) >>> real_root(_) -2 If one creates a non-principle root and applies real_root, the result will not be real (so use with caution): >>> root(-8, 3, 2) -2*(-1)**(2/3) >>> real_root(_) -2*(-1)**(2/3) See Also ======== sympy.polys.rootoftools.rootof sympy.core.power.integer_nthroot root, sqrt """ from sympy import im, Piecewise if n is not None: try: n = as_int(n) arg = sympify(arg) if arg.is_positive or arg.is_negative: rv = root(arg, n) else: raise ValueError except __HOLE__: return root(arg, n)*Piecewise( (S.One, ~Equality(im(arg), 0)), (Pow(S.NegativeOne, S.One/n)**(2*floor(n/2)), And( Equality(n % 2, 1), arg < 0)), (S.One, True)) else: rv = sympify(arg) n1pow = Transform(lambda x: -(-x.base)**x.exp, lambda x: x.is_Pow and x.base.is_negative and x.exp.is_Rational and x.exp.p == 1 and x.exp.q % 2) return rv.xreplace(n1pow) ############################################################################### ############################# MINIMUM and MAXIMUM ############################# ###############################################################################
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/functions/elementary/miscellaneous.py/real_root
3,497
@register.tag def get_photo(parser, token): """Get a single photo from the photologue library and return the img tag to display it. Takes 3 args: - the photo to display. This can be either the slug of a photo, or a variable that holds either a photo instance or a integer (photo id) - the photosize to use. - a CSS class to apply to the img tag. """ try: # Split the contents of the tag, i.e. tag name + argument. tag_name, photo, photosize, css_class = token.split_contents() except __HOLE__: msg = '%r tag requires 3 arguments' % token.contents[0] raise template.TemplateSyntaxError(msg) return PhotoNode(photo, photosize[1:-1], css_class[1:-1])
ValueError
dataset/ETHPy150Open jdriscoll/django-photologue/photologue/templatetags/photologue_tags.py/get_photo
3,498
@register.tag def get_rotating_photo(parser, token): """Pick at random a photo from a given photologue gallery and return the img tag to display it. Takes 3 args: - the gallery to pick a photo from. This can be either the slug of a gallery, or a variable that holds either a gallery instance or a gallery slug. - the photosize to use. - a CSS class to apply to the img tag. """ try: # Split the contents of the tag, i.e. tag name + argument. tag_name, gallery, photosize, css_class = token.split_contents() except __HOLE__: msg = '%r tag requires 3 arguments' % token.contents[0] raise template.TemplateSyntaxError(msg) return PhotoGalleryNode(gallery, photosize[1:-1], css_class[1:-1])
ValueError
dataset/ETHPy150Open jdriscoll/django-photologue/photologue/templatetags/photologue_tags.py/get_rotating_photo
3,499
def iter_first(sequence): """Get the first element from an iterable or raise a ValueError if the iterator generates no values. """ it = iter(sequence) try: if PY3: return next(it) else: return it.next() except __HOLE__: raise ValueError() # Exceptions.
StopIteration
dataset/ETHPy150Open beetbox/beets/beets/util/confit.py/iter_first