Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,600
def initial_context(self, request, *args, **kwargs): context = super(ZoomableView, self).initial_context(request, *args, **kwargs) try: zoom = int(request.GET['zoom']) except (KeyError, __HOLE__): zoom = self.default_zoom else: zoom = min(max(10, zoom), 18) context['zoom'] = zoom context.update({ 'zoom_controls': True, }) return context
ValueError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/ZoomableView.initial_context
8,601
def ReverseView(request): from molly.auth.views import SecureView try: name = request.GET['name'] args = request.GET.getlist('arg') path = reverse(name, args=args) view, view_args, view_kwargs = resolve(path) is_secure = isinstance(view, SecureView) and not settings.DEBUG_SECURE return HttpResponse("http%s://%s%s" % ( 's' if is_secure else '', request.META['HTTP_HOST'], path, ), mimetype='text/plain') except NoReverseMatch: raise Http404 except __HOLE__: return HttpResponseBadRequest()
KeyError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/views.py/ReverseView
8,602
def Load(self, kind, data): """Parses CSV data, uses a Loader to convert to entities, and stores them. On error, fails fast. Returns a "bad request" HTTP response code and includes the traceback in the output. Args: kind: a string containing the entity kind that this loader handles data: a string containing the CSV data to load Returns: tuple (response code, output) where: response code: integer HTTP response code to return output: string containing the HTTP response body """ data = data.encode('utf-8') Validate(kind, basestring) Validate(data, basestring) output = [] try: loader = Loader.RegisteredLoaders()[kind] except __HOLE__: output.append('Error: no Loader defined for kind %s.' % kind) return (httplib.BAD_REQUEST, ''.join(output)) buffer = StringIO.StringIO(data) reader = csv.reader(buffer, skipinitialspace=True) try: csv.field_size_limit(800000) except AttributeError: pass return self.LoadEntities(self.IterRows(reader), loader)
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/ext/bulkload/__init__.py/BulkLoad.Load
8,603
def parse_isotime(timestr): """Parse time from ISO 8601 format.""" try: return iso8601.parse_date(timestr) except iso8601.ParseError as e: raise ValueError(six.text_type(e)) except __HOLE__ as e: raise ValueError(six.text_type(e))
TypeError
dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/parse_isotime
8,604
def utcnow(): """Overridable version of utils.utcnow.""" if utcnow.override_time: try: return utcnow.override_time.pop(0) except __HOLE__: return utcnow.override_time return datetime.datetime.utcnow()
AttributeError
dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/utcnow
8,605
def advance_time_delta(timedelta): """Advance overridden time using a datetime.timedelta.""" assert(utcnow.override_time is not None) try: for dt in utcnow.override_time: dt += timedelta except __HOLE__: utcnow.override_time += timedelta
TypeError
dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/advance_time_delta
8,606
def total_seconds(delta): """Return the total seconds of datetime.timedelta object. Compute total seconds of datetime.timedelta, datetime.timedelta doesn't have method total_seconds in Python2.6, calculate it manually. """ try: return delta.total_seconds() except __HOLE__: return ((delta.days * 24 * 3600) + delta.seconds + float(delta.microseconds) / (10 ** 6))
AttributeError
dataset/ETHPy150Open openstack/python-monascaclient/monascaclient/openstack/common/timeutils.py/total_seconds
8,607
def update(self, request, *args, **kwargs): "Reply to message" if request.data is None: return rc.BAD_REQUEST pkfield = kwargs.get(self.model._meta.pk.name) or request.data.get( self.model._meta.pk.name) if not pkfield: return rc.BAD_REQUEST user = request.user.profile try: message = self.model.objects.get(pk=pkfield) except __HOLE__: return rc.NOT_FOUND if not user.has_permission(message): return rc.FORBIDDEN reply = Message() reply.author = user.get_contact() if not reply.author: return rc.FORBIDDEN reply.reply_to = message form = MessageReplyForm( user, message.stream_id, message, request.data, instance=reply) if form.is_valid(): reply = form.save() reply.set_user_from_request(request) # Add author to recipients reply.recipients.add(reply.author) message.read_by.clear() try: # if email entered create contact and add to recipients if 'multicomplete_recipients' in request.POST and request.POST['multicomplete_recipients']: try: conf = ModuleSetting.get_for_module( 'treeio.messaging', 'default_contact_type')[0] default_contact_type = ContactType.objects.get( pk=long(conf.value)) except Exception: default_contact_type = None emails = request.POST[ 'multicomplete_recipients'].split(',') for email in emails: emailstr = unicode(email).strip() if re.match('[a-zA-Z0-9+_\-\.]+@[0-9a-zA-Z][.-0-9a-zA-Z]*.[a-zA-Z]+', emailstr): contact, created = Contact.get_or_create_by_email( emailstr, contact_type=default_contact_type) reply.recipients.add(contact) if created: contact.set_user_from_request(request) except: pass # Add each recipient of the reply to the original message for recipient in reply.recipients.all(): message.recipients.add(recipient) # send email to all recipients reply.send_email() return reply else: self.status = 400 return form.errors
ObjectDoesNotExist
dataset/ETHPy150Open treeio/treeio/treeio/messaging/api/handlers.py/MessageHandler.update
8,608
def __init__(self, vcs_project, path, locales=None): """ Load the resource file for each enabled locale and store its translations in VCSEntity instances. """ from pontoon.base.models import Locale from pontoon.sync import formats # Avoid circular import. self.vcs_project = vcs_project self.path = path self.locales = locales or [] self.files = {} self.entities = {} # Create entities using resources from the source directory, source_resource_path = os.path.join(vcs_project.source_directory_path(), self.path) source_resource_path = relative_source_path(source_resource_path) source_resource_file = formats.parse(source_resource_path, locale=Locale.objects.get(code='en-US')) for index, translation in enumerate(source_resource_file.translations): vcs_entity = VCSEntity( resource=self, key=translation.key, string=translation.source_string, string_plural=translation.source_string_plural, comments=translation.comments, source=translation.source, order=translation.order or index ) self.entities[vcs_entity.key] = vcs_entity # Fill in translations from the locale resources. for locale in locales: resource_path = os.path.join( locale_directory_path(vcs_project.checkout_path, locale.code), self.path ) try: resource_file = formats.parse(resource_path, source_resource_path, locale) except (IOError, ParseError): continue # File doesn't exist or is invalid, let's move on self.files[locale] = resource_file for translation in resource_file.translations: try: self.entities[translation.key].translations[locale.code] = translation except __HOLE__: # If the source is missing an entity, we consider it # deleted and don't add it. pass
KeyError
dataset/ETHPy150Open mozilla/pontoon/pontoon/sync/vcs/models.py/VCSResource.__init__
8,609
def default_patch_view(resource, request): try: data = request.json_body except __HOLE__: request.response.status_int = 400 return {'message': 'No JSON data provided.'} resource.validate(data, partial=True) resource.update_from_dict(data, replace=False) return resource.to_dict()
ValueError
dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_patch_view
8,610
def default_put_view(resource, request): try: data = request.json_body except __HOLE__: request.response.status_int = 400 return {'message': 'No JSON data provided.'} resource.validate(data, partial=False) resource.update_from_dict(data, replace=True) return resource.to_dict()
ValueError
dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_put_view
8,611
def default_post_view(resource, request): try: data = request.json_body except __HOLE__: request.response.status_int = 400 return {'message': 'No JSON data provided.'} resource.validate_child(data) request.response.status_int = 201 return resource.add_child(data)
ValueError
dataset/ETHPy150Open wichert/rest_toolkit/src/rest_toolkit/views.py/default_post_view
8,612
def shortcut(request, content_type_id, object_id): """ Redirect to an object's page based on a content-type ID and an object ID. """ # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) if not content_type.model_class(): raise http.Http404(_("Content type %(ct_id)s object has no associated model") % {'ct_id': content_type_id}) obj = content_type.get_object_for_this_type(pk=object_id) except (ObjectDoesNotExist, __HOLE__): raise http.Http404(_("Content type %(ct_id)s object %(obj_id)s doesn't exist") % {'ct_id': content_type_id, 'obj_id': object_id}) try: get_absolute_url = obj.get_absolute_url except AttributeError: raise http.Http404(_("%(ct_name)s objects don't have a get_absolute_url() method") % {'ct_name': content_type.name}) absurl = get_absolute_url() # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith('http://') or absurl.startswith('https://'): return http.HttpResponseRedirect(absurl) # Otherwise, we need to introspect the object's relationships for a # relation to the Site object object_domain = None if Site._meta.installed: opts = obj._meta # First, look for an many-to-many relationship to Site. for field in opts.many_to_many: if field.rel.to is Site: try: # Caveat: In the case of multiple related Sites, this just # selects the *first* one, which is arbitrary. object_domain = getattr(obj, field.name).all()[0].domain except IndexError: pass if object_domain is not None: break # Next, look for a many-to-one relationship to Site. if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domain except Site.DoesNotExist: pass if object_domain is not None: break # Fall back to the current site (if possible). if object_domain is None: try: object_domain = get_current_site(request).domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it. Otherwise, fall back # to whatever get_absolute_url() returned. if object_domain is not None: protocol = 'https' if request.is_secure() else 'http' return http.HttpResponseRedirect('%s://%s%s' % (protocol, object_domain, absurl)) else: return http.HttpResponseRedirect(absurl)
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/contenttypes/views.py/shortcut
8,613
def heap_merged(items_lists, combiner): heap = [] def pushback(it): try: k,v = it.next() # put i before value, so do not compare the value heapq.heappush(heap, (k, i, v)) except __HOLE__: pass for i, it in enumerate(items_lists): if isinstance(it, list): items_lists[i] = it = (k for k in it) pushback(it) if not heap: return last_key, i, last_value = heapq.heappop(heap) pushback(items_lists[i]) while heap: k, i, v = heapq.heappop(heap) if k != last_key: yield last_key, last_value last_key, last_value = k, v else: last_value = combiner(last_value, v) pushback(items_lists[i]) yield last_key, last_value
StopIteration
dataset/ETHPy150Open douban/dpark/dpark/shuffle.py/heap_merged
8,614
def _configure_section(self, f, section, items): target = getattr(self.module, section, None) if target is None: # silently ignore self._handle_missing_section(section, f) notify('Configuring section "{}" from "{}"'.format(section, f)) for k, v in items: try: setattr(target, k, v) except __HOLE__: self._handle_missing_key(section, k, f)
AttributeError
dataset/ETHPy150Open EverythingMe/click-config/click_config/__init__.py/Parser._configure_section
8,615
def _calculate(self, data): x = pop(data, 'x', None) y = pop(data, 'y', None) # intercept and slope may be one of: # - aesthetics to geom_abline or # - parameter settings to stat_abline slope = pop(data, 'slope', self.params['slope']) intercept = pop(data, 'intercept', self.params['intercept']) if hasattr(slope, '__call__'): if x is None or y is None: raise GgplotError( 'To compute the slope, x & y aesthetics are needed') try: slope = slope(x, y) except TypeError as err: raise GgplotError(*err.args) if hasattr(intercept, '__call__'): if x is None or y is None: raise GgplotError( 'To compute the intercept, x & y aesthetics are needed') try: intercept = intercept(x, y) except __HOLE__ as err: raise GgplotError(*err.args) try: n = len(slope) except TypeError: n = 1 try: _n = len(intercept) except TypeError: _n = 1 if n != _n: raise GgplotError( 'Specified {} slopes but {} intercepts'.format(n, _n)) slope = make_iterable(slope) intercept = make_iterable(intercept) new_data = pd.DataFrame({'slope': slope, 'intercept': intercept}) # Copy the other aesthetics into the new dataframe n = len(slope) for ae in data: new_data[ae] = make_iterable_ntimes(data[ae].iloc[0], n) return new_data
TypeError
dataset/ETHPy150Open yhat/ggplot/ggplot/stats/stat_abline.py/stat_abline._calculate
8,616
def get_instance_port(self, instance_id): """Returns the port of the HTTP server for an instance.""" try: instance_id = int(instance_id) except __HOLE__: raise request_info.InvalidInstanceIdError() with self._condition: if 0 <= instance_id < len(self._instances): wsgi_servr = self._wsgi_servers[instance_id] else: raise request_info.InvalidInstanceIdError() return wsgi_servr.port
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/ManualScalingServer.get_instance_port
8,617
def get_instance(self, instance_id): """Returns the instance with the provided instance ID.""" try: with self._condition: return self._instances[int(instance_id)] except (ValueError, __HOLE__): raise request_info.InvalidInstanceIdError()
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/ManualScalingServer.get_instance
8,618
def get_instance_port(self, instance_id): """Returns the port of the HTTP server for an instance.""" try: instance_id = int(instance_id) except __HOLE__: raise request_info.InvalidInstanceIdError() with self._condition: if 0 <= instance_id < len(self._instances): wsgi_servr = self._wsgi_servers[instance_id] else: raise request_info.InvalidInstanceIdError() return wsgi_servr.port
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/BasicScalingServer.get_instance_port
8,619
def get_instance(self, instance_id): """Returns the instance with the provided instance ID.""" try: with self._condition: return self._instances[int(instance_id)] except (ValueError, __HOLE__): raise request_info.InvalidInstanceIdError()
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/server.py/BasicScalingServer.get_instance
8,620
def add_boundaries_for_layer(self, config, layer, bset, database): # Get spatial reference system for the postgis geometry field geometry_field = Boundary._meta.get_field_by_name(GEOMETRY_COLUMN)[0] SpatialRefSys = connections[database].ops.spatial_ref_sys() db_srs = SpatialRefSys.objects.using(database).get( srid=geometry_field.srid).srs if 'srid' in config and config['srid']: layer_srs = SpatialRefSys.objects.get(srid=config['srid']).srs else: layer_srs = layer.srs # Simplification can be configured but default is to create simplified # geometry field by collapsing points within 1/1000th of a degree. # For reference, Chicago is at approx. 42 degrees latitude this works # out to a margin of roughly 80 meters latitude and 112 meters # longitude for Chicago area. simplification = config.get('simplification', 0.0001) # Create a convertor to turn the source data into transformer = CoordTransform(layer_srs, db_srs) for feature in layer: log.debug("Processing boundary %s" % feature) # Transform the geometry to the correct SRS geometry = self.polygon_to_multipolygon(feature.geom) geometry.transform(transformer) # Preserve topology prevents a shape from ever crossing over # itself. simple_geometry = geometry.geos.simplify(simplification, preserve_topology=True) # Conversion may force multipolygons back to being polygons simple_geometry = self.polygon_to_multipolygon(simple_geometry.ogr) # Extract metadata into a dictionary metadata = {} for field in layer.fields: # Decode string fields using encoding specified in definitions # config if config['encoding'] != '': try: metadata[field] = feature.get(field).decode( config['encoding']) # Only strings will be decoded, get value in normal way if # int etc. except __HOLE__: metadata[field] = feature.get(field) else: metadata[field] = feature.get(field) external_id = config['ider'](feature) feature_name = config['namer'](feature) # If encoding is specified, decode id and feature name if config['encoding'] != '': external_id = external_id.decode(config['encoding']) feature_name = feature_name.decode(config['encoding']) if config['kind_first']: display_name = '%s %s' % (config['singular'], feature_name) else: display_name = '%s %s' % (feature_name, config['singular']) Boundary.objects.create( set=bset, kind=config['singular'], external_id=external_id, name=feature_name, display_name=display_name, metadata=metadata, shape=geometry.wkt, simple_shape=simple_geometry.wkt, centroid=geometry.geos.centroid)
AttributeError
dataset/ETHPy150Open newsapps/django-boundaryservice/boundaryservice/management/commands/loadshapefiles.py/Command.add_boundaries_for_layer
8,621
def onReload(self,moduleName="ParenchymaAnalysis"): """Generic reload method for any scripted module. ModuleWizard will subsitute correct default moduleName. """ import imp, sys, os, slicer widgetName = moduleName + "Widget" # reload the source code # - set source file path # - load the module to the global space filePath = eval('slicer.modules.%s.path' % moduleName.lower()) p = os.path.dirname(filePath) if not sys.path.__contains__(p): sys.path.insert(0,p) fp = open(filePath, "r") globals()[moduleName] = imp.load_module( moduleName, fp, filePath, ('.py', 'r', imp.PY_SOURCE)) fp.close() # rebuild the widget # - find and hide the existing widget # - create a new widget in the existing parent parent = slicer.util.findChildren(name='%s Reload' % moduleName)[0].parent().parent() for child in parent.children(): try: child.hide() except __HOLE__: pass # Remove spacer items item = parent.layout().itemAt(0) while item: parent.layout().removeItem(item) item = parent.layout().itemAt(0) # delete the old widget instance if hasattr(globals()['slicer'].modules, widgetName): getattr(globals()['slicer'].modules, widgetName).cleanup() # create new widget inside existing parent globals()[widgetName.lower()] = eval( 'globals()["%s"].%s(parent)' % (moduleName, widgetName)) globals()[widgetName.lower()].setup() setattr(globals()['slicer'].modules, widgetName, globals()[widgetName.lower()])
AttributeError
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/ParenchymaAnalysis/ParenchymaAnalysis.py/ParenchymaAnalysisWidget.onReload
8,622
def find_python_module(self, name, mark): if not name: raise ConstructorError("while constructing a Python module", mark, "expected non-empty name appended to the tag", mark) try: __import__(name) except __HOLE__ as exc: raise ConstructorError("while constructing a Python module", mark, "cannot find module %r (%s)" % (name, exc), mark) return sys.modules[name]
ImportError
dataset/ETHPy150Open NicoSantangelo/sublime-text-i18n-rails/pyyaml/constructor.py/Constructor.find_python_module
8,623
def find_python_name(self, name, mark): if not name: raise ConstructorError("while constructing a Python object", mark, "expected non-empty name appended to the tag", mark) if '.' in name: module_name, object_name = name.rsplit('.', 1) else: module_name = 'builtins' object_name = name try: __import__(module_name) except __HOLE__ as exc: raise ConstructorError("while constructing a Python object", mark, "cannot find module %r (%s)" % (module_name, exc), mark) module = sys.modules[module_name] if not hasattr(module, object_name): raise ConstructorError("while constructing a Python object", mark, "cannot find %r in the module %r" % (object_name, module.__name__), mark) return getattr(module, object_name)
ImportError
dataset/ETHPy150Open NicoSantangelo/sublime-text-i18n-rails/pyyaml/constructor.py/Constructor.find_python_name
8,624
def outgoing (self, msg): try: channel = msg.irc_channel except __HOLE__: channel = self.channels[0] if channel: target = channel else: target = msg.connection.identity response = "%s: %s" % (msg.connection.identity, msg.text) self.info("sending to %s: %s", target, response) self.server.privmsg(target, response)
AttributeError
dataset/ETHPy150Open rapidsms/rapidsms-core-dev/lib/rapidsms/backends/irc.py/Backend.outgoing
8,625
def pubmsg (self, connection, event): self.debug("%s -> %s: %r", event.source(), event.target(), event.arguments()) try: nick, txt = map(str.strip, event.arguments()[0].split(":")) except __HOLE__: return # not for me nick = nick.split("!")[0] if nick == self.nick: self.info("routing public message from %s", event.source()) c = Connection(self, event.source().split("!")[0]) msg = self.message(c.identity, txt) msg.irc_channel = event.target() self.route(msg)
ValueError
dataset/ETHPy150Open rapidsms/rapidsms-core-dev/lib/rapidsms/backends/irc.py/Backend.pubmsg
8,626
def main(world_folder): world = AnvilWorldFolder(world_folder) # Not supported for McRegion if not world.nonempty(): # likely still a McRegion file sys.stderr.write("World folder %r is empty or not an Anvil formatted world\n" % world_folder) return 65 # EX_DATAERR biome_totals = [0]*256 # 256 counters for 256 biome IDs try: for chunk in world.iter_nbt(): for biomeid in chunk["Level"]["Biomes"]: biome_totals[biomeid] += 1 except __HOLE__: print_results(biome_totals) return 75 # EX_TEMPFAIL print_results(biome_totals) return 0 # NOERR
KeyboardInterrupt
dataset/ETHPy150Open twoolie/NBT/examples/biome_analysis.py/main
8,627
def _rerequest_single(self, t, s, l, callback): try: closer = [None] def timedout(self = self, l = l, closer = closer): if self.lock.trip(l): self.errorcodes['troublecode'] = 'Problem connecting to tracker - timeout exceeded' self.lock.unwait(l) try: closer[0]() except: pass self.externalsched(timedout, self.timeout) err = None try: h = urlopen(t+s) closer[0] = h.close data = h.read() except (IOError, error), e: err = 'Problem connecting to tracker - ' + str(e) except: err = 'Problem connecting to tracker' try: h.close() except: pass if err: if self.lock.trip(l): self.errorcodes['troublecode'] = err self.lock.unwait(l) return if data == '': if self.lock.trip(l): self.errorcodes['troublecode'] = 'no data from tracker' self.lock.unwait(l) return try: r = bdecode(data, sloppy=1) check_peers(r) except __HOLE__, e: if self.lock.trip(l): self.errorcodes['bad_data'] = 'bad data from tracker - ' + str(e) self.lock.unwait(l) return if r.has_key('failure reason'): if self.lock.trip(l): self.errorcodes['rejected'] = self.rejectedmessage + r['failure reason'] self.lock.unwait(l) return if self.lock.trip(l, True): # success! self.lock.unwait(l) else: callback = lambda: None # attempt timed out, don't do a callback # even if the attempt timed out, go ahead and process data def add(self = self, r = r, callback = callback): self.postrequest(r, callback) self.externalsched(add) except: self.exception(callback)
ValueError
dataset/ETHPy150Open lg/murder/dist/BitTornado/BT1/Rerequester.py/Rerequester._rerequest_single
8,628
def download_directory(url, target, insecure=False): def mkdir(): if not mkdir.done: try: os.mkdir(target) except __HOLE__: pass mkdir.done = True mkdir.done = False opener = build_opener(insecure=insecure) response = opener.open(url) if response.info().type == 'text/html': contents = response.read() parser = ListingParser(url) parser.feed(contents) for link in parser.links: link = resolve_link(link, url) if link[-1] == '/': link = link[:-1] if not link.startswith(url): continue name = link.rsplit('/', 1)[1] if '?' in name: continue mkdir() download_directory(link, os.path.join(target, name), insecure) if not mkdir.done: # We didn't find anything to write inside this directory # Maybe it's a HTML file? if url[-1] != '/': end = target[-5:].lower() if not (end.endswith('.htm') or end.endswith('.html')): target = target + '.html' with open(target, 'wb') as fp: fp.write(contents) else: buffer_size = 4096 with open(target, 'wb') as fp: chunk = response.read(buffer_size) while chunk: fp.write(chunk) chunk = response.read(buffer_size) ###############################################################################
OSError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/URL/http_directory.py/download_directory
8,629
def init(): import nova.conf CONF = nova.conf.CONF # NOTE(markmc): gracefully handle the CLI options not being registered if 'remote_debug' not in CONF: return if not (CONF.remote_debug.host and CONF.remote_debug.port): return import logging from nova.i18n import _LW LOG = logging.getLogger(__name__) LOG.debug('Listening on %(host)s:%(port)s for debug connection', {'host': CONF.remote_debug.host, 'port': CONF.remote_debug.port}) try: from pydev import pydevd except __HOLE__: import pydevd pydevd.settrace(host=CONF.remote_debug.host, port=CONF.remote_debug.port, stdoutToServer=False, stderrToServer=False) LOG.warning(_LW('WARNING: Using the remote debug option changes how ' 'Nova uses the eventlet library to support async IO. This ' 'could result in failures that do not occur under normal ' 'operation. Use at your own risk.'))
ImportError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/debugger.py/init
8,630
def main(): parser = argparse.ArgumentParser() parser.add_argument('keys', metavar='KEY', nargs='+', default=None, help='keys associated with values to be selected') args = parser.parse_args() if sys.stdin.isatty(): parser.error('no input, pipe another btc command output into this command') l = sys.stdin.read() if len(l.strip()) == 0: exit(1) try: l = decoder.decode(l) except ValueError: error('unexpected input: %s' % l) if not isinstance(l, list): error('input must be a list') elif not all(isinstance(x, dict) for x in l): error('list items must be dictionaries') out = [] for i, e in enumerate(l): e_out = {} for key in args.keys: try: if len(args.keys) == 1: e_out = e[key] else: e_out[key] = e[key] except __HOLE__: error('key not found: {}'.format(key)) out.append(e_out) if len(args.keys) > 1: print(encoder.encode([ordered_dict(d) for d in out])) else: print(encoder.encode([e for e in out]))
KeyError
dataset/ETHPy150Open bittorrent/btc/btc/btc_select.py/main
8,631
def __getitem__(self, key): for mapping in self.maps: try: return mapping[key] # can't use 'key in mapping' with defaultdict except __HOLE__: pass return self.__missing__(key) # support subclasses that define __missing__
KeyError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.__getitem__
8,632
def __delitem__(self, key): try: del self.maps[0][key] except __HOLE__: raise KeyError('Key not found in the first mapping: {!r}'.format(key))
KeyError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.__delitem__
8,633
def popitem(self): 'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.' try: return self.maps[0].popitem() except __HOLE__: raise KeyError('No keys found in the first mapping.')
KeyError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.popitem
8,634
def pop(self, key, *args): 'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].' try: return self.maps[0].pop(key, *args) except __HOLE__: raise KeyError('Key not found in the first mapping: {!r}'.format(key))
KeyError
dataset/ETHPy150Open ionelmc/python-aspectlib/src/aspectlib/py2chainmap.py/ChainMap.pop
8,635
@then(u'we should get exit code {expected_exit_code:d}') def check_exit_code(context, expected_exit_code): try: assert context.exit_code == expected_exit_code, \ "expected %d, got %d" % (expected_exit_code, context.exit_code) except __HOLE__: # behave likes to back up by two lines and then print some stuff, which clobbers my output, so I stick some # extra newlines on here. print "Output of setup_chronos_job:\n" + context.output + "\n\n" raise
AssertionError
dataset/ETHPy150Open Yelp/paasta/paasta_itests/steps/setup_chronos_job_steps.py/check_exit_code
8,636
def create_structure(struct, prefix=None, update=False): """ Manifests a directory structure in the filesystem :param struct: directory structure as dictionary of dictionaries :param prefix: prefix path for the structure :param update: update an existing directory structure as boolean """ if prefix is None: prefix = os.getcwd() for name, content in struct.items(): if isinstance(content, string_types): with open(join_path(prefix, name), 'w') as fh: fh.write(utils.utf8_encode(content)) elif isinstance(content, dict): try: os.mkdir(join_path(prefix, name)) except __HOLE__: if not update: raise create_structure(struct[name], prefix=join_path(prefix, name), update=update) elif content is None: pass else: raise RuntimeError("Don't know what to do with content type " "{type}.".format(type=type(content)))
OSError
dataset/ETHPy150Open blue-yonder/pyscaffold/pyscaffold/structure.py/create_structure
8,637
def diff_map(self, incolls): """Generate SQL to transform existing collations :param incolls: a YAML map defining the new collations :return: list of SQL statements Compares the existing collation definitions, as fetched from the catalogs, to the input map and generates SQL statements to create, drop or change the collations accordingly. """ stmts = [] # check input collations for cll in incolls: incoll = incolls[cll] # does it exist in the database? if cll in self: stmts.append(self[cll].diff_map(incoll)) else: # check for possible RENAME if hasattr(incoll, 'oldname'): oldname = incoll.oldname try: stmts.append(self[oldname].rename(incoll.name)) del self[oldname] except __HOLE__ as exc: exc.args = ("Previous name '%s' for collation '%s' " "not found" % (oldname, incoll.name), ) raise else: # create new collation stmts.append(incoll.create()) # check database collations for (sch, cll) in self: # if missing, drop it if (sch, cll) not in incolls: stmts.append(self[(sch, cll)].drop()) return stmts
KeyError
dataset/ETHPy150Open perseas/Pyrseas/pyrseas/dbobject/collation.py/CollationDict.diff_map
8,638
def _update_voi(self): if len(self.inputs) == 0: return plane = self.plane extents = (self.x_min, self.x_max, self.y_min, self.y_max, self.z_min, self.z_max) try: plane.set_extent(extents) except __HOLE__: plane.extent = tuple(extents) plane.update_whole_extent() plane.update() self.data_changed = True
AttributeError
dataset/ETHPy150Open enthought/mayavi/mayavi/components/custom_grid_plane.py/CustomGridPlane._update_voi
8,639
def __missing__(self, key): try: value = raw_input(prompt_str.format(key)) except __HOLE__: # Catch the sigint here, since the user's pretty likely to # Ctrl-C and go fix the options mapping input file raise SystemExit if not value: value = None self[key] = value return value
KeyboardInterrupt
dataset/ETHPy150Open seandst/cfn-pyplates/cfn_pyplates/options.py/OptionsMapping.__missing__
8,640
def jar_run(debugger): # Set up the root Tk context root = Tk() # Construct a window debugging the nominated program view = MainWindow(root, debugger) # Run the main loop try: view.mainloop() except __HOLE__: view.on_quit()
KeyboardInterrupt
dataset/ETHPy150Open pybee/bugjar/bugjar/main.py/jar_run
8,641
def _to_nodes(self, object): nodes = [] for element in object.findall('devices/device'): if element.findtext("type") == "Virtual Server": try: state = self.NODE_STATE_MAP[element.attrib['status']] except __HOLE__: state = NodeState.UNKNOWN public_ip = private_ip = None ipassignments = element.findall("ipassignments/ipassignment") for ip in ipassignments: if ip.attrib["type"] =="frontend": public_ip = ip.text elif ip.attrib["type"] == "backend": private_ip = ip.text nodes.append(Node(id= element.attrib['id'], name=element.attrib['label'], state=state, public_ip= public_ip, private_ip= private_ip, driver=self.connection.driver)) return nodes
KeyError
dataset/ETHPy150Open secondstory/dewpoint/libcloud/drivers/voxel.py/VoxelNodeDriver._to_nodes
8,642
def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('videoid') url = mobj.group('proto') + 'www.' + mobj.group('url') req = compat_urllib_request.Request(url) req.add_header('Cookie', 'age_verified=1') webpage = self._download_webpage(req, video_id) age_limit = self._rta_search(webpage) # Get JSON parameters json_params = self._search_regex( r'var currentVideo = new Video\((.*)\)[,;]', webpage, 'JSON parameters') try: params = json.loads(json_params) except: raise ExtractorError('Invalid JSON') self.report_extraction(video_id) try: video_title = params['title'] upload_date = unified_strdate(params['release_date_f']) video_description = params['description'] video_uploader = params['submitted_by'] thumbnail = params['thumbnails'][0]['image'] except __HOLE__: raise ExtractorError('Missing JSON parameter: ' + sys.exc_info()[1]) # Get all of the links from the page DOWNLOAD_LIST_RE = r'(?s)<ul class="downloadList">(?P<download_list>.*?)</ul>' download_list_html = self._search_regex(DOWNLOAD_LIST_RE, webpage, 'download list').strip() LINK_RE = r'<a href="([^"]+)">' links = re.findall(LINK_RE, download_list_html) # Get all encrypted links encrypted_links = re.findall(r'var encryptedQuality[0-9]{3}URL = \'([a-zA-Z0-9+/]+={0,2})\';', webpage) for encrypted_link in encrypted_links: link = aes_decrypt_text(encrypted_link, video_title, 32).decode('utf-8') links.append(link) formats = [] for link in links: # A link looks like this: # http://cdn1.download.youporn.phncdn.com/201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4?nvb=20121113051249&nva=20121114051249&ir=1200&sr=1200&hash=014b882080310e95fb6a0 # A path looks like this: # /201210/31/8004515/480p_370k_8004515/YouPorn%20-%20Nubile%20Films%20The%20Pillow%20Fight.mp4 video_url = unescapeHTML(link) path = compat_urllib_parse_urlparse(video_url).path format_parts = path.split('/')[4].split('_')[:2] dn = compat_urllib_parse_urlparse(video_url).netloc.partition('.')[0] resolution = format_parts[0] height = int(resolution[:-len('p')]) bitrate = int(format_parts[1][:-len('k')]) format = '-'.join(format_parts) + '-' + dn formats.append({ 'url': video_url, 'format': format, 'format_id': format, 'height': height, 'tbr': bitrate, 'resolution': resolution, }) self._sort_formats(formats) if not formats: raise ExtractorError('ERROR: no known formats available for video') return { 'id': video_id, 'uploader': video_uploader, 'upload_date': upload_date, 'title': video_title, 'thumbnail': thumbnail, 'description': video_description, 'age_limit': age_limit, 'formats': formats, }
KeyError
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/extractor/youporn.py/YouPornIE._real_extract
8,643
def _init_vintageous(view, new_session=False): """ Initializes global data. Runs at startup and every time a view gets activated, loaded, etc. @new_session Whether we're starting up Sublime Text. If so, volatile data must be wiped. """ _logger.debug("running init for view %d", view.id()) if not is_view(view): # Abort if we got a widget, panel... _logger.info( '[_init_vintageous] ignoring view: {0}'.format( view.name() or view.file_name() or '<???>')) try: # XXX: All this seems to be necessary here. if not is_ignored_but_command_mode(view): view.settings().set('command_mode', False) view.settings().set('inverse_caret_state', False) view.settings().erase('vintage') if is_ignored(view): # Someone has intentionally disabled Vintageous, so let the user know. sublime.status_message( 'Vintageous: Vim emulation disabled for the current view') except __HOLE__: _logger.info( '[_init_vintageous] probably received the console view') except Exception: _logger.error('[_init_vintageous] error initializing view') finally: return state = State(view) if not state.reset_during_init: # Probably exiting from an input panel, like when using '/'. Don't # reset the global state, as it may contain data needed to complete # the command that's being built. state.reset_during_init = True return # Non-standard user setting. reset = state.settings.view['vintageous_reset_mode_when_switching_tabs'] # XXX: If the view was already in normal mode, we still need to run the # init code. I believe this is due to Sublime Text (intentionally) not # serializing the inverted caret state and the command_mode setting when # first loading a file. # If the mode is unknown, it might be a new file. Let normal mode setup # continue. if not reset and (state.mode not in (modes.NORMAL, modes.UNKNOWN)): return # If we have no selections, add one. if len(state.view.sel()) == 0: state.view.sel().add(sublime.Region(0)) state.logger.info('[_init_vintageous] running init') if state.mode in (modes.VISUAL, modes.VISUAL_LINE): # TODO: Don't we need to pass a mode here? view.window().run_command('_enter_normal_mode', {'from_init': True}) elif state.mode in (modes.INSERT, modes.REPLACE): # TODO: Don't we need to pass a mode here? view.window().run_command('_enter_normal_mode', {'from_init': True}) elif (view.has_non_empty_selection_region() and state.mode != modes.VISUAL): # Runs, for example, when we've performed a search via ST3 search # panel and we've pressed 'Find All'. In this case, we want to # ensure a consistent state for multiple selections. # TODO: We could end up with multiple selections in other ways # that bypass _init_vintageous. state.mode = modes.VISUAL else: # This may be run when we're coming from cmdline mode. pseudo_visual = view.has_non_empty_selection_region() mode = modes.VISUAL if pseudo_visual else state.mode # TODO: Maybe the above should be handled by State? state.enter_normal_mode() view.window().run_command('_enter_normal_mode', {'mode': mode, 'from_init': True}) state.reset_command_data() if new_session: state.reset_volatile_data() # Load settings. DotFile.from_user().run() # TODO: Implement this
AttributeError
dataset/ETHPy150Open guillermooo/Vintageous/state.py/_init_vintageous
8,644
def plugin_unloaded(): view = sublime.active_window().active_view() try: view.settings().set('command_mode', False) view.settings().set('inverse_caret_state', False) except __HOLE__: _logger.warn( 'could not access sublime.active_window().active_view().settings ' ' while unloading')
AttributeError
dataset/ETHPy150Open guillermooo/Vintageous/state.py/plugin_unloaded
8,645
def cpu_count(): """Returns the number of processors on this machine.""" try: return multiprocessing.cpu_count() except NotImplementedError: pass try: return os.sysconf("SC_NPROCESSORS_CONF") except __HOLE__: pass gen_log.error("Could not detect number of processors; assuming 1") return 1
ValueError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/cpu_count
8,646
def _reseed_random(): if 'random' not in sys.modules: return import random # If os.urandom is available, this method does the same thing as # random.seed (at least as of python 2.6). If os.urandom is not # available, we mix in the pid in addition to a timestamp. try: seed = long(hexlify(os.urandom(16)), 16) except __HOLE__: seed = int(time.time() * 1000) ^ os.getpid() random.seed(seed)
NotImplementedError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/_reseed_random
8,647
def fork_processes(num_processes, max_restarts=100): """Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory between any server code. Note that multiple processes are not compatible with the autoreload module (or the debug=True option to `tornado.web.Application`). When using multiple processes, no IOLoops can be created or referenced until after the call to ``fork_processes``. In each child process, ``fork_processes`` returns its *task id*, a number between 0 and ``num_processes``. Processes that exit abnormally (due to a signal or non-zero exit status) are restarted with the same id (up to ``max_restarts`` times). In the parent process, ``fork_processes`` returns None if all child processes have exited normally, but will otherwise only exit by throwing an exception. """ global _task_id assert _task_id is None if num_processes is None or num_processes <= 0: num_processes = cpu_count() if ioloop.IOLoop.initialized(): raise RuntimeError("Cannot run in multiple processes: IOLoop instance " "has already been initialized. You cannot call " "IOLoop.instance() before calling start_processes()") gen_log.info("Starting %d processes", num_processes) children = {} def start_child(i): pid = os.fork() if pid == 0: # child process _reseed_random() global _task_id _task_id = i return i else: children[pid] = i return None for i in range(num_processes): id = start_child(i) if id is not None: return id num_restarts = 0 while children: try: pid, status = os.wait() except __HOLE__ as e: if e.errno == errno.EINTR: continue raise if pid not in children: continue id = children.pop(pid) if os.WIFSIGNALED(status): gen_log.warning("child %d (pid %d) killed by signal %d, restarting", id, pid, os.WTERMSIG(status)) elif os.WEXITSTATUS(status) != 0: gen_log.warning("child %d (pid %d) exited with status %d, restarting", id, pid, os.WEXITSTATUS(status)) else: gen_log.info("child %d (pid %d) exited normally", id, pid) continue num_restarts += 1 if num_restarts > max_restarts: raise RuntimeError("Too many child restarts, giving up") new_id = start_child(id) if new_id is not None: return new_id # All child processes exited cleanly, so exit the master process # instead of just returning to right after the call to # fork_processes (which will probably just start up another IOLoop # unless the caller checks the return value). sys.exit(0)
OSError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/fork_processes
8,648
@classmethod def _try_cleanup_process(cls, pid): try: ret_pid, status = os.waitpid(pid, os.WNOHANG) except __HOLE__ as e: if e.args[0] == errno.ECHILD: return if ret_pid == 0: return assert ret_pid == pid subproc = cls._waiting.pop(pid) subproc.io_loop.add_callback_from_signal( subproc._set_returncode, status)
OSError
dataset/ETHPy150Open D-L/SimpleBookMarks/src/tornado/process.py/Subprocess._try_cleanup_process
8,649
def test_transaction_hook(self): run_hook = [] class RootController(object): @expose() def index(self): run_hook.append('inside') return 'Hello, World!' @expose() def redirect(self): redirect('/') @expose() def error(self): return [][1] def gen(event): return lambda: run_hook.append(event) app = TestApp(make_app(RootController(), hooks=[ TransactionHook( start=gen('start'), start_ro=gen('start_ro'), commit=gen('commit'), rollback=gen('rollback'), clear=gen('clear') ) ])) response = app.get('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 3 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'inside' assert run_hook[2] == 'clear' run_hook = [] response = app.post('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 4 assert run_hook[0] == 'start' assert run_hook[1] == 'inside' assert run_hook[2] == 'commit' assert run_hook[3] == 'clear' # # test hooks for GET /redirect # This controller should always be non-transactional # run_hook = [] response = app.get('/redirect') assert response.status_int == 302 assert len(run_hook) == 2 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' # # test hooks for POST /redirect # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.post('/redirect') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'commit' assert run_hook[2] == 'clear' run_hook = [] try: response = app.post('/error') except __HOLE__: pass assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear'
IndexError
dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook
8,650
def test_transaction_hook_with_transactional_decorator(self): run_hook = [] class RootController(object): @expose() def index(self): run_hook.append('inside') return 'Hello, World!' @expose() def redirect(self): redirect('/') @expose() @transactional() def redirect_transactional(self): redirect('/') @expose() @transactional(False) def redirect_rollback(self): redirect('/') @expose() def error(self): return [][1] @expose() @transactional(False) def error_rollback(self): return [][1] @expose() @transactional() def error_transactional(self): return [][1] def gen(event): return lambda: run_hook.append(event) app = TestApp(make_app(RootController(), hooks=[ TransactionHook( start=gen('start'), start_ro=gen('start_ro'), commit=gen('commit'), rollback=gen('rollback'), clear=gen('clear') ) ])) response = app.get('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 3 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'inside' assert run_hook[2] == 'clear' run_hook = [] # test hooks for / response = app.post('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 4 assert run_hook[0] == 'start' assert run_hook[1] == 'inside' assert run_hook[2] == 'commit' assert run_hook[3] == 'clear' # # test hooks for GET /redirect # This controller should always be non-transactional # run_hook = [] response = app.get('/redirect') assert response.status_int == 302 assert len(run_hook) == 2 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' # # test hooks for POST /redirect # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.post('/redirect') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'commit' assert run_hook[2] == 'clear' # # test hooks for GET /redirect_transactional # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.get('/redirect_transactional') assert response.status_int == 302 assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'commit' assert run_hook[4] == 'clear' # # test hooks for POST /redirect_transactional # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.post('/redirect_transactional') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'commit' assert run_hook[2] == 'clear' # # test hooks for GET /redirect_rollback # This controller should always be transactional, # *except* in the case of redirects # run_hook = [] response = app.get('/redirect_rollback') assert response.status_int == 302 assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'rollback' assert run_hook[4] == 'clear' # # test hooks for POST /redirect_rollback # This controller should always be transactional, # *except* in the case of redirects # run_hook = [] response = app.post('/redirect_rollback') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' # # Exceptions (other than HTTPFound) should *always* # rollback no matter what # run_hook = [] try: response = app.post('/error') except IndexError: pass assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' run_hook = [] try: response = app.get('/error') except IndexError: pass assert len(run_hook) == 2 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' run_hook = [] try: response = app.post('/error_transactional') except __HOLE__: pass assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' run_hook = [] try: response = app.get('/error_transactional') except IndexError: pass assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'rollback' assert run_hook[4] == 'clear' run_hook = [] try: response = app.post('/error_rollback') except IndexError: pass assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' run_hook = [] try: response = app.get('/error_rollback') except IndexError: pass assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'rollback' assert run_hook[4] == 'clear'
IndexError
dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook_with_transactional_decorator
8,651
def test_transaction_hook_with_transactional_class_decorator(self): run_hook = [] @transactional() class RootController(object): @expose() def index(self): run_hook.append('inside') return 'Hello, World!' @expose() def redirect(self): redirect('/') @expose() @transactional(False) def redirect_rollback(self): redirect('/') @expose() def error(self): return [][1] @expose(generic=True) def generic(self): pass @generic.when(method='GET') def generic_get(self): run_hook.append('inside') return 'generic get' @generic.when(method='POST') def generic_post(self): run_hook.append('inside') return 'generic post' def gen(event): return lambda: run_hook.append(event) app = TestApp(make_app(RootController(), hooks=[ TransactionHook( start=gen('start'), start_ro=gen('start_ro'), commit=gen('commit'), rollback=gen('rollback'), clear=gen('clear') ) ])) response = app.get('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 6 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'inside' assert run_hook[4] == 'commit' assert run_hook[5] == 'clear' run_hook = [] # test hooks for / response = app.post('/') assert response.status_int == 200 assert response.body == b_('Hello, World!') assert len(run_hook) == 4 assert run_hook[0] == 'start' assert run_hook[1] == 'inside' assert run_hook[2] == 'commit' assert run_hook[3] == 'clear' # # test hooks for GET /redirect # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.get('/redirect') assert response.status_int == 302 assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'commit' assert run_hook[4] == 'clear' # # test hooks for POST /redirect # This controller should always be transactional, # even in the case of redirects # run_hook = [] response = app.post('/redirect') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'commit' assert run_hook[2] == 'clear' # # test hooks for GET /redirect_rollback # This controller should always be transactional, # *except* in the case of redirects # run_hook = [] response = app.get('/redirect_rollback') assert response.status_int == 302 assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'rollback' assert run_hook[4] == 'clear' # # test hooks for POST /redirect_rollback # This controller should always be transactional, # *except* in the case of redirects # run_hook = [] response = app.post('/redirect_rollback') assert response.status_int == 302 assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' # # Exceptions (other than HTTPFound) should *always* # rollback no matter what # run_hook = [] try: response = app.post('/error') except __HOLE__: pass assert len(run_hook) == 3 assert run_hook[0] == 'start' assert run_hook[1] == 'rollback' assert run_hook[2] == 'clear' run_hook = [] try: response = app.get('/error') except IndexError: pass assert len(run_hook) == 5 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'rollback' assert run_hook[4] == 'clear' # # test hooks for GET /generic # This controller should always be transactional, # run_hook = [] response = app.get('/generic') assert response.status_int == 200 assert response.body == b_('generic get') assert len(run_hook) == 6 assert run_hook[0] == 'start_ro' assert run_hook[1] == 'clear' assert run_hook[2] == 'start' assert run_hook[3] == 'inside' assert run_hook[4] == 'commit' assert run_hook[5] == 'clear' # # test hooks for POST /generic # This controller should always be transactional, # run_hook = [] response = app.post('/generic') assert response.status_int == 200 assert response.body == b_('generic post') assert len(run_hook) == 4 assert run_hook[0] == 'start' assert run_hook[1] == 'inside' assert run_hook[2] == 'commit' assert run_hook[3] == 'clear'
IndexError
dataset/ETHPy150Open pecan/pecan/pecan/tests/test_hooks.py/TestTransactionHook.test_transaction_hook_with_transactional_class_decorator
8,652
@defer.inlineCallbacks def _check_recaptcha(self, authdict, clientip): try: user_response = authdict["response"] except __HOLE__: # Client tried to provide captcha but didn't give the parameter: # bad request. raise LoginError( 400, "Captcha response is required", errcode=Codes.CAPTCHA_NEEDED ) logger.info( "Submitting recaptcha response %s with remoteip %s", user_response, clientip ) # TODO: get this from the homeserver rather than creating a new one for # each request try: client = self.hs.get_simple_http_client() resp_body = yield client.post_urlencoded_get_json( self.hs.config.recaptcha_siteverify_api, args={ 'secret': self.hs.config.recaptcha_private_key, 'response': user_response, 'remoteip': clientip, } ) except PartialDownloadError as pde: # Twisted is silly data = pde.response resp_body = simplejson.loads(data) if 'success' in resp_body and resp_body['success']: defer.returnValue(True) raise LoginError(401, "", errcode=Codes.UNAUTHORIZED)
KeyError
dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/auth.py/AuthHandler._check_recaptcha
8,653
def validate_short_term_login_token_and_get_user_id(self, login_token): try: macaroon = pymacaroons.Macaroon.deserialize(login_token) auth_api = self.hs.get_auth() auth_api.validate_macaroon(macaroon, "login", True) return self.get_user_from_macaroon(macaroon) except (pymacaroons.exceptions.MacaroonException, __HOLE__, ValueError): raise AuthError(401, "Invalid token", errcode=Codes.UNKNOWN_TOKEN)
TypeError
dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/auth.py/AuthHandler.validate_short_term_login_token_and_get_user_id
8,654
def testDefFile(self): l = Parser.parseSource(testHeader) # FIXME: hardcode the function pointer since we don't parse those yet l.functions["funcPointer"] = Library.Function("funcPointer", "void") for function, ordinal in Parser.parseDefFile(testDefFile): l.functions[function].ordinal = ordinal # check that all ordinals were read for f in l.functions.values(): assert f.ordinal is not None # check overlapping ordinals in input try: Parser.parseDefFile(testBadDefFile) self.fail("ValueError not raised.") except __HOLE__: pass
ValueError
dataset/ETHPy150Open skyostil/tracy/src/generator/ParserTest.py/ParserTest.testDefFile
8,655
def test_channel_close_does_not_raise_an_exception_with_no_socket(self): try: self.channel.close() except __HOLE__: self.fail("Attempted to remove a socketless channel from the engine.")
TypeError
dataset/ETHPy150Open ecdavis/pants/pants/test/core/test_channel.py/TestChannelClose.test_channel_close_does_not_raise_an_exception_with_no_socket
8,656
def main(): args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]), version=const.VERSION) logging.basicConfig( level=logging.DEBUG if args['--verbose'] else logging.INFO, stream=sys.stdout, ) conf = config.new_context_from_file(args['--config-file'], section='imap') delete_conf = config.new_context_from_file(args['--config-file'], section='trash') if conf is None: return 1 try: imap_account = imap_cli.connect(**conf) imap_cli.change_dir(imap_account, args['--directory'] or const.DEFAULT_DIRECTORY, read_only=False) if delete_conf['delete_method'] == 'MOVE_TO_TRASH': copy.copy(imap_account, args['<mail_id>'], delete_conf['trash_directory']) flag.flag(imap_account, args['<mail_id>'], [const.FLAG_DELETED]) if delete_conf['delete_method'] in ['MOVE_TO_TRASH', 'EXPUNGE']: imap_account.expunge() imap_cli.disconnect(imap_account) except __HOLE__: log.info('Interrupt by user, exiting') return 0
KeyboardInterrupt
dataset/ETHPy150Open Gentux/imap-cli/imap_cli/delete.py/main
8,657
def bug_role(role, rawtext, text, linenum, inliner, options={}, content=[]): try: bugnum = int(text) if bugnum <= 0: raise ValueError except __HOLE__: msg = inliner.reporter.error( 'Bug number must be a number greater than or equal to 1; ' '"%s" is invalid.' % text, line=linenum) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] bugtracker_url = inliner.document.settings.env.config.bugtracker_url if not bugtracker_url or '%s' not in bugtracker_url: msg = inliner.reporter.error('bugtracker_url must be configured.', line=linenum) prb = inliner.problematic(rawtext, rawtext, msg) return [prb], [msg] ref = bugtracker_url % bugnum node = nodes.reference(rawtext, 'Bug #' + utils.unescape(text), refuri=ref, **options) return [node], []
ValueError
dataset/ETHPy150Open reviewboard/reviewboard/docs/releasenotes/_ext/extralinks.py/bug_role
8,658
def _find_checkers(): try: from pkg_resources import working_set except __HOLE__: return [num_plurals, python_format] checkers = [] for entry_point in working_set.iter_entry_points('babel.checkers'): checkers.append(entry_point.load()) return checkers
ImportError
dataset/ETHPy150Open IanLewis/kay/kay/lib/babel/messages/checkers.py/_find_checkers
8,659
@transaction.atomic def handle_project_locale(self, project, locale): # Match locale code inconsistencies pootle_locale = locale.replace('-', '_') if pootle_locale == 'ga_IE': pootle_locale = 'ga' # Match project slug inconsistencies pootle_project = { 'amo': 'amo', 'find-my-device': 'findmydevice', 'firefox-accounts': 'accounts', 'firefox-accounts-payments': 'payments', 'firefox-hello': 'loop', 'firefox-input': 'input', 'marketplace': 'marketplace', 'marketplace-commbadge': 'commbadge', 'marketplace-fireplace': 'fireplace', 'marketplace-spartacus': 'spartacus', 'marketplace-stats': 'marketplace_stats', 'marketplace-zippy': 'zippy', 'master-firefox-os': 'masterfirefoxos', 'mdn': 'mdn', 'mozillians': 'mozillians', 'social-api-directory': 'socialapi-directory', 'sumo': 'sumo', }.get(project) if not pootle_project: return # Get Pootle data filename = pootle_locale + '_' + pootle_project + '.json' url = 'http://svn.mozilla.org/projects/l10n-misc/trunk/pontoon/verbatim/' + filename try: pootle = requests.get(url).json() except __HOLE__: return self.stdout.write("--- Skipping missing file {}.".format(filename)) # Get all Pontoon translations matching Pootle data paths = pootle.keys() entities = [] strings = [] emails = [] for path in paths: for entity in pootle[path].keys(): entities.append(entity) strings.append(pootle[path][entity]["translation"]) emails.append(pootle[path][entity]["author"]) translations = Translation.objects.filter( entity__resource__project__slug=project, entity__resource__path__in=paths, entity__string__in=entities, locale__code=locale, user=None, string__in=strings ) # Save user permissions and create dict to avoid hitting the DB later users_dict = {} users = User.objects.filter(email__in=emails) missing_users_list = [] locale_translators_map = dict(Locale.objects.values_list('code', 'translators_group')) for u in users: users_dict[u.email] = u if 'base.can_translate_locale' not in u.get_all_permissions(): u.groups.add(locale_translators_map[locale]) self.stdout.write("Permission granted to user {} to locale: {}.".format(u.email, locale)) if users: bulk_update(users) for t in translations: try: pootle_translation = pootle[t.entity.resource.path][t.entity.string] # Path - entity mismatch, skip to next translation except KeyError: continue # Save user email = pootle_translation["author"] user = users_dict.get(email) if not user: missing_users_list.append(email) t.user = user t.approved_user = user # Save date date = pootle_translation["date"].split("+")[0] dateObj = timezone.make_aware(datetime.strptime(date, "%Y-%m-%d %H:%M:%S")) t.date = dateObj t.approved_date = dateObj if translations: bulk_update(translations) missing_users = Counter(missing_users_list) for missing_user in missing_users.keys(): self.stdout.write("Pontoon user {} not found: {} translations.".format(missing_user, missing_users[missing_user])) self.stdout.write("+++ Imported data from file {}.".format(filename))
ValueError
dataset/ETHPy150Open mozilla/pontoon/pontoon/sync/management/commands/import_pootle.py/Command.handle_project_locale
8,660
@property def _provider(self): from libcloud.storage.types import Provider try: provider_name = self.LIBCLOUD_S3_PROVIDERS_BY_REGION[self._region] return getattr(Provider, provider_name) except __HOLE__: raise ArgumentError( 'Invalid value {invalid_region!r} for region. Valid Amazon S3 ' 'regions are {valid_regions}'.format( invalid_region=self._region, valid_regions=', '.join( sorted(self.LIBCLOUD_S3_PROVIDERS_BY_REGION.keys()) ) ) )
KeyError
dataset/ETHPy150Open jpvanhal/siilo/siilo/storages/amazon_s3.py/AmazonS3Storage._provider
8,661
def fetchone(self, delete_flag=False): try: result = self.last_select_command.results.next() if isinstance(result, (int, long)): return (result,) query = self.last_select_command.query row = [] # Prepend extra select values to the resulting row for col, select in query.extra_selects: row.append(result.get(col)) for col in self.last_select_command.query.init_list: row.append(result.get(col)) self.returned_ids.append(result.key().id_or_name()) return row except __HOLE__: return None
StopIteration
dataset/ETHPy150Open potatolondon/djangae/djangae/db/backends/appengine/base.py/Cursor.fetchone
8,662
def prep_lookup_key(self, model, value, field): if isinstance(value, basestring): value = value[:500] left = value[500:] if left: warnings.warn("Truncating primary key that is over 500 characters. " "THIS IS AN ERROR IN YOUR PROGRAM.", RuntimeWarning) # This is a bit of a hack. Basically when you query an integer PK with a # string containing an int. SQL seems to return the row regardless of type, and as far as # I can tell, Django at no point tries to cast the value to an integer. So, in the # case where the internal type is an AutoField, we try to cast the string value # I would love a more generic solution... patches welcome! # It would be nice to see the SQL output of the lookup_int_as_str test is on SQL, if # the string is converted to an int, I'd love to know where! if field.get_internal_type() == 'AutoField': try: value = int(value) except (__HOLE__, ValueError): pass value = get_datastore_key(model, value) else: value = get_datastore_key(model, value) return value
TypeError
dataset/ETHPy150Open potatolondon/djangae/djangae/db/backends/appengine/base.py/DatabaseOperations.prep_lookup_key
8,663
def main(namespace): # parse args command = ' '.join(sys.argv[1:]) if not command: # console (interactive) try: reinit(namespace) except __HOLE__: pass # ignore Ctrl-C (interferes with gevent) signal.signal(signal.SIGINT, lambda signum, frame: None) else: # call (non-interactive) reinit(namespace, info=False) console = code.InteractiveConsole(locals()) console.runsource(command)
KeyboardInterrupt
dataset/ETHPy150Open alexcepoi/pyscale/pyscale/tools/console.py/main
8,664
def _get_level_name_dict(self): ''' Returns level_name_dict for pre-set lookup_scheme_name, tile_type_id, satellite_tag, sensor_name & level_name Returns None if not found ''' assert self.lookup_scheme_name, 'lookup_scheme_name not set' assert self.tile_type_id, 'tile_type_id not set' assert self.satellite_tag, 'satellite_tag not set' assert self.sensor_name, 'sensor_name not set' assert self.level_name, 'level_name not set' try: level_name_dict = BandLookup._band_lookup_dict[self.lookup_scheme_name][self.tile_type_id][self.satellite_tag][self.sensor_name][self.level_name] except __HOLE__: level_name_dict = {} return level_name_dict
KeyError
dataset/ETHPy150Open GeoscienceAustralia/agdc/src/band_lookup.py/BandLookup._get_level_name_dict
8,665
def __getitem__(self, alias): try: return self._connections.connections[alias] except __HOLE__: self._connections.connections = {} except KeyError: pass try: backend = get_backend(alias) except KeyError: raise KeyError('%s is not a valid backend alias' % alias) connection = get_connection(backend) connection.open() self._connections.connections[alias] = connection return connection
AttributeError
dataset/ETHPy150Open ui/django-post_office/post_office/connections.py/ConnectionHandler.__getitem__
8,666
def parse_driver_info(node): """Checks for the required properties and values validity. :param node: the target node. :raises: MissingParameterValue if one or more required properties are missing. :raises: InvalidParameterValue if a parameter value is invalid. """ driver_info = node.driver_info _check_required_properties(driver_info) base_url = driver_info.get('msftocs_base_url') if not _is_valid_url(base_url): raise exception.InvalidParameterValue( _('"%s" is not a valid "msftocs_base_url"') % base_url) blade_id = driver_info.get('msftocs_blade_id') try: blade_id = int(blade_id) except __HOLE__: raise exception.InvalidParameterValue( _('"%s" is not a valid "msftocs_blade_id"') % blade_id) if blade_id < 1: raise exception.InvalidParameterValue( _('"msftocs_blade_id" must be greater than 0. The provided value ' 'is: %s') % blade_id)
ValueError
dataset/ETHPy150Open openstack/ironic/ironic/drivers/modules/msftocs/common.py/parse_driver_info
8,667
def indented_short_title(self, item): """ Generate a short title for an object, indent it depending on the object's depth in the hierarchy. """ mptt_opts = item._mptt_meta r = '' try: url = item.get_absolute_url() except (__HOLE__,): url = None if url: r = ( '<input type="hidden" class="medialibrary_file_path"' ' value="%s" id="_refkey_%d" />') % (url, item.pk) changeable_class = '' if not self.changeable(item): changeable_class = ' tree-item-not-editable' r += ( '<span id="page_marker-%d" class="page_marker%s"' ' style="width: %dpx;">&nbsp;</span>&nbsp;') % ( item.pk, changeable_class, 14 + getattr(item, mptt_opts.level_attr) * 18) # r += '<span tabindex="0">' if hasattr(item, 'short_title') and callable(item.short_title): r += escape(item.short_title()) else: r += escape('%s' % item) # r += '</span>' return mark_safe(r)
AttributeError
dataset/ETHPy150Open feincms/feincms/feincms/admin/tree_editor.py/TreeEditor.indented_short_title
8,668
def _collect_editable_booleans(self): """ Collect all fields marked as editable booleans. We do not want the user to be able to edit arbitrary fields by crafting an AJAX request by hand. """ if hasattr(self, '_ajax_editable_booleans'): return self._ajax_editable_booleans = {} for field in self.list_display: # The ajax_editable_boolean return value has to be assigned # to the ModelAdmin class try: item = getattr(self.__class__, field) except (AttributeError, __HOLE__): continue attr = getattr(item, 'editable_boolean_field', None) if attr: if hasattr(item, 'editable_boolean_result'): result_func = item.editable_boolean_result else: def _fn(attr): return lambda self, instance: [ ajax_editable_boolean_cell(instance, attr)] result_func = _fn(attr) self._ajax_editable_booleans[attr] = result_func
TypeError
dataset/ETHPy150Open feincms/feincms/feincms/admin/tree_editor.py/TreeEditor._collect_editable_booleans
8,669
def __init__(self, config_file=None): '''Attempt to initialize a config dictionary from a yaml file. Error out if loading the yaml file fails for any reason. :param config_file: The Bandit yaml config file :raises bandit.utils.ConfigError: If the config is invalid or unreadable. ''' self.config_file = config_file self._config = {} if config_file: try: f = open(config_file, 'r') except __HOLE__: raise utils.ConfigError("Could not read config file.", config_file) try: self._config = yaml.safe_load(f) self.validate(config_file) except yaml.YAMLError: raise utils.ConfigError("Error parsing file.", config_file) # valid config must be a dict if not isinstance(self._config, dict): raise utils.ConfigError("Error parsing file.", config_file) self.convert_legacy_config() else: # use sane defaults self._config['plugin_name_pattern'] = '*.py' self._config['include'] = ['*.py', '*.pyw'] self._init_settings()
IOError
dataset/ETHPy150Open openstack/bandit/bandit/core/config.py/BanditConfig.__init__
8,670
def test_no_exception_on_select(self): """ no exception on SELECT for numeric column name """ try: self.session.execute('SELECT * FROM test1rf.table_num_col') except __HOLE__ as e: self.fail("Unexpected ValueError exception: %s" % e.message)
ValueError
dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_no_exception_on_select
8,671
def test_can_select_using_alias(self): """ can SELECT "<numeric col name>" AS aliases """ if self._cass_version < (2, 0, 0): raise unittest.SkipTest("Alias in SELECT not supported before 2.0") try: self.session.execute('SELECT key, "626972746864617465" AS my_col from test1rf.table_num_col') except __HOLE__ as e: self.fail("Unexpected ValueError exception: %s" % e.message)
ValueError
dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_can_select_using_alias
8,672
def test_can_select_with_dict_factory(self): """ can SELECT numeric column using dict_factory """ self.session.row_factory = dict_factory try: self.session.execute('SELECT * FROM test1rf.table_num_col') except __HOLE__ as e: self.fail("Unexpected ValueError exception: %s" % e.message)
ValueError
dataset/ETHPy150Open datastax/python-driver/tests/integration/standard/test_row_factories.py/NamedTupleFactoryAndNumericColNamesTests.test_can_select_with_dict_factory
8,673
def _getconftestmodules(self, path): if self._noconftest: return [] try: return self._path2confmods[path] except __HOLE__: if path.isfile(): clist = self._getconftestmodules(path.dirpath()) else: # XXX these days we may rather want to use config.rootdir # and allow users to opt into looking into the rootdir parent # directories instead of requiring to specify confcutdir clist = [] for parent in path.parts(): if self._confcutdir and self._confcutdir.relto(parent): continue conftestpath = parent.join("conftest.py") if conftestpath.isfile(): mod = self._importconftest(conftestpath) clist.append(mod) self._path2confmods[path] = clist return clist
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._getconftestmodules
8,674
def _rget_with_confmod(self, name, path): modules = self._getconftestmodules(path) for mod in reversed(modules): try: return mod, getattr(mod, name) except __HOLE__: continue raise KeyError(name)
AttributeError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._rget_with_confmod
8,675
def _importconftest(self, conftestpath): try: return self._conftestpath2mod[conftestpath] except __HOLE__: pkgpath = conftestpath.pypkgpath() if pkgpath is None: _ensure_removed_sysmodule(conftestpath.purebasename) try: mod = conftestpath.pyimport() except Exception: raise ConftestImportFailure(conftestpath, sys.exc_info()) self._conftest_plugins.add(mod) self._conftestpath2mod[conftestpath] = mod dirpath = conftestpath.dirpath() if dirpath in self._path2confmods: for path, mods in self._path2confmods.items(): if path and path.relto(dirpath) or path == dirpath: assert mod not in mods mods.append(mod) self.trace("loaded conftestmodule %r" %(mod)) self.consider_conftest(mod) return mod # # API for bootstrapping plugin loading # #
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager._importconftest
8,676
def import_plugin(self, modname): # most often modname refers to builtin modules, e.g. "pytester", # "terminal" or "capture". Those plugins are registered under their # basename for historic purposes but must be imported with the # _pytest prefix. assert isinstance(modname, str) if self.get_plugin(modname) is not None: return if modname in builtin_plugins: importspec = "_pytest." + modname else: importspec = modname try: __import__(importspec) except __HOLE__ as e: new_exc = ImportError('Error importing plugin "%s": %s' % (modname, e)) # copy over name and path attributes for attr in ('name', 'path'): if hasattr(e, attr): setattr(new_exc, attr, getattr(e, attr)) raise new_exc except Exception as e: import pytest if not hasattr(pytest, 'skip') or not isinstance(e, pytest.skip.Exception): raise self._warn("skipped plugin %r: %s" %((modname, e.msg))) else: mod = sys.modules[importspec] self.register(mod, modname) self.consider_module(mod)
ImportError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/PytestPluginManager.import_plugin
8,677
def __init__(self, *names, **attrs): """store parms in private vars for use in add_argument""" self._attrs = attrs self._short_opts = [] self._long_opts = [] self.dest = attrs.get('dest') if self.TYPE_WARN: try: help = attrs['help'] if '%default' in help: warnings.warn( 'pytest now uses argparse. "%default" should be' ' changed to "%(default)s" ', FutureWarning, stacklevel=3) except KeyError: pass try: typ = attrs['type'] except KeyError: pass else: # this might raise a keyerror as well, don't want to catch that if isinstance(typ, py.builtin._basestring): if typ == 'choice': if self.TYPE_WARN: warnings.warn( 'type argument to addoption() is a string %r.' ' For parsearg this is optional and when supplied ' ' should be a type.' ' (options: %s)' % (typ, names), FutureWarning, stacklevel=3) # argparse expects a type here take it from # the type of the first element attrs['type'] = type(attrs['choices'][0]) else: if self.TYPE_WARN: warnings.warn( 'type argument to addoption() is a string %r.' ' For parsearg this should be a type.' ' (options: %s)' % (typ, names), FutureWarning, stacklevel=3) attrs['type'] = Argument._typ_map[typ] # used in test_parseopt -> test_parse_defaultgetter self.type = attrs['type'] else: self.type = typ try: # attribute existence is tested in Config._processopt self.default = attrs['default'] except __HOLE__: pass self._set_opt_strings(names) if not self.dest: if self._long_opts: self.dest = self._long_opts[0][2:].replace('-', '_') else: try: self.dest = self._short_opts[0][1:] except IndexError: raise ArgumentError( 'need a long or short option', self)
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Argument.__init__
8,678
def attrs(self): # update any attributes set by processopt attrs = 'default dest help'.split() if self.dest: attrs.append(self.dest) for attr in attrs: try: self._attrs[attr] = getattr(self, attr) except __HOLE__: pass if self._attrs.get('help'): a = self._attrs['help'] a = a.replace('%default', '%(default)s') #a = a.replace('%prog', '%(prog)s') self._attrs['help'] = a return self._attrs
AttributeError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Argument.attrs
8,679
def _ensure_removed_sysmodule(modname): try: del sys.modules[modname] except __HOLE__: pass
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/_ensure_removed_sysmodule
8,680
def _preparse(self, args, addopts=True): self._initini(args) if addopts: args[:] = shlex.split(os.environ.get('PYTEST_ADDOPTS', '')) + args args[:] = self.getini("addopts") + args self._checkversion() self.pluginmanager.consider_preparse(args) try: self.pluginmanager.load_setuptools_entrypoints("pytest11") except __HOLE__ as e: self.warn("I2", "could not load setuptools entry import: %s" % (e,)) self.pluginmanager.consider_env() self.known_args_namespace = ns = self._parser.parse_known_args(args, namespace=self.option.copy()) if self.known_args_namespace.confcutdir is None and self.inifile: confcutdir = py.path.local(self.inifile).dirname self.known_args_namespace.confcutdir = confcutdir try: self.hook.pytest_load_initial_conftests(early_config=self, args=args, parser=self._parser) except ConftestImportFailure: e = sys.exc_info()[1] if ns.help or ns.version: # we don't want to prevent --help/--version to work # so just let is pass and print a warning at the end self._warn("could not load initial conftests (%s)\n" % e.path) else: raise
ImportError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._preparse
8,681
def getini(self, name): """ return configuration value from an :ref:`ini file <inifiles>`. If the specified name hasn't been registered through a prior :py:func:`parser.addini <pytest.config.Parser.addini>` call (usually from a plugin), a ValueError is raised. """ try: return self._inicache[name] except __HOLE__: self._inicache[name] = val = self._getini(name) return val
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config.getini
8,682
def _getini(self, name): try: description, type, default = self._parser._inidict[name] except __HOLE__: raise ValueError("unknown configuration value: %r" %(name,)) try: value = self.inicfg[name] except KeyError: if default is not None: return default if type is None: return '' return [] if type == "pathlist": dp = py.path.local(self.inicfg.config.path).dirpath() l = [] for relpath in shlex.split(value): l.append(dp.join(relpath, abs=True)) return l elif type == "args": return shlex.split(value) elif type == "linelist": return [t for t in map(lambda x: x.strip(), value.split("\n")) if t] elif type == "bool": return bool(_strtobool(value.strip())) else: assert type is None return value
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._getini
8,683
def _getconftest_pathlist(self, name, path): try: mod, relroots = self.pluginmanager._rget_with_confmod(name, path) except __HOLE__: return None modpath = py.path.local(mod.__file__).dirpath() l = [] for relroot in relroots: if not isinstance(relroot, py.path.local): relroot = relroot.replace("/", py.path.local.sep) relroot = modpath.join(relroot, abs=True) l.append(relroot) return l
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config._getconftest_pathlist
8,684
def getoption(self, name, default=notset, skip=False): """ return command line option value. :arg name: name of the option. You may also specify the literal ``--OPT`` option instead of the "dest" option name. :arg default: default value if no option of that name exists. :arg skip: if True raise pytest.skip if option does not exists or has a None value. """ name = self._opt2dest.get(name, name) try: val = getattr(self.option, name) if val is None and skip: raise AttributeError(name) return val except __HOLE__: if default is not notset: return default if skip: import pytest pytest.skip("no %r option found" %(name,)) raise ValueError("no option named %r" % (name,))
AttributeError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/Config.getoption
8,685
def determine_setup(inifile, args): if inifile: iniconfig = py.iniconfig.IniConfig(inifile) try: inicfg = iniconfig["pytest"] except __HOLE__: inicfg = None rootdir = get_common_ancestor(args) else: ancestor = get_common_ancestor(args) rootdir, inifile, inicfg = getcfg( [ancestor], ["pytest.ini", "tox.ini", "setup.cfg"]) if rootdir is None: for rootdir in ancestor.parts(reverse=True): if rootdir.join("setup.py").exists(): break else: rootdir = ancestor return rootdir, inifile, inicfg or {}
KeyError
dataset/ETHPy150Open pytest-dev/pytest/_pytest/config.py/determine_setup
8,686
def create_client(self, name, app_id, valid_facets): ensure_valid_name(name) try: self.get_client(name) raise ValueError('Client already exists: %s' % name) except __HOLE__: client = Client(name, app_id, valid_facets) self._session.add(client) log.info('Client created: %s', name)
KeyError
dataset/ETHPy150Open Yubico/u2fval/u2fval/client/controller.py/ClientController.create_client
8,687
def library_paths(): """Iterates for library paths to try loading. The result paths are not guaranteed that they exist. :returns: a pair of libwand and libmagick paths. they can be the same. path can be ``None`` as well :rtype: :class:`tuple` """ libwand = None libmagick = None versions = '', '-6', '-Q16', '-Q8', '-6.Q16' options = '', 'HDRI', 'HDRI-2' system = platform.system() magick_home = os.environ.get('MAGICK_HOME') if system == 'Windows': # ImageMagick installers normally install coder and filter DLLs in # subfolders, we need to add those folders to PATH, otherwise loading # the DLL later will fail. try: with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\ImageMagick\Current") as reg_key: libPath = winreg.QueryValueEx(reg_key, "LibPath") coderPath = winreg.QueryValueEx(reg_key, "CoderModulesPath") filterPath = winreg.QueryValueEx(reg_key, "FilterModulesPath") magick_home = libPath[0] os.environ['PATH'] += (';' + libPath[0] + ";" + coderPath[0] + ";" + filterPath[0]) except __HOLE__: # otherwise use MAGICK_HOME, and we assume the coder and # filter DLLs are in the same directory pass def magick_path(path): return os.path.join(magick_home, *path) combinations = itertools.product(versions, options) for suffix in (version + option for version, option in combinations): # On Windows, the API is split between two libs. On other platforms, # it's all contained in one. if magick_home: if system == 'Windows': libwand = 'CORE_RL_wand_{0}.dll'.format(suffix), libmagick = 'CORE_RL_magick_{0}.dll'.format(suffix), yield magick_path(libwand), magick_path(libmagick) libwand = 'libMagickWand{0}.dll'.format(suffix), libmagick = 'libMagickCore{0}.dll'.format(suffix), yield magick_path(libwand), magick_path(libmagick) elif system == 'Darwin': libwand = 'lib', 'libMagickWand{0}.dylib'.format(suffix), yield magick_path(libwand), magick_path(libwand) else: libwand = 'lib', 'libMagickWand{0}.so'.format(suffix), yield magick_path(libwand), magick_path(libwand) if system == 'Windows': libwand = ctypes.util.find_library('CORE_RL_wand_' + suffix) libmagick = ctypes.util.find_library('CORE_RL_magick_' + suffix) yield libwand, libmagick libwand = ctypes.util.find_library('libMagickWand' + suffix) libmagick = ctypes.util.find_library('libMagickCore' + suffix) yield libwand, libmagick else: libwand = ctypes.util.find_library('MagickWand' + suffix) yield libwand, libwand
OSError
dataset/ETHPy150Open dahlia/wand/wand/api.py/library_paths
8,688
def load_library(): """Loads the MagickWand library. :returns: the MagickWand library and the ImageMagick library :rtype: :class:`ctypes.CDLL` """ tried_paths = [] for libwand_path, libmagick_path in library_paths(): if libwand_path is None or libmagick_path is None: continue try: tried_paths.append(libwand_path) libwand = ctypes.CDLL(libwand_path) if libwand_path == libmagick_path: libmagick = libwand else: tried_paths.append(libmagick_path) libmagick = ctypes.CDLL(libmagick_path) except (__HOLE__, OSError): continue return libwand, libmagick raise IOError('cannot find library; tried paths: ' + repr(tried_paths))
IOError
dataset/ETHPy150Open dahlia/wand/wand/api.py/load_library
8,689
def _parse_version(self, raw_version): err_msg = 'Unsupported version %r' % raw_version try: version = float(raw_version.lstrip('v')) except __HOLE__: raise ValueError(err_msg) if not any(version == v for v in RESPONSE_VERSIONS): raise ValueError(err_msg) return version
ValueError
dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware._parse_version
8,690
def _parse_path(self, request): """ Parse path parts of request into a tuple of version, account, container, obj. Unspecified path parts are filled in as None, except version which is always returned as a float using the configured default response version if not specified in the request. :param request: the swob request :returns: parsed path parts as a tuple with version filled in as configured default response version if not specified. :raises: ValueError if path is invalid, message will say why. """ clean_path = request.path[len(self.endpoints_path) - 1:] # try to peel off version try: raw_version, rest = split_path(clean_path, 1, 2, True) except __HOLE__: raise ValueError('No account specified') try: version = self._parse_version(raw_version) except ValueError: if raw_version.startswith('v') and '_' not in raw_version: # looks more like a invalid version than an account raise # probably no version specified, but if the client really # said /endpoints/v_3/account they'll probably be sorta # confused by the useless response and lack of error. version = self.default_response_version rest = clean_path else: rest = '/' + rest if rest else '/' try: account, container, obj = split_path(rest, 1, 3, True) except ValueError: raise ValueError('No account specified') return version, account, container, obj
ValueError
dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware._parse_path
8,691
def __call__(self, env, start_response): request = Request(env) if not request.path.startswith(self.endpoints_path): return self.app(env, start_response) if request.method != 'GET': return HTTPMethodNotAllowed( req=request, headers={"Allow": "GET"})(env, start_response) try: version, account, container, obj = self._parse_path(request) except __HOLE__ as err: return HTTPBadRequest(str(err))(env, start_response) if account is not None: account = unquote(account) if container is not None: container = unquote(container) if obj is not None: obj = unquote(obj) storage_policy_index = None if obj is not None: container_info = get_container_info( {'PATH_INFO': '/v1/%s/%s' % (account, container)}, self.app, swift_source='LE') storage_policy_index = container_info['storage_policy'] obj_ring = self.get_object_ring(storage_policy_index) partition, nodes = obj_ring.get_nodes( account, container, obj) endpoint_template = 'http://{ip}:{port}/{device}/{partition}/' + \ '{account}/{container}/{obj}' elif container is not None: partition, nodes = self.container_ring.get_nodes( account, container) endpoint_template = 'http://{ip}:{port}/{device}/{partition}/' + \ '{account}/{container}' else: partition, nodes = self.account_ring.get_nodes( account) endpoint_template = 'http://{ip}:{port}/{device}/{partition}/' + \ '{account}' endpoints = [] for node in nodes: endpoint = endpoint_template.format( ip=node['ip'], port=node['port'], device=node['device'], partition=partition, account=quote(account), container=quote(container or ''), obj=quote(obj or '')) endpoints.append(endpoint) resp = self.response_map[version]( request, endpoints=endpoints, storage_policy_index=storage_policy_index) return resp(env, start_response)
ValueError
dataset/ETHPy150Open openstack/swift/swift/common/middleware/list_endpoints.py/ListEndpointsMiddleware.__call__
8,692
def ext_pillar(minion_id, pillar, # pylint: disable=W0613 conf): ''' Check vault for all data ''' comps = conf.split() profile = {} if comps[0]: profile_name = comps[0] profile = __opts__.get(profile_name, {}) path = '/' if len(comps) > 1 and comps[1].startswith('path='): path = comps[1].replace('path=', '') try: pillar = salt.utils.vault.read_(path, profile=profile) except __HOLE__: log.error('No such path in vault profile {0}: {1}'.format(profile, path)) pillar = {} return pillar
KeyError
dataset/ETHPy150Open saltstack/salt/salt/pillar/vault.py/ext_pillar
8,693
def main(): global config, stream, observer, git_sync, notifier config = parse_config() stream = Stream(callback, config['local_path'], file_events=True) observer.schedule(stream) (git_sync, notifier) = gitsynclib.GitSync.setup_git_sync(config) git_sync.run_initial_sync() observer.start() try: while 1: pause() except __HOLE__: stop() return 0
KeyboardInterrupt
dataset/ETHPy150Open jachin/GitSync/src/gitsync/GitSync.py/main
8,694
def setUp(self): self.patcher = patch('ffmpegwrapper.ffmpeg.Popen') popen = self.patcher.start() self.instance = popen.return_value read_value = bytearray(b'this is a line\nthis too\n') poll = lambda: None if read_value else 0 def read(*args): try: return bytearray([read_value.pop(0)]) except __HOLE__: return b'' self.instance.poll.side_effect = poll self.instance.stdout.read.side_effect = read
IndexError
dataset/ETHPy150Open interru/ffmpegwrapper/test.py/FFmpegTestCase.setUp
8,695
def _connect(self): self._connection.connect() full_path = None try: full_path = self.path + '?' + urllib.urlencode(self.query_parameters) except __HOLE__: full_path = self.path + '?' + urllib.parse.urlencode(self.query_parameters) self._connection.putrequest('POST', full_path, skip_accept_encoding=1) headers = { 'Accept': 'application/json', 'Authorization': ('Bearer %s' % self.client_access_token) } headers.update(self._prepare_headers()) for header_key, header_value in headers.items(): self._connection.putheader(header_key, header_value) self._connection.endheaders() begin = self._prepage_begin_request_data() if not begin is None: self.send(begin.encode('utf-8'))
AttributeError
dataset/ETHPy150Open api-ai/api-ai-python/apiai/requests/request.py/Request._connect
8,696
def get_category(self): if 'pk' in self.kwargs: # Usual way to reach a category page. We just look at the primary # key, which is easy on the database. If the slug changed, get() # will redirect appropriately. # WARNING: Category.get_absolute_url needs to look up it's parents # to compute the URL. As this is slightly expensive, Oscar's # default implementation caches the method. That's pretty safe # as ProductCategoryView does the lookup by primary key, which # will work even if the cache is stale. But if you override this # logic, consider if that still holds true. return get_object_or_404(Category, pk=self.kwargs['pk']) elif 'category_slug' in self.kwargs: # DEPRECATED. TODO: Remove in Oscar 1.2. # For SEO and legacy reasons, we allow chopping off the primary # key from the URL. In that case, we have the target category slug # and it's ancestors' slugs concatenated together. # To save on queries, we pick the last slug, look up all matching # categories and only then compare. # Note that currently we enforce uniqueness of slugs, but as that # might feasibly change soon, it makes sense to be forgiving here. concatenated_slugs = self.kwargs['category_slug'] slugs = concatenated_slugs.split(Category._slug_separator) try: last_slug = slugs[-1] except __HOLE__: raise Http404 else: for category in Category.objects.filter(slug=last_slug): if category.full_slug == concatenated_slugs: message = ( "Accessing categories without a primary key" " is deprecated will be removed in Oscar 1.2.") warnings.warn(message, DeprecationWarning) return category raise Http404
IndexError
dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/catalogue/views.py/ProductCategoryView.get_category
8,697
def __getitem__(self, k): try: return getattr(self, k) except __HOLE__: raise KeyError
AttributeError
dataset/ETHPy150Open kbandla/dpkt/dpkt/dpkt.py/Packet.__getitem__
8,698
def prompt(): while True: try: term = float(input('+ ')) except __HOLE__: break yield term
ValueError
dataset/ETHPy150Open fluentpython/example-code/attic/control/adder/coroadder_deco.py/prompt
8,699
def main(get_terms): adder = adder_coro() for term in get_terms: adder.send(term) try: adder.send(None) except __HOLE__ as exc: result = exc.value print(result)
StopIteration
dataset/ETHPy150Open fluentpython/example-code/attic/control/adder/coroadder_deco.py/main