Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,200
def __fstat(self, dname, fname): try: fstat = os.stat(os.path.join(dname, fname)).st_mtime except __HOLE__, e: return False else: return fstat
OSError
dataset/ETHPy150Open zynga/hiccup/hiccup/FileWatcher.py/FileWatcher.__fstat
1,201
def next(self, iterateAbove=-1, bindingsLen=-1): # iterate hyperspace bindings if not self.hyperspaceBindings: raise StopIteration hsBsToReset = [] if bindingsLen == -1: bindingsLen = len(self.hyperspaceBindings) for iHsB in range(bindingsLen - 1, iterateAbove, -1): hsB = self.hyperspaceBindings[iHsB] try: hsB.next() for hsB in hsBsToReset: hsB.reset() return # hsB has another value to return except __HOLE__: hsBsToReset.insert(0, hsB) # reset after outer iterator advanced raise StopIteration # no more outermost loop of iteration
StopIteration
dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/sphinx/SphinxContext.py/HyperspaceBindings.next
1,202
def next(self): # will raise StopIteration if no (more) facts or fallback uncoveredAspectFacts = self.hyperspaceBindings.aspectBoundFacts if self.yieldedFact is not None and self.hyperspaceBindings.aggregationNode is None: for aspect, priorFact in self.evaluationContributedUncoveredAspects.items(): if priorFact == "none": del uncoveredAspectFacts[aspect] else: uncoveredAspectFacts[aspect] = priorFact self.evaluationContributedUncoveredAspects.clear() try: if self.isWithRestrictionNode: self.yieldedFactsPartition = next(self.factIter) for self.yieldedFact in self.yieldedFactsPartition: break else: self.yieldedFact = next(self.factIter) self.evaluationContributedUncoveredAspects = {} if not self.isValuesIteration: for aspect in self.unQualifiedAspects: # covered aspects may not be defined e.g., test 12062 v11, undefined aspect is a complemented aspect if uncoveredAspectFacts.get(aspect) is None: self.evaluationContributedUncoveredAspects[aspect] = uncoveredAspectFacts.get(aspect,"none") uncoveredAspectFacts[aspect] = None if aspect in self.axesAspects else self.yieldedFact if self.sCtx.formulaOptions.traceVariableFiltersResult: self.sCtx.modelXbrl.info("sphinx:trace", _("Hyperspace %(variable)s: bound value %(result)s"), sourceFileLine=self.node.sourceFileLine, variable=str(self.node), result=str(self.yieldedFact)) except __HOLE__: self.yieldedFact = None if self.isWithRestrictionNode: self.yieldedFactsPartition = [] if self.fallback and not self.fallenBack: self.fallenBack = True if self.sCtx.formulaOptions.traceVariableExpressionResult: self.sCtx.modelXbrl.info("sphinx:trace", _("Hyperspace %(variable)s: fallbackValue result %(result)s"), sourceFileLine=self.node.sourceFileLine, variable=str(self.node), result=0) else: raise StopIteration
StopIteration
dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/sphinx/SphinxContext.py/HyperspaceBinding.next
1,203
def next(self): # will raise StopIteration if no (more) facts or fallback try: self.yieldedValue = next(self.forIter) # set next value here as well as in for node, because may be cleared above context of for node self.sCtx.localVariables[self.node.name] = self.yieldedValue if self.sCtx.formulaOptions.traceVariableFiltersResult: self.sCtx.modelXbrl.info("sphinx:trace", _("For loop %(variable)s: bound value %(result)s"), sourceFileLine=self.node.sourceFileLine, variable=str(self.node.name), result=str(self.yieldedValue)) except __HOLE__: if self.yieldedValue is not None: del self.sCtx.localVariables[self.node.name] self.yieldedValue = None raise StopIteration
StopIteration
dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/sphinx/SphinxContext.py/ForBinding.next
1,204
def get_petsc_dir(): try: arch = '/' + env.get('PETSC_ARCH', '') dir = env['PETSC_DIR'] return (dir, dir + arch) except KeyError: try: import petsc return (petsc.get_petsc_dir(), ) except __HOLE__: sys.exit("""Error: Could not find PETSc library. Set the environment variable PETSC_DIR to your local PETSc base directory or install PETSc from PyPI: pip install petsc""")
ImportError
dataset/ETHPy150Open OP2/PyOP2/setup.py/get_petsc_dir
1,205
def _dispatch_request(self, seq, raw_args): try: handler, args = raw_args args = self._unbox(args) res = self._HANDLERS[handler](self, *args) except __HOLE__: raise except: # need to catch old style exceptions too t, v, tb = sys.exc_info() self._last_traceback = tb if self._config["logger"]: self._config["logger"].debug("Exception caught", exc_info=True) if t is SystemExit and self._config["propagate_SystemExit_locally"]: raise self._send_exception(seq, t, v, tb) else: self._send_reply(seq, res)
KeyboardInterrupt
dataset/ETHPy150Open sccn/SNAP/src/rpyc/core/protocol.py/Connection._dispatch_request
1,206
def serve_all(self): """Serves all requests and replies for as long as the connection is alive.""" try: try: while True: self.serve(0.1) except (socket.error, select_error, __HOLE__): if not self.closed: raise except EOFError: pass except Exception,e: print "Exception during serve_all:" print e finally: self.close()
IOError
dataset/ETHPy150Open sccn/SNAP/src/rpyc/core/protocol.py/Connection.serve_all
1,207
def _handle_cmp(self, oid, other): # cmp() might enter recursive resonance... yet another workaround #return cmp(self._local_objects[oid], other) obj = self._local_objects[oid] try: return type(obj).__cmp__(obj, other) except (AttributeError, __HOLE__): return NotImplemented
TypeError
dataset/ETHPy150Open sccn/SNAP/src/rpyc/core/protocol.py/Connection._handle_cmp
1,208
def _handle_buffiter(self, oid, count): items = [] obj = self._local_objects[oid] i = 0 try: while i < count: items.append(next(obj)) i += 1 except __HOLE__: pass return tuple(items)
StopIteration
dataset/ETHPy150Open sccn/SNAP/src/rpyc/core/protocol.py/Connection._handle_buffiter
1,209
def cache_scan(self): try: return len(self.transformations) - self.transformations[::-1].index(CACHE_T) except __HOLE__: return 0
ValueError
dataset/ETHPy150Open EntilZha/PyFunctional/functional/lineage.py/Lineage.cache_scan
1,210
def simplify_ops(ops): addDict = {} deleteDict = {} for op_count, op in enumerate(ops): op.db_id = -op_count - 1 if op.vtType == 'add': addDict[(op.db_what, op.db_objectId)] = op elif op.vtType == 'delete': try: del addDict[(op.db_what, op.db_objectId)] except KeyError: deleteDict[(op.db_what, op.db_objectId)] = op elif op.vtType == 'change': try: k = addDict[(op.db_what, op.db_oldObjId)] except __HOLE__: addDict[(op.db_what, op.db_newObjId)] = op else: old_old_id = getOldObjId(k) del addDict[(op.db_what, op.db_oldObjId)] addDict[(op.db_what, op.db_newObjId)] = \ DBChange(id=opCount, what=op.db_what, oldObjId=old_old_id, newObjId=op.db_newObjId, parentObjId=op.db_parentObjId, parentObjType=op.db_parentObjType, data=op.db_data, ) deletes = deleteDict.values() deletes.sort(key=lambda x: -x.db_id) # faster than sort(lambda x, y: -cmp(x.db_id, y.db_id)) adds = addDict.values() adds.sort(key=lambda x: -x.db_id) # faster than sort(lambda x, y: -cmp(x.db_id, y.db_id)) return deletes + adds
KeyError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/db/services/action_chain.py/simplify_ops
1,211
def getCurrentOperationDict(actions, currentOperations=None): if currentOperations is None: currentOperations = {} # note that this operation assumes unique ids for each operation's data # any add adds to the dict, delete removes from the dict, and # change replaces the current value in the dict for action in actions: for operation in action.db_operations: operationvtType = operation.vtType d = operation.__dict__ if operationvtType == 'add': currentOperations[(d['_db_what'], d['_db_objectId'])] = \ operation elif operationvtType == 'delete': what = d['_db_what'] objectId = d['_db_objectId'] t = (what, objectId) try: del currentOperations[t] except KeyError: msg = "Illegal delete operation: %d" % d['_db_id'] raise RuntimeError(msg) elif operationvtType == 'change': what = d['_db_what'] objectId = d['_db_oldObjId'] t = (what, objectId) try: del currentOperations[t] except __HOLE__: msg = "Illegal change operation: %d" % d['_db_id'] raise RuntimeError(msg) currentOperations[(what, d['_db_newObjId'])] = operation else: msg = "Unrecognized operation '%s'" % operation.vtType raise TypeError(msg) return currentOperations
KeyError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/db/services/action_chain.py/getCurrentOperationDict
1,212
def contour(x, y, z, data=None, marker=None, alpha=.5, xscale='linear', yscale='linear', cmap=None, ncontours=100, gridsize=100, colorbar=True, labels=False, figsize=(12, 6), filled=True, fig=None, axes=None, cgrid=None, axislabels=True, axisticks=True, **kwargs): """ Create a contour plot from x, y, ans z values """ # if no dataframe is supplied, create one if data is None: (x, y, z, _), data = components.create_df(x, y, z, _) df = data.copy() df = df[[i for i in (x, y, z) if i]] df = df.dropna() df = df.reset_index() if fig and not axes: fig = fig canvas = mbb.FigureCanvasAgg(fig) axm, axc, axl, axt = components.get_axes_1(fig) elif axes: axm = axes else: fig = mpl.figure.Figure(figsize=figsize, tight_layout=True) canvas = mbb.FigureCanvasAgg(fig) axm, _, _, _ = components.create_axes(False, False, False, fig=fig) xi = np.linspace(np.min(df[x]), np.max(df[x]), gridsize) yi = np.linspace(np.min(df[y]), np.max(df[y]), gridsize) try: zi = mpl.mlab.griddata(df[x], df[y], df[z], xi, yi, interp='linear') except __HOLE__: return if filled: cf = axm.contourf(xi, yi, zi, ncontours, cmap=cmap, **kwargs) else: cf = axm.contour(xi, yi, zi, ncontours, cmap=cmap, **kwargs) if not axisticks: axm.get_xaxis().set_visible(False) axm.get_yaxis().set_visible(False) if marker: axm.scatter(df[x], df[y], marker=marker, color='k') if colorbar and not axes: fig.colorbar(cf) if labels: axm.clabel(cf) axm.set_xlim(np.min(df[x]), np.max(df[x])) axm.set_ylim(np.min(df[y]), np.max(df[y])) axm.set_yscale(yscale) axm.set_xscale(xscale) if axislabels: axm.set_xlabel(x) axm.set_ylabel(y) if axes: return axm else: return canvas.figure
ValueError
dataset/ETHPy150Open beltashazzer/jmpy/jmpy/plotting/contour.py/contour
1,213
def get_reconciler_content_type(op): try: return { 'put': 'application/x-put', 'delete': 'application/x-delete', }[op.lower()] except __HOLE__: raise ValueError('invalid operation type %r' % op)
KeyError
dataset/ETHPy150Open openstack/swift/swift/container/reconciler.py/get_reconciler_content_type
1,214
def parse_raw_obj(obj_info): """ Translate a reconciler container listing entry to a dictionary containing the parts of the misplaced object queue entry. :param obj_info: an entry in an a container listing with the required keys: name, content_type, and hash :returns: a queue entry dict with the keys: q_policy_index, account, container, obj, q_op, q_ts, q_record, and path """ raw_obj_name = obj_info['name'].encode('utf-8') policy_index, obj_name = raw_obj_name.split(':', 1) q_policy_index = int(policy_index) account, container, obj = split_path(obj_name, 3, 3, rest_with_last=True) try: q_op = { 'application/x-put': 'PUT', 'application/x-delete': 'DELETE', }[obj_info['content_type']] except __HOLE__: raise ValueError('invalid operation type %r' % obj_info.get('content_type', None)) return { 'q_policy_index': q_policy_index, 'account': account, 'container': container, 'obj': obj, 'q_op': q_op, 'q_ts': decode_timestamps((obj_info['hash']))[0], 'q_record': last_modified_date_to_timestamp( obj_info['last_modified']), 'path': '/%s/%s/%s' % (account, container, obj) }
KeyError
dataset/ETHPy150Open openstack/swift/swift/container/reconciler.py/parse_raw_obj
1,215
def test_raises_when_start_address_not_found(self): text = 'aa bb cc' try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Start address was not found in data' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_start_address_not_found
1,216
def test_raises_when_start_address_is_invalid(self): text = 'oops: aa bb cc' try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Could not parse address: oops' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_start_address_is_invalid
1,217
def test_raises_when_start_address_is_too_short(self): text = '01: aa bb cc' try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Expected address to be 2 bytes, got 1' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_start_address_is_too_short
1,218
def test_raises_when_start_address_is_too_long(self): text = '010304: aa bb cc' try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Expected address to be 2 bytes, got 3' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_start_address_is_too_long
1,219
def test_raises_when_next_address_is_unexpected(self): text = "c000: aa\nc002: cc" try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Non-contigous block detected. Expected next ' \ 'address to be $c001, label was $c002' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_next_address_is_unexpected
1,220
def test_raises_when_data_is_invalid(self): text = 'c000: foo' try: Loader(text) self.fail() except __HOLE__ as exc: msg = 'Could not parse data: foo' self.assertEqual(msg, str(exc))
ValueError
dataset/ETHPy150Open mnaberez/py65/py65/tests/utils/test_hexdump.py/HexdumpLoaderTests.test_raises_when_data_is_invalid
1,221
def __str__(self): try: import cStringIO as StringIO except __HOLE__: import StringIO output = StringIO.StringIO() output.write(Exception.__str__(self)) # Check if we wrapped an exception and print that too. if hasattr(self, 'exc_info'): import traceback output.write('\n\nOriginal ') e = self.exc_info traceback.print_exception(e[0], e[1], e[2], 500, output) return output.getvalue()
ImportError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/TemplateSyntaxError.__str__
1,222
def __init__(self, template_string, origin=None, name='<Unknown Template>'): try: template_string = smart_unicode(template_string) except __HOLE__: raise TemplateEncodingError("Templates can only be constructed from unicode or UTF-8 strings.") if settings.TEMPLATE_DEBUG and origin is None: origin = StringOrigin(template_string) self.nodelist = compile_string(template_string, origin) self.name = name
UnicodeDecodeError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/Template.__init__
1,223
def parse(self, parse_until=None): if parse_until is None: parse_until = [] nodelist = self.create_nodelist() while self.tokens: token = self.next_token() if token.token_type == TOKEN_TEXT: self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token.token_type == TOKEN_VAR: if not token.contents: self.empty_variable(token) filter_expression = self.compile_filter(token.contents) var_node = self.create_variable_node(filter_expression) self.extend_nodelist(nodelist, var_node,token) elif token.token_type == TOKEN_BLOCK: if token.contents in parse_until: # put token back on token list so calling code knows why it terminated self.prepend_token(token) return nodelist try: command = token.contents.split()[0] except __HOLE__: self.empty_block_tag(token) # execute callback function for this tag and append resulting node self.enter_command(command, token) try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command) try: compiled_result = compile_func(self, token) except TemplateSyntaxError, e: if not self.compile_function_error(token, e): raise self.extend_nodelist(nodelist, compiled_result, token) self.exit_command() if parse_until: self.unclosed_block_tag(parse_until) return nodelist
IndexError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/Parser.parse
1,224
def extend_nodelist(self, nodelist, node, token): if node.must_be_first and nodelist: try: if nodelist.contains_nontext: raise AttributeError except __HOLE__: raise TemplateSyntaxError("%r must be the first tag in the template." % node) if isinstance(nodelist, NodeList) and not isinstance(node, TextNode): nodelist.contains_nontext = True nodelist.append(node)
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/Parser.extend_nodelist
1,225
def args_check(name, func, provided): provided = list(provided) plen = len(provided) # Check to see if a decorator is providing the real function. func = getattr(func, '_decorated_function', func) args, varargs, varkw, defaults = getargspec(func) # First argument is filter input. args.pop(0) if defaults: nondefs = args[:-len(defaults)] else: nondefs = args # Args without defaults must be provided. try: for arg in nondefs: provided.pop(0) except __HOLE__: # Not enough raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen)) # Defaults can be overridden. defaults = defaults and list(defaults) or [] try: for parg in provided: defaults.pop(0) except IndexError: # Too many. raise TemplateSyntaxError("%s requires %d arguments, %d provided" % (name, len(nondefs), plen)) return True
IndexError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/FilterExpression.args_check
1,226
def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. self.literal = float(var) # So it's a float... is it an int? If the original value contained a # dot or an "e" then it was a float, not an int. if '.' not in var and 'e' not in var.lower(): self.literal = int(self.literal) # "2." is invalid if var.endswith('.'): raise ValueError except __HOLE__: # A ValueError means that the variable isn't a number. if var.startswith('_(') and var.endswith(')'): # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. if var[0] in "\"'" and var[0] == var[-1]: self.literal = mark_safe(var[1:-1]) else: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR))
ValueError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/Variable.__init__
1,227
def _resolve_lookup(self, context): """ Performs resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context for bit in self.lookups: try: # dictionary lookup current = current[bit] except (TypeError, AttributeError, KeyError): try: # attribute lookup current = getattr(current, bit) if callable(current): if getattr(current, 'alters_data', False): current = settings.TEMPLATE_STRING_IF_INVALID else: try: # method call (assuming no args required) current = current() except TypeError: # arguments *were* required # GOTCHA: This will also catch any TypeError # raised in the function itself. current = settings.TEMPLATE_STRING_IF_INVALID # invalid method call except Exception, e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: raise except (TypeError, AttributeError): try: # list-index lookup current = current[int(bit)] except (IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key __HOLE__, # unsubscriptable object ): raise VariableDoesNotExist("Failed lookup for key [%s] in %r", (bit, current)) # missing attribute except Exception, e: if getattr(e, 'silent_variable_failure', False): current = settings.TEMPLATE_STRING_IF_INVALID else: raise return current
TypeError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/Variable._resolve_lookup
1,228
def render(self, context): try: output = force_unicode(self.filter_expression.resolve(context)) except __HOLE__: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail quietly. return '' if (context.autoescape and not isinstance(output, SafeData)) or isinstance(output, EscapeData): return force_unicode(escape(output)) else: return force_unicode(output)
UnicodeDecodeError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/VariableNode.render
1,229
def get_library(module_name): lib = libraries.get(module_name, None) if not lib: try: mod = __import__(module_name, {}, {}, ['']) except __HOLE__, e: raise InvalidTemplateLibrary("Could not load template library from %s, %s" % (module_name, e)) try: lib = mod.register libraries[module_name] = lib except AttributeError: raise InvalidTemplateLibrary("Template library %s does not have a variable named 'register'" % module_name) return lib
ImportError
dataset/ETHPy150Open dcramer/django-compositepks/django/template/__init__.py/get_library
1,230
def clean(self, value): super(LVPersonalCodeField, self).clean(value) if value in EMPTY_VALUES: return '' match = re.match(idcode, value) if not match: raise ValidationError(self.error_messages['invalid_format']) day, month, year, century, check = map(int, match.groups()) if check != self.lv_checksum(value[0:6] + value[7:11]): raise ValidationError(self.error_messages['invalid']) year += 1800 + 100 * century try: date(year, month, day) except __HOLE__: raise ValidationError(self.error_messages['invalid']) return value
ValueError
dataset/ETHPy150Open django/django-localflavor/localflavor/lv/forms.py/LVPersonalCodeField.clean
1,231
@staticmethod def parse_bool(val, _states={ '1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False }): try: return _states[val.lower()] except __HOLE__: raise ValueError(val)
KeyError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/Conf.parse_bool
1,232
def strip_noise_bytes( obj, replace=u'_', encoding='utf-8', byte_errors='backslashreplace', unicode_errors='replace' ): '''Converts obj to byte representation, making sure there arent any random weird chars that dont belong to any alphabet. Only ascii non-letters are allowed, as fancy symbols don't seem to work too.''' if not isinstance(obj, types.StringTypes): obj = bytes(obj) if isinstance(obj, bytes): obj = force_unicode(obj, encoding=encoding, errors=byte_errors) obj_ucs = list() for uc in obj: try: unicodedata.name(uc) if unicodedata.category(uc) != 'Ll': uc.encode('ascii') except (__HOLE__, UnicodeEncodeError): if replace: obj_ucs.append(replace) else: obj_ucs.append(uc) obj = u''.join(obj_ucs) return force_bytes(obj, encoding=encoding, errors=unicode_errors)
ValueError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/strip_noise_bytes
1,233
def _child_readline_poll(self): 'child.stdout.readline() that also reacts to signals.' # One shitty ipc instead of another... good job! line = None while True: if '\n' in self.line_buff: line, self.line_buff = self.line_buff.split('\n', 1) if line is not None: return line try: evs = self.poller.poll(self.poll_timeout) or list() except IOError as err: if err.errno != errno.EINTR: raise return '' except __HOLE__: # ^C in console, probably because UI hangs raise PAMixerIPCError('Poll call interrupted') if not evs: log.debug( 'Parent poll timeout event,' ' likely a race condition bug (timeout: %.1fs)', self.poll_timeout ) line = '' for fd, ev in evs: if fd == self.wakeup_fd.fileno(): try: self.wakeup_fd.read(1) except IOError as err: if err.errno != errno.EAGAIN: raise log.debug('Got EAGAIN from' ' wakeup_fd returned by poll(), this should not happen') if line is None: line = '' # make sure to break the loop here else: if not ev & select.EPOLLIN: raise IOError('Poll returned error event: {}'.format(ev)) try: chunk = self._child.stdout.read(2**20) except IOError as err: if err.errno != errno.EAGAIN: raise continue self.line_buff += chunk
KeyboardInterrupt
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge._child_readline_poll
1,234
def _child_readline(self, wait_for_cid=None, one_signal=False, init_line=False): ts0 = mono_time() while True: if wait_for_cid and wait_for_cid in self.child_calls: # XXX: check for errors indicating that dbus is gone here? line_ts, line = self.child_calls.pop(wait_for_cid) if random.random() < self.child_calls_cleanup[0]: ts_deadline = mono_time() - self.child_calls_cleanup[1] for k, (line_ts, line) in self.child_calls.items(): if line_ts < ts_deadline: self.child_calls.pop(k, None) return line try: line = self._child_readline_poll().strip() if not line: # likely a break on signal, shouldn't be too often if mono_time() - ts0 > self.proxy_call_timeout: raise PAMixerIPCError('Call timeout: {:.2f}s'.format(self.proxy_call_timeout)) continue except PAMixerIPCError as err: raise PAMixerIPCError( 'IPC error while waiting for event {!r} (line_buff: {!r}): {}'\ .format(dict(wait_for_cid=wait_for_cid, one_signal=one_signal), self.line_buff, err) ) if init_line: assert line.strip() == 'ready', repr(line) break self.line_debug.append(('rpc-parent(raw) << %r', line)) if self.log_pipes: log.debug(*self.line_debug[-1]) try: line = json.loads(line) except __HOLE__ as err: # json module error doesn't provide the actual data raise ValueError('Failed to parse line ({}): {!r}', err, line) if line['t'] == 'signal': self.child_sigs.append(line) if one_signal: break elif line['t'] in ['call_result', 'call_error']: self.child_calls[line['cid']] = mono_time(), line
ValueError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge._child_readline
1,235
def signal_handler(self, sig=None, frm=None): log.debug('Signal handler triggered by: %s', sig) if not self.child_sigs: self._child_readline(one_signal=True) while True: try: line = self.child_sigs.popleft() except __HOLE__: break self.signal_func(**line)
IndexError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge.signal_handler
1,236
def child_kill(self): if self._child: child, self._child = self._child, None self._child_gc.add(child.pid) try: child.kill() # no need to be nice here except __HOLE__ as err: log.debug('child_kill error: %s', err) else: log.debug('child_kill invoked with no child around')
OSError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge.child_kill
1,237
def child_check_restart(self, sig=None, frm=None): if self._child_check: return # likely due to SIGCHLD from Popen self._child_check = True try: if self._child_gc: # these are cleaned-up just to avoid keeping zombies around for pid in list(self._child_gc): try: res = os.waitpid(pid, os.WNOHANG) except __HOLE__: res = pid, None if res and res[0]: self._child_gc.remove(pid) self.child_start() if not self._child: return # can't be started if self._child.poll() is not None: log.debug('glib/dbus child pid (%s) died. restarting it', self._child.pid) self.child_start(gc_old_one=True) finally: self._child_check = False
OSError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge.child_check_restart
1,238
@_glib_err_wrap def _core_notify(self, _signal=False, **kws): chunk = dict(**kws) self.line_debug.append(('rpc-child(py) >> %s', chunk)) if self.log_pipes: log.debug(*self.line_debug[-1]) chunk = json.dumps(chunk) assert '\n' not in chunk, chunk try: if _signal: os.kill(self.core_pid, self.signal) self.stdout.write('{}\n'.format(chunk)) except __HOLE__: return self.loop.quit() # parent is gone, we're done too
IOError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge._core_notify
1,239
@_glib_err_wrap def _rpc_call(self, buff, stream=None, ev=None): assert stream is self.stdin, [stream, self.stdin] if ev is None: ev = self._glib.IO_IN if ev & (self._glib.IO_ERR | self._glib.IO_HUP): return self.loop.quit() # parent is gone, we're done too elif ev & self._glib.IO_IN: while True: try: chunk = self.stdin.read(2**20) except __HOLE__ as err: if err.errno != errno.EAGAIN: raise chunk = None if not chunk: break buff.append(chunk) while True: # Detect if there are any full requests buffered for n, chunk in enumerate(buff): if '\n' in chunk: break else: break # no more full requests # Read/decode next request from buffer req = list() for m in xrange(n+1): chunk = buff.popleft() if m == n: chunk, chunk_next = chunk.split('\n', 1) buff.appendleft(chunk_next) assert '\n' not in chunk, chunk req.append(chunk) req = json.loads(''.join(req)) self.line_debug.append(('rpc-child(py) << %s', req)) if self.log_pipes: log.debug(*self.line_debug[-1]) # Run dbus call and return the result, synchronously assert req['t'] == 'call', req func, kws = req['func'], dict() obj_path, iface = req.get('obj'), req.get('iface') args, translate = req['args'], req.get('translate') if iface: kws['dbus_interface'] = dbus_abbrev(iface) if translate: args = self._dbus_val(args, translate) obj = self.core if not obj_path\ else self.bus.get_object(object_path=obj_path) # XXX: bus gone handling log.debug('DBus call: %s %s %s', func, args, kws) try: res = getattr(obj, func)(*args, **kws) except self._dbus.exceptions.DBusException as err: self._core_notify( t='call_error', cid=req['cid'], err_type=err.get_dbus_name(), err_msg=err.message ) else: res = strip_dbus_types(res) self._core_notify(t='call_result', cid=req['cid'], val=res) else: log.warn('Unrecognized event type from glib: %r', ev)
IOError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge._rpc_call
1,240
def child_run(self): from dbus.mainloop.glib import DBusGMainLoop from gi.repository import GLib import dbus def excepthook(t, v, tb, hook=sys.excepthook): time.sleep(0.2) # to dump parent/child tracebacks non-interleaved return hook(t, v, tb) sys.excepthook = excepthook self._dbus, self._glib = dbus, GLib # Disable stdin/stdout buffering self.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0) self.stdin = os.fdopen(sys.stdin.fileno(), 'rb', 0) self.stdout.write('ready\n') # wait for main process to get ready, signal readiness log.debug('DBus signal handler subprocess started') DBusGMainLoop(set_as_default=True) self.loop, self.loop_exc = GLib.MainLoop(), None self.bus = self._get_bus() # XXX: bus gone handling self.core = self.bus.get_object(object_path='/org/pulseaudio/core1') rpc_buffer = deque() flags = fcntl.fcntl(self.stdin, fcntl.F_GETFL) fcntl.fcntl(self.stdin, fcntl.F_SETFL, flags | os.O_NONBLOCK) self._glib.io_add_watch( self.stdin, self._glib.PRIORITY_DEFAULT, self._glib.IO_IN | self._glib.IO_ERR | self._glib.IO_HUP, ft.partial(self._rpc_call, rpc_buffer) ) signals = ['NewSink', 'SinkRemoved', 'NewPlaybackStream', 'PlaybackStreamRemoved'] if self.handle_proplist_updates: signals.append('Stream.PropertyListUpdated') for sig_name in signals: sig_name_last = sig_name.rsplit('.')[-1] self.bus.add_signal_receiver( ft.partial(self._relay_signal, sig_name=sig_name_last), sig_name_last, path_keyword='src_obj_path' ) self.core.ListenForSignal(dbus_join('pulse', [sig_name]), self._dbus.Array(signature='o')) self._glib.unix_signal_add(self._glib.PRIORITY_HIGH, signal.SIGTERM, self.loop.quit) try: self.loop.run() except __HOLE__: pass # XXX: wrapper loop here, in case of *clean* loop.quit() yet dbus not being dead if self.loop_exc: raise self.loop_exc[0], self.loop_exc[1], self.loop_exc[2]
KeyboardInterrupt
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerDBusBridge.child_run
1,241
def _get_name_descriptive(self): 'Can probably fail with KeyError if something is really wrong with stream/device props.' ext, props = None, dict( (force_bytes(k), strip_noise_bytes(v, self.conf.broken_chars_replace)) for k,v in self.props.viewitems() ) if self.t == 'stream': if self.conf.use_media_name: name = props.get('media.name') if name and name not in self.conf.placeholder_media_names: return name try: name = props['application.name'] except KeyError: # some synthetic stream with non-descriptive name name = self._get_name_unique(props['media.name']) ext = '({application.process.user}@'\ '{application.process.host}:{application.process.id})' elif self.t == 'sink': if self.conf.use_device_name: name = self._prop_get('Name') else: name = props.get('alsa.id')\ or props.get('device.description') or props.get('device.api') if not name: try: name = '{}.{}'.format(props['device.api'], props['device.string']) except KeyError: self._get_name_unique(props['device.description']) ext = '({device.profile.name}@{alsa.driver_name})' else: raise KeyError('Unknown menu-item type (for naming): {}'.format(self.t)) if ext: try: name = '{} {}'.format( name, re.sub(r'\{([^}]+)\}', r'{}', ext).format( *op.itemgetter(*re.findall(r'\{([^}]+)\}', ext))(props) ) ) except __HOLE__ as err: log.debug( 'Unable to get extended descriptive name' ' (trype: %r, path: %s) due to missing key: %s', self.t, self.dbus_path, err ) return name
KeyError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerMenuItem._get_name_descriptive
1,242
def _run(self, stdscr): c, self.c_stdscr = self.c, stdscr key_match = lambda key,*choices: key in map(self.c_key, choices) c.curs_set(0) c.use_default_colors() win = self.c_win_init() self.conf.adjust_step /= 100.0 while True: try: # XXX: full refresh on every keypress is a bit excessive items, item_hl = self.menu.item_list, self.item_hl if item_hl is None: item_hl = self.item_hl = self.menu.item_default() if item_hl not in items: item_hl = self.menu.item_default() self.c_win_draw(win, items, item_hl) except PAMixerDBusError as err: if err.args[0] == 'org.freedesktop.DBus.Error.UnknownMethod': continue raise # XXX: check all the old pitfalls here watchdog_handle_ping() key = None while True: try: key = win.getch() except KeyboardInterrupt: key = self.c_key('q') except c.error: break try: key_name = c.keyname(key) except __HOLE__: key_name = 'unknown' # e.g. "-1" if watchdog_handle_ping(): assert win.getch() == -1 # no idea why continue break if key is None: continue log.debug('Keypress event: %s (%r)', key, key_name) if item_hl: if key_match(key, 'up', 'k', 'p'): self.item_hl = item_hl.get_prev() elif key_match(key, 'down', 'j', 'n'): self.item_hl = item_hl.get_next() elif key_match(key, 'left', 'h', 'b'): item_hl.volume_change(-self.conf.adjust_step) elif key_match(key, 'right', 'l', 'f'): item_hl.volume_change(self.conf.adjust_step) elif key_match(key, ' ', 'm'): item_hl.muted_toggle() elif key_name.isdigit(): # 1-0 keyboard row item_hl.volume = (float(key_name) or 10.0) / 10 # 0 is 100% if key_match(key, 'resize', '\f'): if self.conf.overkill_redraw: c.endwin() stdscr.refresh() win = self.c_win_init() else: win.resize(*win.getmaxyx()) elif key_match(key, 'q'): break
ValueError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/PAMixerUI._run
1,243
def watchdog_run(conf, args): signal.signal(signal.SIGUSR2, watchdog_run_pong) proc = proc_poller = None proc_pongs = 0 while True: if not proc: r, w = os.pipe() proc_opts = list(args) + [ '--parent-pid-do-not-use', 'w{}-{}'.format(os.getpid(), w) ] proc = subprocess.Popen(self_exec_cmd(*proc_opts)) os.close(w) assert os.read(r, 1) == '!' proc_poller = select.epoll() proc_poller.register(r, select.EPOLLHUP) watchdog_run.ping_last_ts = ts_ping = ts_timeout = None ts = mono_time() if ts_timeout and ts >= ts_timeout: proc_running, proc_restart = proc.poll() is None, proc_pongs >= 2 log.debug( 'wd: !!! sending exit-signal (to %s, running: %s, restart: %s, pongs: %s) !!!', proc.pid, proc_running, proc_restart, proc_pongs ) if proc: if proc_running: try: proc.send_signal(signal.SIGALRM) if not proc_poller.poll(min(conf.watchdog_ping_timeout, 3)): log.debug('wd: killing stuck pid %s', proc.pid) proc.send_signal(signal.SIGCONT) proc.kill() except (__HOLE__, IOError) as err: if err.errno not in [errno.ESRCH, errno.EINTR]: raise proc.wait() proc, proc_pongs = None, 0 if not proc_restart: log.error( 'wd: main process failed without enough' ' pongs from it, not restarting to avoid endless restart-loop' ) return 1 continue ts_ping_last = getattr(watchdog_run, 'ping_last_ts', None) if ts_ping_last: watchdog_run.ping_last_ts = None proc_pongs += 1 ts_timeout = ts_ping_last + conf.watchdog_ping_timeout if not ts_ping: ts_ping = ts_ping_last + conf.watchdog_ping_interval if ts_ping and ts >= ts_ping: log.debug('wd: sending ping (to %s)', proc.pid) try: proc.send_signal(signal.SIGUSR2) except OSError as err: if err.errno != errno.ESRCH: raise continue while ts_ping <= ts: ts_ping = ts_ping + conf.watchdog_ping_interval deadline = min(ts_ping or ts_timeout, ts_timeout or ts_ping)\ if ts_ping or ts_timeout else (ts + conf.watchdog_ping_interval) try: proc_poller.poll(max(0.1, deadline - ts)) except IOError: pass if proc.poll() is not None: err = proc.wait() if err != 0: proc = None log.debug( 'wd: detected process exit' ' (code: %s), %s', err, 'exiting' if proc else 'restarting it' ) if proc: return err
OSError
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/watchdog_run
1,244
def main(args=None): conf = Conf() conf_file = os.path.expanduser('~/.pulseaudio-mixer-cli.cfg') try: conf_file = open(conf_file) except (OSError, IOError) as err: pass else: update_conf_from_file(conf, conf_file) import argparse parser = argparse.ArgumentParser(description='Command-line PulseAudio mixer tool.') parser.add_argument('-a', '--adjust-step', action='store', type=int, metavar='step', default=conf.adjust_step, help='Adjustment for a single keypress in interactive mode (0-100%%, default: %(default)s%%).') parser.add_argument('-l', '--max-level', action='store', type=int, metavar='level', default=conf.max_level, help='Value to treat as max (default: %(default)s).') parser.add_argument('-n', '--use-media-name', action='store_true', default=conf.use_media_name, help='Display streams by "media.name" property, if possible.' ' Default is to prefer application name and process properties.') parser.add_argument('-v', '--verbose', action='store_true', default=conf.verbose, help='Dont close stderr to see any sort of errors (which' ' mess up curses interface, thus silenced that way by default).') parser.add_argument('-w', '--watchdog', action='store_true', default=conf.watchdog, help='Run watchdog pid to restart the thing if it hangs.') parser.add_argument('--dump-stream-params', action='store_true', help='Dump all parameters for each stream to stderr.') parser.add_argument('--debug', action='store_true', help='Verbose operation mode.') parser.add_argument('--debug-pipes', action='store_true', help='Also logs chatter between parent/child pids. Very noisy, only useful with --debug.') parser.add_argument('--fatal', action='store_true', help='Dont try too hard to recover from errors. For debugging purposes only.') parser.add_argument('--parent-pid-do-not-use', metavar='pid', help='Used internally to spawn dbus sub-pid, should not be used directly.') args = sys.argv[1:] if args is None else args opts = parser.parse_args(args) for k,v in vars(opts).viewitems(): setattr(conf, k, v) del opts global log, print log_pid = os.getpid() logging.basicConfig( level=logging.DEBUG if conf.debug else logging.WARNING, format='%(asctime)s :: {} %(levelname)s :: %(message)s'.format(uid_str(log_pid)), datefmt='%Y-%m-%d %H:%M:%S' ) log = logging.getLogger() print= ft.partial(print, file=sys.stderr) # stdout is used by curses or as a pipe (child) log.debug('Starting script (child: %s, pid: %s)', bool(conf.parent_pid_do_not_use), log_pid) if conf.parent_pid_do_not_use: pid = conf.parent_pid_do_not_use if pid.startswith('w'): conf.watchdog_opts = map(int, pid.lstrip('w').split('-', 1)) else: dbus_bridge = PAMixerDBusBridge(core_pid=int(pid), log_pipes=conf.debug_pipes) if conf.use_media_name: dbus_bridge.handle_proplist_updates = True try: return dbus_bridge.child_run() finally: if log.isEnabledFor(logging.INFO): log_lines( log.info, ['Last pipe traffic (child pid side):'] + list(dbus_bridge.line_debug) ) if not conf.watchdog_opts: if conf.watchdog: try: return watchdog_run(conf, args) except __HOLE__: return 0 else: pid, fd = conf.watchdog_opts os.write(fd, '!') watchdog_handle(pid) dbus_bridge = ['--parent-pid-do-not-use', bytes(os.getpid())] if conf.debug: dbus_bridge += ['--debug'] if conf.debug_pipes: dbus_bridge += ['--debug-pipes'] if conf.use_media_name: dbus_bridge += ['--use-media-name'] dbus_bridge = PAMixerDBusBridge( self_exec_cmd(*dbus_bridge), fatal=conf.fatal, log_pipes=conf.debug_pipes ) menu = PAMixerMenu(dbus_bridge, conf, fatal=conf.fatal) dbus_bridge.install_signal_handler(menu.update_signal) dbus_bridge.child_start() with PAMixerUI(menu) as curses_ui: # Any output will mess-up curses ui, so try to close sys.stderr if possible if not conf.verbose and not conf.debug\ and not conf.dump_stream_params: sys.stderr.close() log.debug('Entering curses ui loop...') try: curses_ui.run() except: if log.isEnabledFor(logging.INFO): log_lines( log.info, ['Last pipe traffic (parent pid side):'] + list(dbus_bridge.line_debug) ) raise log.debug('Finished')
KeyboardInterrupt
dataset/ETHPy150Open mk-fg/pulseaudio-mixer-cli/pa-mixer-mk2.py/main
1,245
def children(self): """ List the children of this path object. @raise OSError: If an error occurs while listing the directory. If the error is 'serious', meaning that the operation failed due to an access violation, exhaustion of some kind of resource (file descriptors or memory), OSError or a platform-specific variant will be raised. @raise UnlistableError: If the inability to list the directory is due to this path not existing or not being a directory, the more specific OSError subclass L{UnlistableError} is raised instead. @return: an iterable of all currently-existing children of this object accessible with L{_PathHelper.child}. """ try: subnames = self.listdir() except WindowsError, winErrObj: # WindowsError is an OSError subclass, so if not for this clause # the OSError clause below would be handling these. Windows error # codes aren't the same as POSIX error codes, so we need to handle # them differently. # Under Python 2.5 on Windows, WindowsError has a winerror # attribute and an errno attribute. The winerror attribute is # bound to the Windows error code while the errno attribute is # bound to a translation of that code to a perhaps equivalent POSIX # error number. # Under Python 2.4 on Windows, WindowsError only has an errno # attribute. It is bound to the Windows error code. # For simplicity of code and to keep the number of paths through # this suite minimal, we grab the Windows error code under either # version. # Furthermore, attempting to use os.listdir on a non-existent path # in Python 2.4 will result in a Windows error code of # ERROR_PATH_NOT_FOUND. However, in Python 2.5, # ERROR_FILE_NOT_FOUND results instead. -exarkun winerror = getattr(winErrObj, 'winerror', winErrObj.errno) if winerror not in (ERROR_PATH_NOT_FOUND, ERROR_FILE_NOT_FOUND, ERROR_INVALID_NAME, ERROR_DIRECTORY): raise raise _WindowsUnlistableError(winErrObj) except __HOLE__, ose: if ose.errno not in (errno.ENOENT, errno.ENOTDIR): # Other possible errors here, according to linux manpages: # EACCES, EMIFLE, ENFILE, ENOMEM. None of these seem like the # sort of thing which should be handled normally. -glyph raise raise UnlistableError(ose) return map(self.child, subnames)
OSError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/filepath.py/_PathHelper.children
1,246
def restat(self, reraise=True): """ Re-calculate cached effects of 'stat'. To refresh information on this path after you know the filesystem may have changed, call this method. @param reraise: a boolean. If true, re-raise exceptions from L{os.stat}; otherwise, mark this path as not existing, and remove any cached stat information. """ try: self.statinfo = stat(self.path) except __HOLE__: self.statinfo = 0 if reraise: raise
OSError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/filepath.py/FilePath.restat
1,247
def touch(self): try: self.open('a').close() except __HOLE__: pass utime(self.path, None)
IOError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/filepath.py/FilePath.touch
1,248
def moveTo(self, destination, followLinks=True): """ Move self to destination - basically renaming self to whatever destination is named. If destination is an already-existing directory, moves all children to destination if destination is empty. If destination is a non-empty directory, or destination is a file, an OSError will be raised. If moving between filesystems, self needs to be copied, and everything that applies to copyTo applies to moveTo. @param destination: the destination (a FilePath) to which self should be copied @param followLinks: whether symlinks in self should be treated as links or as their targets (only applicable when moving between filesystems) """ try: os.rename(self.path, destination.path) except __HOLE__, ose: if ose.errno == errno.EXDEV: # man 2 rename, ubuntu linux 5.10 "breezy": # oldpath and newpath are not on the same mounted filesystem. # (Linux permits a filesystem to be mounted at multiple # points, but rename(2) does not work across different mount # points, even if the same filesystem is mounted on both.) # that means it's time to copy trees of directories! secsib = destination.temporarySibling() self.copyTo(secsib, followLinks) # slow secsib.moveTo(destination, followLinks) # visible # done creating new stuff. let's clean me up. mysecsib = self.temporarySibling() self.moveTo(mysecsib, followLinks) # visible mysecsib.remove() # slow else: raise else: self.changed() destination.changed()
OSError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/python/filepath.py/FilePath.moveTo
1,249
def remove(self): logger.debug('Removing pth entries from %s:', self.file) with open(self.file, 'rb') as fh: # windows uses '\r\n' with py3k, but uses '\n' with py2.x lines = fh.readlines() self._saved_lines = lines if any(b'\r\n' in line for line in lines): endline = '\r\n' else: endline = '\n' for entry in self.entries: try: logger.debug('Removing entry: %s', entry) lines.remove((entry + endline).encode("utf-8")) except __HOLE__: pass with open(self.file, 'wb') as fh: fh.writelines(lines)
ValueError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/req/req_uninstall.py/UninstallPthEntries.remove
1,250
def _log_func_exception(self, data, stat, event=None): try: # For backwards compatibility, don't send event to the # callback unless the send_event is set in constructor if not self._ever_called: self._ever_called = True try: result = self._func(data, stat, event) except __HOLE__: result = self._func(data, stat) if result is False: self._stopped = True self._client.remove_listener(self._session_watcher) except Exception as exc: log.exception(exc) raise
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/kazoo-2.0/kazoo/recipe/watchers.py/DataWatch._log_func_exception
1,251
def __init__(self, *args, **kwargs): try: self.retry_after = int(kwargs.pop('retry_after')) except (__HOLE__, ValueError): self.retry_after = 0 super(RequestEntityTooLarge, self).__init__(*args, **kwargs)
KeyError
dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/exceptions.py/RequestEntityTooLarge.__init__
1,252
def from_response(response, method, url): """Returns an instance of :class:`HttpError` or subclass based on response. :param response: instance of `requests.Response` class :param method: HTTP method used for request :param url: URL used for request """ req_id = response.headers.get("x-openstack-request-id") # NOTE(hdd) true for older versions of nova and cinder if not req_id: req_id = response.headers.get("x-compute-request-id") kwargs = { "http_status": response.status_code, "response": response, "method": method, "url": url, "request_id": req_id, } if "retry-after" in response.headers: kwargs["retry_after"] = response.headers["retry-after"] content_type = response.headers.get("Content-Type", "") if content_type.startswith("application/json"): try: body = response.json() except ValueError: pass else: if isinstance(body, dict) and isinstance(body.get("error"), dict): error = body["error"] kwargs["message"] = error.get("message") kwargs["details"] = error.get("details") elif content_type.startswith("text/"): kwargs["details"] = response.text try: cls = _code_map[response.status_code] except __HOLE__: if 500 <= response.status_code < 600: cls = HttpServerError elif 400 <= response.status_code < 500: cls = HTTPClientError else: cls = HttpError return cls(**kwargs)
KeyError
dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/exceptions.py/from_response
1,253
def _to_key_pair(self, data): try: pubkey = data['ssh_pub_key'] except __HOLE__: pubkey = None return KeyPair(data['name'], public_key=pubkey, fingerprint=None, driver=self, private_key=None, extra={'id': data['id']})
KeyError
dataset/ETHPy150Open apache/libcloud/libcloud/compute/drivers/digitalocean.py/DigitalOcean_v1_NodeDriver._to_key_pair
1,254
def _mkdir_p(path): """Creates all non-existing directories encountered in the passed in path Args: path (str): Path containing directories to create Raises: OSError: If some underlying error occurs when calling :func:`os.makedirs`, that is not errno.EEXIST. """ try: os.makedirs(path) except __HOLE__ as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
OSError
dataset/ETHPy150Open jmagnusson/Flask-Resize/flask_resize/__init__.py/_mkdir_p
1,255
def strformat(self): try: # Try to get a relative path path = os.path.relpath(self.filename) except __HOLE__: # Fallback to absolute path if error occured in getting the # relative path. # This may happen on windows if the drive is different path = os.path.abspath(self.filename) return 'File "%s", line %d' % (path, self.line)
ValueError
dataset/ETHPy150Open numba/numba/numba/ir.py/Loc.strformat
1,256
def get(self, name): try: return self._con[name] except __HOLE__: raise NotDefinedError(name)
KeyError
dataset/ETHPy150Open numba/numba/numba/ir.py/VarMap.get
1,257
def clear(self): try: shutil.rmtree(self.root) except __HOLE__, e: pass
OSError
dataset/ETHPy150Open douban/dpark/dpark/cache.py/DiskCache.clear
1,258
def __init__(self, motor_config): """Initialize a set of DMCCs and their associated motors :param motor_config: Config entry mapping motor names to DMCC ids and motor indices Dictionary entries are in the format: <motor_name>: { board_num: [0-3], motor_num: [1-2] } """ self.config = lib.get_config("bot/config.yaml") self.logger = lib.get_logger() self.is_testing = self.config["test_mode"]["DMCC"] # print "Testing: ", self.config["testing"] # print pyDMCC.lib._config # This instantiates all DMCCs in every DMCCManager, which is probably # not optimal, which works fine for our purposes. Potentially better # approaches: # - global state: shared dmccs dictionary, instantiated once # - selected instantiation: only initialize the dmccs we are control if not self.is_testing: dmccs = pyDMCC.autodetect() self.logger.debug("Found %d physical DMCC boards" % len(dmccs)) else: self.logger.debug("Skipping autodetect due to test mode") dmccs = defaultdict( lambda: pyDMCC.DMCC( 0, verify=False, bus=None, logger=self.logger)) self.logger.debug("DMCC Motor conf: {}".format(dmccs)) self.motors = {} for name, conf in motor_config.items(): if 'invert' in conf.keys(): invert = conf['invert'] else: invert = False try: self.motors[name] = DMCCMotor( dmccs[conf['board_num']], conf['motor_num'], invert) except __HOLE__: self.logger.error( "Bad motor definition for motor: '{}'".format( name)) raise self.logger.debug("Setup {}".format(self))
KeyError
dataset/ETHPy150Open IEEERobotics/bot/bot/hardware/dmcc_motor.py/DMCCMotorSet.__init__
1,259
def test_3_ensure_va_kwa(self): a = A() try: assert a.hello(1,2,3,4,5,*('extra va1','extra va2')) == 0, 'should throw TypeError' except __HOLE__: pass a.hello = introspect.ensure_va_kwa(a.hello) expected = self.expect_hello_info.copy() expected['varargs'] = True expected['varkw'] = True returned = introspect.callable_info(a.hello) assert returned == expected, '%s\n!=\n%s' % (returned, expected) assert a.hello(1,2,3,4,5, *('va1','va2'), **{'kw1':1, 'kw2':2}) == { 'self': a, 'one': 1, 'two': 14, 'three': 3, 'four': 4, 'five': 5, 'foo':'oof', 'bar':'rab', 'baz':'f' } assert a.hello('ett', 'tva') == { 'self': a, 'one': 'ett', 'two': 14, 'three': None, 'four': 123, 'five': 'internets', 'foo':'oof', 'bar':'rab', 'baz':'f' } # This should not raise an exception a.none = introspect.ensure_va_kwa(a.none) a.none() a.none(1,2) a.none(1,2,3,4) a.none(1,2,3,4,foo=12)
TypeError
dataset/ETHPy150Open rsms/smisk/lib/smisk/test/util/introspect.py/IntrospectTests.test_3_ensure_va_kwa
1,260
@task(ignore_results=True) def process_feed(feed_url, owner_id=None, create=False, category_title=None): """ Stores a feed, its related data, its entries and their related data. If create=True then it creates the feed, otherwise it only stores new entries and their related data. """ print("[process_feed] URL={}".format(feed_url)) def normalize_tag(tag): """ converts things like "-noise-" to "noise" and "- noise -" to "noise" """ if tag.startswith("-"): tag = tag[1:] if tag.endswith("-"): tag = tag[:-1] # fix for HTML entities tag = BeautifulSoup(tag).prettify(formatter="html") tag = tag.strip().lower() return tag try: USER_AGENT = settings.PLANET["USER_AGENT"] except (KeyError, AttributeError): print( """Please set PLANET = {" USER_AGENT": <string>} in your settings.py""") exit(0) feed_url = str(feed_url).strip() try: planet_feed = Feed.objects.get(url=feed_url) except Feed.DoesNotExist: planet_feed = None print("*" * 20) print("Feed: {}".format(feed_url)) if create and planet_feed: # can't create it due to it already exists print("This feed already exists!") exit(0) if not create and not planet_feed: # can't update it due to it does not exist print("This feed does not exist!") exit(0) # retrieve and parse feed using conditional GET method if not create: modified = datetime.timetuple(planet_feed.last_modified) etag = planet_feed.etag # update last checked datetime planet_feed.last_checked = datetime.now() planet_feed.save() else: modified = etag = None document = feedparser.parse(feed_url, agent=USER_AGENT, modified=modified, etag=etag) current_site = Site.objects.get(pk=settings.SITE_ID) if create: # then create blog, feed, generator, feed links and feed tags title = document.feed.get("title", "--") subtitle = document.feed.get("subtitle") blog_url = document.feed.get("link") rights = document.feed.get("rights") or document.feed.get("license") info = document.feed.get("info") try: guid = unicode(md5(document.feed.get("link")).hexdigest()) except NameError: guid = md5(document.feed.get("link").encode('utf-8')).hexdigest() image_url = document.feed.get("image", {}).get("href") icon_url = document.feed.get("icon") language = document.feed.get("language") etag = document.get("etag", '') updated_parsed = document.get("updated_parsed") if updated_parsed: last_modified = datetime.fromtimestamp(time.mktime(updated_parsed)) else: last_modified = datetime.now() feed_links = document.feed.get("links", []) if not blog_url: link = [item for item in feed_links if item["rel"] == "alternate"] if link: blog_url = link[0]["href"] User = get_user_model() try: owner = User.objects.get(pk=owner_id) except User.DoesNotExist: owner = None blog, created = Blog.objects.get_or_create( url=blog_url, defaults={"title": title}, owner=owner) generator_dict = document.feed.get("generator_detail", {}) if generator_dict: generator, created = Generator.objects.get_or_create( name=generator_dict.get("name", "--"), link=generator_dict.get("link"), version=generator_dict.get("version")) else: generator = None if category_title: # TODO: site_objects! category = Category.objects.get(title=category_title) else: category = None planet_feed = Feed(title=title, subtitle=subtitle, blog=blog, url=feed_url, rights=rights, info=info, guid=guid, image_url=image_url, icon_url=icon_url, language=language, etag=etag, last_modified=last_modified, generator=generator, is_active=True, last_checked=datetime.now(), site=current_site, category=category ) planet_feed.save() for tag_dict in document.feed.get("tags", []): name = tag_dict.get("term") for link_dict in feed_links: feed_link, created = FeedLink.objects.get_or_create( feed=planet_feed, rel=link_dict.get("rel", "--"), mime_type=link_dict.get("type", "text/html"), link=link_dict.get("href", blog_url) ) entries = [] total_results = int( document.feed.get("opensearch_totalresults", len(document.entries))) items_per_page = int(document.feed.get("opensearch_itemsperpage", 25)) new_posts_count = 0 if total_results == 0: print("No entries to store. status: {} {}".format( document.get("status"), document.get("debug_message"))) else: print("Entries total count: {}".format(total_results)) stop_retrieving = False while (total_results > len(entries)) and not stop_retrieving: # retrieve and store feed posts entries.extend(document.entries) print("Processing {} entries".format(len(document.entries))) for entry in document.entries: title = entry.get("title", "") url = entry.get("link") try: guid = unicode(md5(entry.get("link")).hexdigest()) except NameError: guid = md5(entry.get("link").encode('utf-8')).hexdigest() content = entry.get('description') or entry.get( "content", [{"value": ""}])[0]["value"] comments_url = entry.get("comments") date_modified = entry.get("updated_parsed") or\ entry.get("published_parsed") try: date_modified = datetime.fromtimestamp( time.mktime(date_modified)) except Exception: date_modified = planet_feed.last_modified or datetime.now() try: if len(Post.objects.filter(url=url, guid=guid)): raise PostAlreadyExists post = Post(title=title, url=url, guid=guid, content=content, comments_url=comments_url, date_modified=date_modified, feed=planet_feed) # To have the feed entry in the pre_save signal post.entry = entry post.save() except PostAlreadyExists: print("Skipping post {} ({}) because already exists" .format(guid, url)) if not create: # if it is in update-mode then stop retrieving when # it finds repeated posts stop_retrieving = True else: new_posts_count += 1 # create post tags... for tag_dict in entry.get("tags", []): tag_name = tag_dict.get( "term") or tag_dict.get("label") tag_name = normalize_tag(tag_name) if len(tag_name) > 50: continue try: if "/" in tag_name: # For path based categories for subtag in tag_name.split("/"): if subtag: # empty string if starts/ends with # slash Tag.objects.add_tag( post, '"%s"' % subtag) else: Tag.objects.add_tag(post, '"%s"' % tag_name) except __HOLE__ as e: print("Ignoring tag error: {}".format(e)) # create post links... for link_dict in entry.get("links", []): post_link, created = PostLink.objects.get_or_create( post=post, rel=link_dict.get("rel", "--"), mime_type=link_dict.get("type", "text/html"), link=link_dict.get("href", "--"), title=link_dict.get("title", "--") ) # create and store enclosures... if entry.get('media_thumbnail', False): try: media_url = entry.get('media_thumbnail').href media_list = [{"url": media_url}] except AttributeError: media_list = entry.get( 'media_thumbnail', [{"url": None}]) for media in media_list: media_url = media["url"] mime_type, enc = mimetypes.guess_type( urlparse(media_url).path) post_enclosure, created = Enclosure.objects.get_or_create( post=post, length=0, mime_type=mime_type, link=media_url ) for enclosure_dict in entry.get("enclosures", []): post_enclosure = Enclosure( post=post, length=enclosure_dict.get("length", 0), mime_type=enclosure_dict.get("type", ""), link=enclosure_dict.get("href") ) post_enclosure.save() # create and store author... author_dict = entry.get("author_detail") if author_dict: author, created = Author.objects.get_or_create( name=author_dict.get("name", ""), email=author_dict.get("email", ""), profile_url=author_dict.get("href") ) try: PostAuthorData.objects.get( author=author, post=post) except PostAuthorData.DoesNotExist: pad = PostAuthorData(author=author, post=post) pad.save() # create and store contributors... for contributor_dict in entry.get("contributors", []): contributor, created = Author.objects.get_or_create( name=author_dict.get("name", ""), email=author_dict.get("email", ""), profile_url=contributor_dict.get("href") ) try: PostAuthorData.objects.get( author=contributor, post=post) except PostAuthorData.DoesNotExist: pad = PostAuthorData(author=contributor, post=post, is_contributor=True) pad.save() # We send a post_created signal print('post_created.send(sender=post)', post) post_created.send(sender=post, instance=post) if not stop_retrieving: opensearch_url = "{}?start-index={}&max-results={}".format( feed_url, len(entries) + 1, items_per_page) print("retrieving {}...".format(opensearch_url)) document = feedparser.parse(opensearch_url, agent=USER_AGENT) if new_posts_count: # update last modified datetime planet_feed.last_modified = datetime.now() planet_feed.save() print("{} posts were created. Done.".format(new_posts_count)) return new_posts_count
AttributeError
dataset/ETHPy150Open matagus/django-planet/planet/tasks.py/process_feed
1,261
def finished(experiment_name, reset=True): """ Track a conversion. :param experiment_name: Name of the experiment. :param reset: If set to `True` current user's session is reset so that they may start the test again in the future. If set to `False` the user will always see the alternative they started with. Defaults to `True`. """ if _exclude_visitor(): return redis = _get_redis_connection() try: experiment = Experiment.find(redis, experiment_name) if not experiment: return alternative_name = _get_session().get(experiment.key) if alternative_name: split_finished = set(session.get('split_finished', [])) if experiment.key not in split_finished: alternative = Alternative( redis, alternative_name, experiment_name) alternative.increment_completion() if reset: _get_session().pop(experiment.key, None) try: split_finished.remove(experiment.key) except __HOLE__: pass else: split_finished.add(experiment.key) session['split_finished'] = list(split_finished) except ConnectionError: if not current_app.config['SPLIT_DB_FAILOVER']: raise
KeyError
dataset/ETHPy150Open jpvanhal/flask-split/flask_split/core.py/finished
1,262
def check_all(self, modname): names = {} try: exec "import %s" % modname in names except __HOLE__: # Silent fail here seems the best route since some modules # may not be available in all environments. return verify(hasattr(sys.modules[modname], "__all__"), "%s has no __all__ attribute" % modname) names = {} exec "from %s import *" % modname in names if names.has_key("__builtins__"): del names["__builtins__"] keys = set(names) all = set(sys.modules[modname].__all__) verify(keys==all, "%s != %s" % (keys, all))
ImportError
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test___all__.py/AllTest.check_all
1,263
def test_all(self): if not sys.platform.startswith('java'): # In case _socket fails to build, make this test fail more gracefully # than an AttributeError somewhere deep in CGIHTTPServer. import _socket self.check_all("BaseHTTPServer") self.check_all("Bastion") self.check_all("CGIHTTPServer") self.check_all("ConfigParser") self.check_all("Cookie") self.check_all("MimeWriter") self.check_all("Queue") self.check_all("SimpleHTTPServer") self.check_all("SocketServer") self.check_all("StringIO") self.check_all("UserString") self.check_all("aifc") self.check_all("atexit") self.check_all("audiodev") self.check_all("base64") self.check_all("bdb") self.check_all("binhex") self.check_all("calendar") self.check_all("cgi") self.check_all("cmd") self.check_all("code") self.check_all("codecs") self.check_all("codeop") self.check_all("colorsys") self.check_all("commands") self.check_all("compileall") self.check_all("copy") self.check_all("copy_reg") self.check_all("csv") self.check_all("dbhash") self.check_all("decimal") self.check_all("difflib") self.check_all("dircache") self.check_all("dis") self.check_all("doctest") self.check_all("dummy_thread") self.check_all("dummy_threading") self.check_all("filecmp") self.check_all("fileinput") self.check_all("fnmatch") self.check_all("fpformat") self.check_all("ftplib") self.check_all("getopt") self.check_all("getpass") self.check_all("gettext") self.check_all("glob") self.check_all("gopherlib") self.check_all("gzip") self.check_all("heapq") self.check_all("htmllib") self.check_all("httplib") self.check_all("ihooks") self.check_all("imaplib") self.check_all("imghdr") self.check_all("imputil") self.check_all("keyword") self.check_all("linecache") self.check_all("locale") self.check_all("macpath") self.check_all("macurl2path") self.check_all("mailbox") self.check_all("mailcap") self.check_all("mhlib") self.check_all("mimetools") self.check_all("mimetypes") self.check_all("mimify") self.check_all("multifile") self.check_all("netrc") self.check_all("nntplib") self.check_all("ntpath") self.check_all("opcode") self.check_all("optparse") self.check_all("os") self.check_all("os2emxpath") self.check_all("pdb") self.check_all("pickle") self.check_all("pickletools") self.check_all("pipes") self.check_all("popen2") self.check_all("poplib") self.check_all("posixpath") self.check_all("pprint") self.check_all("profile") self.check_all("pstats") self.check_all("pty") self.check_all("py_compile") self.check_all("pyclbr") self.check_all("quopri") self.check_all("random") self.check_all("re") self.check_all("repr") self.check_all("rexec") self.check_all("rfc822") self.check_all("rlcompleter") self.check_all("robotparser") self.check_all("sched") self.check_all("sets") self.check_all("sgmllib") self.check_all("shelve") self.check_all("shlex") self.check_all("shutil") self.check_all("smtpd") self.check_all("smtplib") self.check_all("sndhdr") self.check_all("socket") self.check_all("_strptime") self.check_all("symtable") self.check_all("tabnanny") self.check_all("tarfile") self.check_all("telnetlib") self.check_all("tempfile") self.check_all("textwrap") self.check_all("threading") self.check_all("timeit") self.check_all("toaiff") self.check_all("tokenize") self.check_all("traceback") self.check_all("tty") self.check_all("unittest") self.check_all("urllib") self.check_all("urlparse") self.check_all("uu") self.check_all("warnings") self.check_all("wave") self.check_all("weakref") self.check_all("webbrowser") self.check_all("xdrlib") self.check_all("zipfile") # rlcompleter needs special consideration; it import readline which # initializes GNU readline which calls setlocale(LC_CTYPE, "")... :-( try: self.check_all("rlcompleter") finally: try: import locale except __HOLE__: pass else: locale.setlocale(locale.LC_CTYPE, 'C')
ImportError
dataset/ETHPy150Open babble/babble/include/jython/Lib/test/test___all__.py/AllTest.test_all
1,264
def set_password(self, value): if value: try: self._password = FERNET.encrypt(bytes(value, 'utf-8')).decode() self.is_encrypted = True except __HOLE__: self._password = value self.is_encrypted = False
NameError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/Connection.set_password
1,265
def set_extra(self, value): if value: try: self._extra = FERNET.encrypt(bytes(value, 'utf-8')).decode() self.is_extra_encrypted = True except __HOLE__: self._extra = value self.is_extra_encrypted = False
NameError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/Connection.set_extra
1,266
@provide_session def run( self, verbose=True, ignore_dependencies=False, # Doesn't check for deps, just runs ignore_depends_on_past=False, # Ignore depends_on_past but respect # other deps force=False, # Disregards previous successes mark_success=False, # Don't run the task, act as if it succeeded test_mode=False, # Doesn't record success or failure in the DB job_id=None, pool=None, session=None): """ Runs the task instance. """ task = self.task self.pool = pool or task.pool self.test_mode = test_mode self.force = force self.refresh_from_db() self.clear_xcom_data() self.job_id = job_id iso = datetime.now().isoformat() self.hostname = socket.gethostname() self.operator = task.__class__.__name__ if self.state == State.RUNNING: logging.warning("Another instance is running, skipping.") elif not force and self.state == State.SUCCESS: logging.info( "Task {self} previously succeeded" " on {self.end_date}".format(**locals()) ) Stats.incr('previously_succeeded', 1, 1) elif ( not ignore_dependencies and not self.are_dependencies_met( session=session, ignore_depends_on_past=ignore_depends_on_past, verbose=True)): logging.warning("Dependencies not met yet") elif ( self.state == State.UP_FOR_RETRY and not self.ready_for_retry()): next_run = (self.end_date + task.retry_delay).isoformat() logging.info( "Not ready for retry yet. " + "Next run after {0}".format(next_run) ) elif force or self.state in State.runnable(): HR = "\n" + ("-" * 80) + "\n" # Line break # For reporting purposes, we report based on 1-indexed, # not 0-indexed lists (i.e. Attempt 1 instead of # Attempt 0 for the first attempt). msg = "Starting attempt {attempt} of {total}".format( attempt=self.try_number % (task.retries + 1) + 1, total=task.retries + 1) self.start_date = datetime.now() if not mark_success and self.state != State.QUEUED and ( self.pool or self.task.dag.concurrency_reached): # If a pool is set for this task, marking the task instance # as QUEUED self.state = State.QUEUED msg = "Queuing attempt {attempt} of {total}".format( attempt=self.try_number % (task.retries + 1) + 1, total=task.retries + 1) logging.info(HR + msg + HR) self.queued_dttm = datetime.now() session.merge(self) session.commit() logging.info("Queuing into pool {}".format(self.pool)) return # print status message logging.info(HR + msg + HR) self.try_number += 1 if not test_mode: session.add(Log(State.RUNNING, self)) self.state = State.RUNNING self.end_date = None if not test_mode: session.merge(self) session.commit() # Closing all pooled connections to prevent # "max number of connections reached" settings.engine.dispose() if verbose: if mark_success: msg = "Marking success for " else: msg = "Executing " msg += "{self.task} on {self.execution_date}" context = {} try: logging.info(msg.format(self=self)) if not mark_success: context = self.get_template_context() task_copy = copy.copy(task) self.task = task_copy def signal_handler(signum, frame): '''Setting kill signal handler''' logging.error("Killing subprocess") task_copy.on_kill() raise AirflowException("Task received SIGTERM signal") signal.signal(signal.SIGTERM, signal_handler) self.render_templates() task_copy.pre_execute(context=context) # If a timout is specified for the task, make it fail # if it goes beyond result = None if task_copy.execution_timeout: with timeout(int( task_copy.execution_timeout.total_seconds())): result = task_copy.execute(context=context) else: result = task_copy.execute(context=context) # If the task returns a result, push an XCom containing it if result is not None: self.xcom_push(key=XCOM_RETURN_KEY, value=result) task_copy.post_execute(context=context) self.state = State.SUCCESS except AirflowSkipException: self.state = State.SKIPPED except (Exception, __HOLE__) as e: self.handle_failure(e, test_mode, context) raise # Recording SUCCESS self.end_date = datetime.now() self.set_duration() if not test_mode: session.add(Log(self.state, self)) session.merge(self) session.commit() # Success callback try: if task.on_success_callback: task.on_success_callback(context) except Exception as e3: logging.error("Failed when executing success callback") logging.exception(e3) session.commit()
KeyboardInterrupt
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/TaskInstance.run
1,267
def __hash__(self): hash_components = [type(self)] for c in self._comps: val = getattr(self, c, None) try: hash(val) hash_components.append(val) except __HOLE__: hash_components.append(repr(val)) return hash(tuple(hash_components)) # Composing Operators -----------------------------------------------
TypeError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/BaseOperator.__hash__
1,268
def _set_relatives(self, task_or_task_list, upstream=False): try: task_list = list(task_or_task_list) except __HOLE__: task_list = [task_or_task_list] for t in task_list: if not isinstance(t, BaseOperator): raise AirflowException( "Relationships can only be set between " "Operators; received {}".format(t.__class__.__name__)) # relationships can only be set if the tasks share a single DAG. Tasks # without a DAG are assigned to that DAG. dags = set(t.dag for t in [self] + task_list if t.has_dag()) if len(dags) > 1: raise AirflowException( 'Tried to set relationships between tasks in ' 'more than one DAG: {}'.format(dags)) elif len(dags) == 1: dag = list(dags)[0] else: raise AirflowException( "Tried to create relationships between tasks that don't have " "DAGs yet. Set the DAG for at least one " "task and try again: {}".format([self] + task_list)) if dag and not self.has_dag(): self.dag = dag for task in task_list: if dag and not task.has_dag(): task.dag = dag if upstream: task.append_only_new(task._downstream_task_ids, self.task_id) self.append_only_new(self._upstream_task_ids, task.task_id) else: self.append_only_new(self._downstream_task_ids, task.task_id) task.append_only_new(task._upstream_task_ids, self.task_id) self.detect_downstream_cycle()
TypeError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/BaseOperator._set_relatives
1,269
def __hash__(self): hash_components = [type(self)] for c in self._comps: val = getattr(self, c, None) try: hash(val) hash_components.append(val) except __HOLE__: hash_components.append(repr(val)) return hash(tuple(hash_components)) # Context Manager -----------------------------------------------
TypeError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/DAG.__hash__
1,270
def set_val(self, value): if value: try: self._val = FERNET.encrypt(bytes(value, 'utf-8')).decode() self.is_encrypted = True except __HOLE__: self._val = value self.is_encrypted = False
NameError
dataset/ETHPy150Open airbnb/airflow/airflow/models.py/Variable.set_val
1,271
def disconnect(self, token): ''' Unregisters a callback for an event topic. @param token: Token of the callback to unregister @type token: dict ''' topic = token['topic'] try: arr = self._connects[topic] except __HOLE__: return arr.remove(token['cb']) if len(arr) == 0: del self._connects[topic]
KeyError
dataset/ETHPy150Open parente/pyttsx/pyttsx/engine.py/Engine.disconnect
1,272
def read_file(filename): """Read a file into a string""" path = os.path.abspath(os.path.dirname(__file__)) filepath = os.path.join(path, filename) try: return open(filepath).read() except __HOLE__: return ''
IOError
dataset/ETHPy150Open mlavin/sickmuse/setup.py/read_file
1,273
def Attach(self): """Attach to an existing extstorage device. This method maps the extstorage volume that matches our name with a corresponding block device and then attaches to this device. """ self.attached = False # Call the External Storage's attach script, # to attach an existing Volume to a block device under /dev result = _ExtStorageAction(constants.ES_ACTION_ATTACH, self.unique_id, self.ext_params, name=self.name, uuid=self.uuid) # Attach script returns the block device path and optionally # the URIs to be used for userspace access (one URI for # each hypervisor supported). # If the provider doesn't support userspace access, then # the 'uris' variable will be an empty list. result = result.split("\n") self.dev_path = result[0] self.uris = result[1:] if not self.dev_path: logging.info("A local block device is not available") self.dev_path = None if not self.uris: logging.error("Neither a block device nor a userspace URI is available") return False self.attached = True return True # Verify that dev_path exists and is a block device try: st = os.stat(self.dev_path) except __HOLE__, err: logging.error("Error stat()'ing %s: %s", self.dev_path, str(err)) return False if not stat.S_ISBLK(st.st_mode): logging.error("%s is not a block device", self.dev_path) return False self.major = os.major(st.st_rdev) self.minor = utils.osminor(st.st_rdev) self.attached = True return True
OSError
dataset/ETHPy150Open ganeti/ganeti/lib/storage/extstorage.py/ExtStorageDevice.Attach
1,274
def do_start(self, arg): """Starts an ActorSystem. The first optional argument is the SystemBase. The remainder of the line (if any) is parsed as the capabilities dictionary to pass to the ActorSystem. """ if self.system: print ('Shutting down previous ActorSystem') self.system.shutdown() del self.system self.system = None if arg: base = arg.split()[0] capspec = ' '.join(arg.split()[1:]) caps = eval(capspec) if capspec else {} print ('Starting %s ActorSystem\nCapabilities: %s'%(base, str(caps))) try: self.system = ActorSystem(base, caps) print ('Started %s ActorSystem'%base) except __HOLE__: print ('***ERROR starting ActorSystem with specified Base: %s'%base) import traceback traceback.print_exc() except ActorSystemException as ex: print ('***ERROR from Actor System: %s'%str(ex)) else: self.system = ActorSystem() print ('Started default ActorSystem')
ImportError
dataset/ETHPy150Open godaddy/Thespian/thespian/shell.py/ThespianShell.do_start
1,275
def do_set_thesplog(self, arg): 'Updates the Thespian thesplog internal call functionality. The first argument is the Actor number, the second argument is the logging threshold (e.g. "debug", "warning", etc.), the third argument is true or false to specify the forwarding of thesplog calls to python logging, and the fourth argument is true or false to specify whether to append thesplog output to /tmp/Thespian.log' try: from thespian.system.messages.logcontrol import SetLogging except __HOLE__: print ('** Sorry, log control not available on this system') return actorAddrAndSettings = self.parseActorNum(arg) if actorAddrAndSettings: anum, addr, settings = actorAddrAndSettings print('settings is <%s>'%(str(settings))) threshold,useLogging,useFile = tuple(settings.split(' ')) l1 = {'debug': logging.DEBUG, 'info' : logging.INFO, 'warning': logging.WARNING, 'error' : logging.ERROR, 'critical' : logging.CRITICAL}.get(threshold.lower(), logging.INFO) l2 = useLogging.lower() not in ['0', 'no', 'false'] l3 = useFile.lower() not in ['0', 'no', 'false'] r = (self.system or ActorSystem()).tell(addr, SetLogging(l1, l2, l3)) print('Actor #%d (%s) logging settings updated.'%(anum, addr))
ImportError
dataset/ETHPy150Open godaddy/Thespian/thespian/shell.py/ThespianShell.do_set_thesplog
1,276
@check_event_permissions def create_or_edit_event(request, calendar_slug, event_id=None, next=None, template_name='event/edit.html', form_class = EventForm): date = coerce_date_dict(request.GET) initial_data = None if date: try: start = datetime.datetime(**date) initial_data = { "start": start, "end": start + datetime.timedelta(minutes=30) } except __HOLE__: raise Http404 except ValueError: raise Http404 instance = None if event_id is not None: instance = get_object_or_404(Event, id=event_id) calendar = get_object_or_404(Calendar, slug=calendar_slug) data = request.POST.copy() if data: data["title"] = data["oncall"]+","+data["fallback"] form = form_class(data=data or None, instance=instance, initial=initial_data) users = User.objects.all(); if form.is_valid(): event = form.save(commit=False) if instance is None: event.creator = request.user event.calendar = calendar event.save() return HttpResponseRedirect(reverse('calendar_details', kwargs={'calendar_slug': calendar.slug})) if instance is not None: officers = instance.title.split(",") data["oncall"] = officers[0] data["fallback"] = officers[1] data["start_ymd"] = instance.start.date().isoformat() data["start_hour"] = instance.start.time().strftime("%H:%M") data["end_ymd"] = instance.end.date().isoformat() data["end_hour"] = instance.end.time().strftime("%H:%M") if instance.end_recurring_period: data["recurr_ymd"] = instance.end_recurring_period.date().isoformat() data["description"] = instance.description data["rule"] = instance.rule and instance.rule.id or "" next = get_next_url(request, next) return render_to_response(template_name, { "data": data, "calendar": calendar, "next":next, "users":users, "form": form, }, context_instance=RequestContext(request))
TypeError
dataset/ETHPy150Open ustream/openduty/openduty/events.py/create_or_edit_event
1,277
def run_from_argv(self, argv): """ Changes the option_list to use the options from the wrapped command. Adds schema parameter to specify which schema will be used when executing the wrapped command. """ # load the command object. if len(argv) <= 2: return try: app_name = get_commands()[argv[2]] except __HOLE__: raise CommandError("Unknown command: %r" % argv[2]) if isinstance(app_name, BaseCommand): # if the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, argv[2]) super(Command, self).run_from_argv(argv)
KeyError
dataset/ETHPy150Open tomturner/django-tenants/django_tenants/management/commands/tenant_command.py/Command.run_from_argv
1,278
def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25 } ssn_odd_chars = { '0': 1, '1': 0, '2': 5, '3': 7, '4': 9, '5': 13, '6': 15, '7': 17, '8': 19, '9': 21, 'A': 1, 'B': 0, 'C': 5, 'D': 7, 'E': 9, 'F': 13, 'G': 15, 'H': 17, 'I': 19, 'J': 21, 'K': 2, 'L': 4, 'M': 18, 'N': 20, 'O': 11, 'P': 3, 'Q': 6, 'R': 8, 'S': 12, 'T': 14, 'U': 16, 'V': 10, 'W': 22, 'X': 25, 'Y': 24, 'Z': 23 } # Chars from 'A' to 'Z' ssn_check_digits = [chr(x) for x in range(65, 91)] ssn = value.upper() total = 0 for i in range(0, 15): try: if i % 2 == 0: total += ssn_odd_chars[ssn[i]] else: total += ssn_even_chars[ssn[i]] except __HOLE__: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]} raise ValueError(msg) return ssn_check_digits[total % 26]
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/it/util.py/ssn_check_digit
1,279
def generate(api, setUp=None): """ Generates a set of tests for every Resource""" if setUp is None: def user_setUp(*args, **kwargs): return else: user_setUp = setUp class UnderResources(MultiTestCase): """ Generates a set of tests for every Resource """ @staticmethod def multi_create_test_resource_unicity(self, resource_name, resource): """ verifies that one and only one object of the resource was created when calling create_test_resource """ initial_count = len(resource._meta.object_class.objects.all()) resource.create_test_resource() final_count = len(resource._meta.object_class.objects.all()) self.assertEqual(initial_count + 1, final_count) @staticmethod def multi_create_test_resource(self, resource_name, resource): """ Verifies that the resource's create_test_data method exists and it doesn't raise any exceptions when called without any parameters """ try: resource.create_test_resource() except Exception, err: msg = "Could not create test resource for %s" % resource_name msg = "%s: %s - %s" % (msg, err.__class__.__name__, err.message) self.assertTrue(False, msg) @staticmethod def multi_test_data_register(self, resource_name, resource): """ verify that the resource has a Test Data generating class asssociated to it """ if not hasattr(resource._meta, 'testdata'): msg = "Missing example data for resource: %(res)s \n" msg += "-Did you create a TestData child class for %(res)s?\n" msg += "-Did you register the TestData on your Api? \n" msg += "-Did you correctly set its resouce='%(res)s' property?" msg %= {"res": resource_name} self.assertTrue(False, msg) @staticmethod def multi_testdata_data_existence(self, resource_name, resource): """ If a resource allows POST(or GET), this test verifies that there is test data for such requests """ #Check existence for method in ['POST', 'GET']: try: if not hasattr(resource._meta, 'testdata'): msg = "Missing testdata data for resource: %s \n"\ "Did you forget to define a TestData class for the\ resource?" msg %= (resource_name) self.assertTrue(False, msg) if api.resource_allows_method(resource_name, method): testdata = getattr(resource._meta.testdata, method.lower()) msg = "Example %s data is not a TestData or dict "\ "but %s" msg %= (method, testdata.__class__) is_testdata = issubclass(testdata.__class__, TestData) is_dict = type(testdata) == dict self.assertTrue(is_testdata or is_dict, msg) except (__HOLE__, KeyError), err: message = "Missing testdata %s data for %s resource.: %s" message %= (method, resource_name, err) self.assertTrue(False, message) @staticmethod def multi_test_post(self, resource_name, resource): """ If the resource allows POSTing, this test verifies that such call using the example post data will work """ if resource.can_create(): post_data = prepare_test_post_data(self, resource) post_response = self.client.post( resource.get_resource_list_uri(), post_data) msg = "Failed to POST testdata data for resource %s"\ "S: %s. R(%s): %s" msg %= (resource_name, post_data, post_response.status_code, post_response.content) self.assertEqual(post_response.status_code, 201, msg) @staticmethod def multi_testdata_get_detail(self, resource_name, resource): """ If the resource allows GETing, this test verifies that such call returns something similar to the get example data """ if api.resource_allows_detail(resource_name, 'GET'): uri, res = resource.create_test_resource() get_response = self.client.get(uri, parse='json') self.assertEqual(200, get_response.status_code, "Location: %s\nResponse (%s):\n%s" % ( uri, get_response.status_code, get_response.data, )) response_dict = get_response.data object_keys = set(response_dict.keys()) expected_keys = set(resource._meta.testdata.get.keys()) msg = "GET data does not match the testdata for resource "\ "%s - EXAMPLE: %s vs GET: %s" msg %= (resource_name, expected_keys, object_keys) self.assertEqual(expected_keys, object_keys, msg) @staticmethod def multi_declared_testdata_fields_coherence(self, resource_name, resource): #only if resource allows detail GET if 'GET' not in resource._meta.detail_allowed_methods: return testdata_fields = set(resource._meta.testdata_fields) declared_fields = set(resource.declared_fields.keys()) delta = testdata_fields - declared_fields if len(delta) > 0: msg = "%s.%s field appears on the testdata but it is "\ "not declared." msg %= (resource_name, delta.pop()) self.assertTrue(False, msg) delta = declared_fields - testdata_fields if len(delta) > 0: msg = "%s.%s field is declared but is missing from testdata." msg %= (resource_name, delta.pop()) self.assertTrue(False, msg) @staticmethod def generate_arguments(): args = [] for resource_name, resource in api._registry.items(): if hasattr(resource._meta, "testdata"): args.append((resource_name, resource)) return args @staticmethod def generate_test_name(resource_name, resource): return resource_name @staticmethod def setUp(self, test, resource_name, resource): test_name = test.__name__ func_name = test_name.replace("multi_", "setup_") self.client = Client() if hasattr(resource._meta.testdata, func_name): getattr(resource._meta.testdata, func_name)(self) user_setUp(self, test_name, resource_name, resource) class TestResources(TestCase): __metaclass__ = create_multi_meta(UnderResources) return TestResources
AttributeError
dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastytools/tastytools/test/definitions/resources.py/generate
1,280
def metadata(id, sleep_time=1): solr ="http://chinkapin.pti.indiana.edu:9994/solr/meta/select/?q=id:%s" % id solr += "&wt=json" ## retrieve JSON results # TODO: exception handling if sleep_time: sleep(sleep_time) ## JUST TO MAKE SURE WE ARE THROTTLED try: data = json.load(urlopen(solr)) print id return data['response']['docs'][0] except (__HOLE__,IndexError, HTTPError): print "No result found for " + id return dict()
ValueError
dataset/ETHPy150Open inpho/topic-explorer/topicexplorer/lib/hathitrust.py/metadata
1,281
@override_settings(TEST_ARTICLE_MODEL='swappable_models.article') def test_case_insensitive(self): "Model names are case insensitive. Check that model swapping honors this." try: Article.objects.all() except __HOLE__: self.fail('Swappable model names should be case insensitive.') self.assertIsNone(Article._meta.swapped)
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/swappable_models/tests.py/SwappableModelTests.test_case_insensitive
1,282
def _connect(self, **kwargs): self.status_code = 'Unknown' self.timeout = kwargs.get('timeout', 5.0) self.proxies = kwargs.get('proxies', '') try: r = self.rate_limited_get( self.url, params=self.params, headers=self.headers, timeout=self.timeout, proxies=self.proxies ) self.status_code = r.status_code self.url = r.url if r.content: self.status_code = 200 except (KeyboardInterrupt, __HOLE__): raise except requests.exceptions.SSLError: self.status_code = 495 self.error = 'ERROR - SSLError' except: self.status_code = 404 self.error = 'ERROR - URL Connection' # Open JSON content from Request connection if self.status_code == 200: try: self.content = r.json() except: self.status_code = 400 self.error = 'ERROR - JSON Corrupted' self.content = r.content
SystemExit
dataset/ETHPy150Open DenisCarriere/geocoder/geocoder/base.py/Base._connect
1,283
def getfeature(self, typename=None, filter=None, bbox=None, featureid=None, featureversion=None, propertyname='*', maxfeatures=None, srsname=None, outputFormat=None, method='Get', startindex=None): """Request and return feature data as a file-like object. Parameters ---------- typename : list List of typenames (string) filter : string XML-encoded OGC filter expression. bbox : tuple (left, bottom, right, top) in the feature type's coordinates. featureid : list List of unique feature ids (string) featureversion : string Default is most recent feature version. propertyname : list List of feature property names. '*' matches all. maxfeatures : int Maximum number of features to be returned. method : string Qualified name of the HTTP DCP method to use. srsname: string EPSG code to request the data in outputFormat: string (optional) Requested response format of the request. startindex: int (optional) Start position to return feature set (paging in combination with maxfeatures) There are 3 different modes of use 1) typename and bbox (simple spatial query). It is assumed, that bbox coordinates are given *always* in the east,north order 2) typename and filter (more expressive) 3) featureid (direct access to known features) """ try: base_url = next((m.get('url') for m in self.getOperationByName('GetFeature').methods if m.get('type').lower() == method.lower())) except __HOLE__: base_url = self.url request = {'service': 'WFS', 'version': self.version, 'request': 'GetFeature'} if not isinstance(typename, list): typename = [typename] if srsname is not None: # check, if desired SRS is supported by the service for this typename if typename is not None: # convert srsname string to Crs object found in GetCaps srsnameobj = self.getSRS(srsname, typename[0]) if srsnameobj is not None: request['srsname'] = srsnameobj.id else: options = ", ".join(map(lambda x: x.id, self.contents[typename[0]].crsOptions)) raise ServiceException("SRSNAME %s not supported. Options: %s" % (srsname, options)) else: request['srsname'] = str(srsname) # check featureid if featureid: request['featureid'] = ','.join(featureid) # bbox elif bbox and typename: request["bbox"] = self.getBBOXKVP(bbox, typename) # or filter elif filter and typename: request['filter'] = str(filter) assert len(typename) > 0 request['typename'] = ','.join(typename) if propertyname is not None: if not isinstance(propertyname, list): propertyname = [propertyname] request['propertyname'] = ','.join(propertyname) if featureversion is not None: request['featureversion'] = str(featureversion) if maxfeatures is not None: request['maxfeatures'] = str(maxfeatures) if startindex is not None: request['startindex'] = str(startindex) if outputFormat is not None: request["outputFormat"] = outputFormat data = urlencode(request) log.debug("Making request: %s?%s" % (base_url, data)) u = openURL(base_url, data, method, timeout=self.timeout) # check for service exceptions, rewrap, and return # We're going to assume that anything with a content-length > 32k # is data. We'll check anything smaller. if 'Content-Length' in u.info(): length = int(u.info()['Content-Length']) have_read = False else: data = u.read() have_read = True length = len(data) if length < 32000: if not have_read: data = u.read() try: tree = etree.fromstring(data) except BaseException: # Not XML return self._makeStringIO(data) else: if tree.tag == "{%s}ServiceExceptionReport" % namespaces["ogc"]: se = tree.find(nspath_eval('ServiceException', namespaces["ogc"])) raise ServiceException(str(se.text).strip()) else: return self._makeStringIO(data) else: if have_read: return self._makeStringIO(data) return u
StopIteration
dataset/ETHPy150Open geopython/OWSLib/owslib/feature/wfs110.py/WebFeatureService_1_1_0.getfeature
1,284
def add_from_path(envname, dirs): try: dirs.extend(os.environ[envname].split(os.pathsep)) except __HOLE__: pass
KeyError
dataset/ETHPy150Open PyTables/PyTables/setup.py/add_from_path
1,285
def find_runtime_path(self, locations=default_runtime_dirs): """ returns True if the runtime can be found returns None otherwise """ # An explicit path can not be provided for runtime libraries. # (The argument is accepted for compatibility with previous methods.) # dlopen() won't tell us where the file is, just whether # success occurred, so this returns True instead of a filename for prefix in self._runtime_prefixes: for suffix in self._runtime_suffixes: try: ctypes.CDLL(prefix + self.runtime_name + suffix) return True except __HOLE__: pass
OSError
dataset/ETHPy150Open PyTables/PyTables/setup.py/Package.find_runtime_path
1,286
@staticmethod def _get_mtimes(filenames): filename_to_mtime = {} for filename in filenames: try: filename_to_mtime[filename] = os.path.getmtime(filename) except __HOLE__ as e: # Ignore deleted includes. if e.errno != errno.ENOENT: raise return filename_to_mtime
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/application_configuration.py/ServerConfiguration._get_mtimes
1,287
def get_list(self): try: return self.__list except __HOLE__: self.__list = self.split('\n') return self.__list
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/LSString.get_list
1,288
def get_spstr(self): try: return self.__spstr except __HOLE__: self.__spstr = self.replace('\n',' ') return self.__spstr
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/LSString.get_spstr
1,289
def get_paths(self): try: return self.__paths except __HOLE__: self.__paths = [path(p) for p in self.split('\n') if os.path.exists(p)] return self.__paths
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/LSString.get_paths
1,290
def get_spstr(self): try: return self.__spstr except __HOLE__: self.__spstr = ' '.join(self) return self.__spstr
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.get_spstr
1,291
def get_nlstr(self): try: return self.__nlstr except __HOLE__: self.__nlstr = '\n'.join(self) return self.__nlstr
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.get_nlstr
1,292
def get_paths(self): try: return self.__paths except __HOLE__: self.__paths = [path(p) for p in self if os.path.exists(p)] return self.__paths
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.get_paths
1,293
def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( lambda x: x.startswith('C') ) a.grep('Cha.*log', prune=1) a.grep('chm', field=-1) """ def match_target(s): if field is None: return s parts = s.split() try: tgt = parts[field] return tgt except __HOLE__: return "" if isinstance(pattern, str): pred = lambda x : re.search(pattern, x, re.IGNORECASE) else: pred = pattern if not prune: return SList([el for el in self if pred(match_target(el))]) else: return SList([el for el in self if not pred(match_target(el))])
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.grep
1,294
def fields(self, *fields): """ Collect whitespace-separated fields from string list Allows quick awk-like usage of string lists. Example data (in var a, created by 'a = !ls -l'):: -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython a.fields(0) is ['-rwxrwxrwx', 'drwxrwxrwx+'] a.fields(1,0) is ['1 -rwxrwxrwx', '6 drwxrwxrwx+'] (note the joining by space). a.fields(-1) is ['ChangeLog', 'IPython'] IndexErrors are ignored. Without args, fields() just split()'s the strings. """ if len(fields) == 0: return [el.split() for el in self] res = SList() for el in [f.split() for f in self]: lineparts = [] for fd in fields: try: lineparts.append(el[fd]) except __HOLE__: pass if lineparts: res.append(" ".join(lineparts)) return res
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.fields
1,295
def sort(self,field= None, nums = False): """ sort by specified fields (see fields()) Example:: a.sort(1, nums = True) Sorts a by second field, in numerical order (so that 21 > 3) """ #decorate, sort, undecorate if field is not None: dsu = [[SList([line]).fields(field), line] for line in self] else: dsu = [[line, line] for line in self] if nums: for i in range(len(dsu)): numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) try: n = int(numstr) except __HOLE__: n = 0; dsu[i][0] = n dsu.sort() return SList([t[1] for t in dsu]) # FIXME: We need to reimplement type specific displayhook and then add this # back as a custom printer. This should also be moved outside utils into the # core. # def print_slist(arg): # """ Prettier (non-repr-like) and more informative printer for SList """ # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" # if hasattr(arg, 'hideonce') and arg.hideonce: # arg.hideonce = False # return # # nlprint(arg) # # print_slist = result_display.when_type(SList)(print_slist)
ValueError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/utils/text.py/SList.sort
1,296
def override_subcommand(section_name, section_items, args): """ Given a specific section in the configuration file that maps to a subcommand (except for the global section) read all the keys that are actual argument flags and slap the values for that one subcommand. Return the altered ``args`` object at the end. """ # XXX We are not coercing here any int-like values, so if ArgParse # does that in the CLI we are totally non-compliant with that expectation # but we will try and infer a few boolean values # acceptable boolean states for flags _boolean_states = {'yes': True, 'true': True, 'on': True, 'no': False, 'false': False, 'off': False} for k, v, in section_items: # get the lower case value of `v`, fallback to the booleanized # (original) value of `v` try: normalized_value = v.lower() except __HOLE__: # probably not a string object that has .lower normalized_value = v value = _boolean_states.get(normalized_value, v) setattr(args, k, value) return args
AttributeError
dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/conf/cephdeploy.py/override_subcommand
1,297
def get_year(self): """ Return the year for which this view should display data. """ year = self.year if year is None: try: year = self.kwargs['year'] except __HOLE__: try: year = self.request.GET['year'] except KeyError: raise Http404(_("No year specified")) return year
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/generic/dates.py/YearMixin.get_year
1,298
def get_month(self): """ Return the month for which this view should display data. """ month = self.month if month is None: try: month = self.kwargs['month'] except __HOLE__: try: month = self.request.GET['month'] except KeyError: raise Http404(_("No month specified")) return month
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/generic/dates.py/MonthMixin.get_month
1,299
def get_day(self): """ Return the day for which this view should display data. """ day = self.day if day is None: try: day = self.kwargs['day'] except __HOLE__: try: day = self.request.GET['day'] except KeyError: raise Http404(_("No day specified")) return day
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/generic/dates.py/DayMixin.get_day