Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
9,400
def medianFilter(self, kernel_size=5): """ **SUMMARY** Apply median filter on the data **PARAMETERS** * *kernel_size* - Size of the filter (should be odd int) - int **RETURNS** A LineScan object with the median filter applied to the values. **EXAMPLE** >>> ls = img.getLineScan(x=10) >>> mf = ls.medianFilter() >>> plt.plot(ls) >>> plt.plot(mf) """ try: from scipy.signal import medfilt except __HOLE__: warnings.warn("Scipy vesion >= 0.11 requierd.") return None if kernel_size % 2 == 0: kernel_size-=1 print "Kernel Size should be odd. New kernel size =" , (kernel_size) medfilt_array = medfilt(np.asarray(self[:]), kernel_size) retVal = LineScan(medfilt_array.astype("uint8").tolist(), image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2, x=self.col, y=self.row) retVal._update(self) return retVal
ImportError
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/LineScan.py/LineScan.medianFilter
9,401
def detrend(self): """ **SUMMARY** Detren the data **PARAMETERS** **RETURNS** A LineScan object with detrened data. **EXAMPLE** >>> ls = img.getLineScan(x=10) >>> dt = ls.detrend() >>> plt.plot(ls) >>> plt.plot(dt) """ try: from scipy.signal import detrend as sdetrend except __HOLE__: warnings.warn("Scipy vesion >= 0.11 requierd.") return None detrend_arr = sdetrend(np.asarray(self[:])) retVal = LineScan(detrend_arr.astype("uint8").tolist(), image=self.image,pointLoc=self.pointLoc,pt1=self.pt1,pt2=self.pt2, x=self.col, y=self.row) retVal._update(self) return retVal
ImportError
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/LineScan.py/LineScan.detrend
9,402
def linux_install_data_files(data_files): for item in data_files: path = os.path.join(sys.prefix, item[0]) print "{0}->{1}".format(item[1], path) try: os.makedirs(os.path.split(path)[0]) except __HOLE__, e: pass try: shutil.copy(item[1], path) except Exception, e: print e try: call(['update-desktop-database']) except: print "update-desktop-database: failed" try: call(['gtk-update-icon-cache', os.path.join(sys.prefix, 'share/icons/hicolor')]) except: print "update-desktop-database: failed"
OSError
dataset/ETHPy150Open legalosLOTR/mdb/setup.py/linux_install_data_files
9,403
@request_handler @defer.inlineCallbacks def _async_render_POST(self, request): requester = yield self.auth.get_user_by_req(request) # TODO: The checks here are a bit late. The content will have # already been uploaded to a tmp file at this point content_length = request.getHeader("Content-Length") if content_length is None: raise SynapseError( msg="Request must specify a Content-Length", code=400 ) if int(content_length) > self.max_upload_size: raise SynapseError( msg="Upload request body is too large", code=413, ) upload_name = request.args.get("filename", None) if upload_name: try: upload_name = upload_name[0].decode('UTF-8') except __HOLE__: raise SynapseError( msg="Invalid UTF-8 filename parameter: %r" % (upload_name), code=400, ) headers = request.requestHeaders if headers.hasHeader("Content-Type"): media_type = headers.getRawHeaders("Content-Type")[0] else: raise SynapseError( msg="Upload request missing 'Content-Type'", code=400, ) # if headers.hasHeader("Content-Disposition"): # disposition = headers.getRawHeaders("Content-Disposition")[0] # TODO(markjh): parse content-dispostion content_uri = yield self.create_content( media_type, upload_name, request.content.read(), content_length, requester.user ) respond_with_json( request, 200, {"content_uri": content_uri}, send_cors=True )
UnicodeDecodeError
dataset/ETHPy150Open matrix-org/synapse/synapse/rest/media/v1/upload_resource.py/UploadResource._async_render_POST
9,404
def main(): test = TestPermutation() test.test_permutation(permutations) try: test.test_permutation(permutations_alt) except __HOLE__: # Alternate solutions are only defined # in the solutions file pass
NameError
dataset/ETHPy150Open donnemartin/interactive-coding-challenges/arrays_strings/permutation/test_permutation_solution.py/main
9,405
def __getitem__(self, key): try: value = self.cache[key] except __HOLE__: f = StringIO(self.dict[key]) value = Unpickler(f).load() if self.writeback: self.cache[key] = value return value
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/shelve.py/Shelf.__getitem__
9,406
def __delitem__(self, key): del self.dict[key] try: del self.cache[key] except __HOLE__: pass
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/shelve.py/Shelf.__delitem__
9,407
def close(self): self.sync() try: self.dict.close() except __HOLE__: pass # Catch errors that may happen when close is called from __del__ # because CPython is in interpreter shutdown. try: self.dict = _ClosedDict() except (NameError, TypeError): self.dict = None
AttributeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/shelve.py/Shelf.close
9,408
def tearDown(self): # Undo the test.globs reassignment we made, so that the parent class # teardown doesn't destroy the ipython namespace if isinstance(self._dt_test.examples[0],IPExample): self._dt_test.globs = self._dt_test_globs_ori # Restore the behavior of the '_' key in the user namespace to # normal after each doctest, so that unittests behave normally _ip.user_ns.protect_underscore = False # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but # it does look like one to me: its tearDown method tries to run # # delattr(__builtin__, self._result_var) # # without checking that the attribute really is there; it implicitly # assumes it should have been set via displayhook. But if the # displayhook was never called, this doesn't necessarily happen. I # haven't been able to find a little self-contained example outside of # ipython that would show the problem so I can report it to the nose # team, but it does happen a lot in our code. # # So here, we just protect as narrowly as possible by trapping an # attribute error whose message would be the name of self._result_var, # and letting any other error propagate. try: super(DocTestCase, self).tearDown() except __HOLE__ as exc: if exc.args[0] != self._result_var: raise # A simple subclassing of the original with a different class name, so we can # distinguish and treat differently IPython examples from pure python ones.
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/testing/plugin/ipdoctest.py/DocTestCase.tearDown
9,409
def test_multiple_rules(self): # Test that parse_limits() handles multiple rules correctly. try: l = limits.Limiter.parse_limits('(get, *, .*, 20, minute);' '(PUT, /foo*, /foo.*, 10, hour);' '(POST, /bar*, /bar.*, 5, second);' '(Say, /derp*, /derp.*, 1, day)') except __HOLE__ as e: assert False, six.text_type(e) # Make sure the number of returned limits are correct self.assertEqual(len(l), 4) # Check all the verbs... expected = ['GET', 'PUT', 'POST', 'SAY'] self.assertEqual([t.verb for t in l], expected) # ...the URIs... expected = ['*', '/foo*', '/bar*', '/derp*'] self.assertEqual([t.uri for t in l], expected) # ...the regexes... expected = ['.*', '/foo.*', '/bar.*', '/derp.*'] self.assertEqual([t.regex for t in l], expected) # ...the values... expected = [20, 10, 5, 1] self.assertEqual([t.value for t in l], expected) # ...and the units... expected = [utils.TIME_UNITS['MINUTE'], utils.TIME_UNITS['HOUR'], utils.TIME_UNITS['SECOND'], utils.TIME_UNITS['DAY']] self.assertEqual([t.unit for t in l], expected)
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/api/openstack/compute/test_limits.py/ParseLimitsTest.test_multiple_rules
9,410
@property def freqstr(self): try: code = self.rule_code except __HOLE__: return repr(self) if self.n != 1: fstr = '%d%s' % (self.n, code) else: fstr = code return fstr
NotImplementedError
dataset/ETHPy150Open pydata/pandas/pandas/tseries/offsets.py/DateOffset.freqstr
9,411
@property def freqstr(self): try: code = self.rule_code except __HOLE__: return repr(self) if self.n != 1: fstr = '%d%s' % (self.n, code) else: fstr = code if self.offset: fstr += self._offset_str() return fstr
NotImplementedError
dataset/ETHPy150Open pydata/pandas/pandas/tseries/offsets.py/BusinessDay.freqstr
9,412
def _validate_time(self, t_input): from datetime import time as dt_time import time if isinstance(t_input, compat.string_types): try: t = time.strptime(t_input, '%H:%M') return dt_time(hour=t.tm_hour, minute=t.tm_min) except __HOLE__: raise ValueError("time data must match '%H:%M' format") elif isinstance(t_input, dt_time): if t_input.second != 0 or t_input.microsecond != 0: raise ValueError( "time data must be specified only with hour and minute") return t_input else: raise ValueError("time data must be string or datetime.time")
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/tseries/offsets.py/BusinessHourMixin._validate_time
9,413
def get_calendar(self, weekmask, holidays, calendar): """Generate busdaycalendar""" if isinstance(calendar, np.busdaycalendar): if not holidays: holidays = tuple(calendar.holidays) elif not isinstance(holidays, tuple): holidays = tuple(holidays) else: # trust that calendar.holidays and holidays are # consistent pass return calendar, holidays if holidays is None: holidays = [] try: holidays = holidays + calendar.holidays().tolist() except __HOLE__: pass holidays = [self._to_dt64(dt, dtype='datetime64[D]') for dt in holidays] holidays = tuple(sorted(holidays)) kwargs = {'weekmask': weekmask} if holidays: kwargs['holidays'] = holidays busdaycalendar = np.busdaycalendar(**kwargs) return busdaycalendar, holidays
AttributeError
dataset/ETHPy150Open pydata/pandas/pandas/tseries/offsets.py/CustomBusinessDay.get_calendar
9,414
@internationalizeDocstring def base(self, irc, msg, args, frm, to, number): """<fromBase> [<toBase>] <number> Converts <number> from base <fromBase> to base <toBase>. If <toBase> is left out, it converts to decimal. """ if not number: number = str(to) to = 10 try: irc.reply(self._convertBaseToBase(number, to, frm)) except __HOLE__: irc.error(_('Invalid <number> for base %s: %s') % (frm, number))
ValueError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Math/plugin.py/Math.base
9,415
@internationalizeDocstring def calc(self, irc, msg, args, text): """<math expression> Returns the value of the evaluated <math expression>. The syntax is Python syntax; the type of arithmetic is floating point. Floating point arithmetic is used in order to prevent a user from being able to crash to the bot with something like '10**10**10**10'. One consequence is that large values such as '10**24' might not be exact. """ try: text = str(text) except UnicodeEncodeError: irc.error(_("There's no reason you should have fancy non-ASCII " "characters in your mathematical expression. " "Please remove them.")) return if self._calc_match_forbidden_chars.match(text): # Note: this is important to keep this to forbid usage of # __builtins__ irc.error(_('There\'s really no reason why you should have ' 'underscores or brackets in your mathematical ' 'expression. Please remove them.')) return text = self._calc_remover(text) if 'lambda' in text: irc.error(_('You can\'t use lambda in this command.')) return text = text.lower() def handleMatch(m): s = m.group(1) if s.startswith('0x'): i = int(s, 16) elif s.startswith('0') and '.' not in s: try: i = int(s, 8) except ValueError: i = int(s) else: i = float(s) x = complex(i) if x.imag == 0: x = x.real # Need to use string-formatting here instead of str() because # use of str() on large numbers loses information: # str(float(33333333333333)) => '3.33333333333e+13' # float('3.33333333333e+13') => 33333333333300.0 return '%.16f' % x return str(x) text = self._mathRe.sub(handleMatch, text) try: self.log.info('evaluating %q from %s', text, msg.prefix) x = complex(eval(text, self._mathSafeEnv, self._mathSafeEnv)) irc.reply(self._complexToString(x)) except OverflowError: maxFloat = math.ldexp(0.9999999999999999, 1024) irc.error(_('The answer exceeded %s or so.') % maxFloat) except TypeError: irc.error(_('Something in there wasn\'t a valid number.')) except __HOLE__ as e: irc.error(_('%s is not a defined function.') % str(e).split()[1]) except Exception as e: irc.error(str(e))
NameError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Math/plugin.py/Math.calc
9,416
@internationalizeDocstring def icalc(self, irc, msg, args, text): """<math expression> This is the same as the calc command except that it allows integer math, and can thus cause the bot to suck up CPU. Hence it requires the 'trusted' capability to use. """ if self._calc_match_forbidden_chars.match(text): # Note: this is important to keep this to forbid usage of # __builtins__ irc.error(_('There\'s really no reason why you should have ' 'underscores or brackets in your mathematical ' 'expression. Please remove them.')) return # This removes spaces, too, but we'll leave the removal of _[] for # safety's sake. text = self._calc_remover(text) if 'lambda' in text: irc.error(_('You can\'t use lambda in this command.')) return text = text.replace('lambda', '') try: self.log.info('evaluating %q from %s', text, msg.prefix) irc.reply(str(eval(text, self._mathEnv, self._mathEnv))) except OverflowError: maxFloat = math.ldexp(0.9999999999999999, 1024) irc.error(_('The answer exceeded %s or so.') % maxFloat) except TypeError: irc.error(_('Something in there wasn\'t a valid number.')) except __HOLE__ as e: irc.error(_('%s is not a defined function.') % str(e).split()[1]) except Exception as e: irc.error(utils.exnToString(e))
NameError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Math/plugin.py/Math.icalc
9,417
def rpn(self, irc, msg, args): """<rpn math expression> Returns the value of an RPN expression. """ stack = [] for arg in args: try: x = complex(arg) if x == abs(x): x = abs(x) stack.append(x) except ValueError: # Not a float. if arg in self._mathSafeEnv: f = self._mathSafeEnv[arg] if callable(f): called = False arguments = [] while not called and stack: arguments.append(stack.pop()) try: stack.append(f(*arguments)) called = True except __HOLE__: pass if not called: irc.error(_('Not enough arguments for %s') % arg) return else: stack.append(f) elif arg in self._rpnEnv: self._rpnEnv[arg](stack) else: arg2 = stack.pop() arg1 = stack.pop() s = '%s%s%s' % (arg1, arg, arg2) try: stack.append(eval(s, self._mathSafeEnv, self._mathSafeEnv)) except SyntaxError: irc.error(format(_('%q is not a defined function.'), arg)) return if len(stack) == 1: irc.reply(str(self._complexToString(complex(stack[0])))) else: s = ', '.join(map(self._complexToString, list(map(complex, stack)))) irc.reply(_('Stack: [%s]') % s)
TypeError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Math/plugin.py/Math.rpn
9,418
@internationalizeDocstring def convert(self, irc, msg, args, number, unit1, unit2): """[<number>] <unit> to <other unit> Converts from <unit> to <other unit>. If number isn't given, it defaults to 1. For unit information, see 'units' command. """ try: digits = len(str(number).split('.')[1]) except __HOLE__: digits = 0 try: newNum = convertcore.convert(number, unit1, unit2) if isinstance(newNum, float): zeros = 0 for char in str(newNum).split('.')[1]: if char != '0': break zeros += 1 # Let's add one signifiant digit. Physicists would not like # that, but common people usually do not give extra zeros... # (for example, with '32 C to F', an extra digit would be # expected). newNum = round(newNum, digits + 1 + zeros) newNum = self._floatToString(newNum) irc.reply(str(newNum)) except convertcore.UnitDataError as ude: irc.error(str(ude))
IndexError
dataset/ETHPy150Open ProgVal/Limnoria/plugins/Math/plugin.py/Math.convert
9,419
def all_projects(): if not REPODIR: return # Future: make this path parameterisable. excludes = set(['tempest', 'requirements']) for name in PROJECTS: name = name.strip() short_name = name.split('/')[-1] try: with open(os.path.join( REPODIR, short_name, 'setup.py'), 'rt') as f: if 'pbr' not in f.read(): continue except __HOLE__: continue if short_name in excludes: continue yield (short_name, dict(name=name, short_name=short_name))
IOError
dataset/ETHPy150Open blue-yonder/pyscaffold/pyscaffold/contrib/pbr/pbr/tests/test_integration.py/all_projects
9,420
def emit(self, record): try: msg = self.format(record) if record.levelno >= self.levelno: self.write(msg) else: self.transient_write(msg) except (KeyboardInterrupt, __HOLE__): raise except: self.handleError(record)
SystemExit
dataset/ETHPy150Open jart/fabulous/fabulous/logs.py/TransientStreamHandler.emit
9,421
def jsinclude(self, translator, node, *args, **kwargs): if len(node.args) != 1: raise TranslationError( "jsinclude function requires one argument", node.node) if ( isinstance(node.args[0], translator.ast.Const) and isinstance(node.args[0].value, str) ): try: data = open(node.args[0].value, 'r').read() except __HOLE__, e: raise TranslationError( "Cannot include file '%s': %s" % (node.args[0].value, e), node.node) translator.ignore_debug = True return data, False else: raise TranslationError( "jsinclude function only supports constant strings", node.node)
IOError
dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/translator_proto.py/__Pyjamas__.jsinclude
9,422
def parse_decorators(self, node, funcname, current_class = None, is_method = False, bind_type = None): if node.decorators is None: return False, False, '%s' self.push_lookup() self.add_lookup('variable', '%s', '%s') code = '%s' staticmethod = False classmethod = False lineno=node.lineno if is_method: bind_type = bind_type or "bound" def add_callfunc(code, d, generic=True): tnode = self.ast.CallFunc(d, [self.ast.Name('%s')], star_args=None, dstar_args=None, lineno=lineno) code = code % self._callfunc_code(tnode, None) if is_method and (bind_type == "bound") and generic: try: bind_type_num = BIND_TYPES_NUMERIC[bind_type] except __HOLE__: raise TranslationError("Unknown bind type: %s" % bind_type, node) code = "$pyjs__decorated_method('%(method_name)s', %(code)s, %(bind_type)s)" % \ { "method_name": node.name, "code": code, "bind_type": bind_type_num } return code for d in node.decorators: if isinstance(d, self.ast.Getattr): if isinstance(d.expr, self.ast.Name): if d.expr.name == 'compiler': raise TranslationError( "The @compiler decorator is deprecated. Use from __pyjamas__ import setCompilerOptions", node, self.module_name) if d.attrname in ("setter", "getter", "deleter"): code = add_callfunc(code, d, generic=False) else: code = add_callfunc(code, d) else: code = add_callfunc(code, d) elif isinstance(d, self.ast.Name): if d.name == 'staticmethod': staticmethod = True elif d.name == 'classmethod': classmethod = True elif d.name == 'property': code = add_callfunc(code, d, generic=False) else: code = add_callfunc(code, d) else: raise TranslationError( "Unsupported decorator '%s'" % d, node, self.module_name) self.pop_lookup() if code != '%s': code = code % "@{{staticmethod}}(%s)" if staticmethod: code = "@{{staticmethod}}(%s)" % code return (staticmethod, classmethod, code) # Join an list into a variable with optional attributes
KeyError
dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/translator_proto.py/Translator.parse_decorators
9,423
def func_args(self, node, current_klass, function_name, bind_type, args, stararg, dstararg): try: bind_type = BIND_TYPES_NUMERIC[bind_type] except __HOLE__: raise TranslationError("Unknown bind type: %s" % bind_type, node) _args = [] default_pos = len(args) - len(node.defaults) for idx, arg in enumerate(args): if idx < default_pos: _args.append("['%s']" % arg) else: default_value = self.expr(node.defaults[idx-default_pos], current_klass) _args.append("""['%s', %s]""" % (arg, default_value)) args = ",".join(_args) if dstararg: args = "['%s'],%s" % (dstararg, args) else: args = "null,%s" % args if stararg: args = "'%s',%s" % (stararg, args) else: args = "null,%s" % args args = '[' + args + ']' # remove any empty tail if args.endswith(',]'): args = args[:-2] + ']' if function_name is None: self.w( "\t, %d, %s);" % (bind_type, args)) else: self.w( self.spacing() + "%s.__bind_type__ = %s;" % (function_name, bind_type)) self.w( self.spacing() + "%s.__args__ = %s;" % (function_name, args))
KeyError
dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/translator_proto.py/Translator.func_args
9,424
def _from(self, node, current_klass, root_level = False): if node.modname == '__pyjamas__': # special module to help make pyjamas modules loadable in # the python interpreter for name in node.names: ass_name = name[1] or name[0] try: jsname = getattr(__pyjamas__, name[0]) if callable(jsname): self.add_lookup("__pyjamas__", ass_name, name[0]) else: self.add_lookup("__pyjamas__", ass_name, jsname) except __HOLE__, e: #raise TranslationError("Unknown __pyjamas__ import: %s" % name, node) pass return if node.modname == '__javascript__': for name in node.names: ass_name = name[1] or name[0] self.add_lookup("__javascript__", ass_name, name[0]) return if node.modname == '__future__': for name in node.names: future = getattr(__future__, name[0], None) if callable(future): future(self) else: # Ignoring from __future__ import name[0] pass return # XXX: hack for in-function checking, we should have another # object to check our scope absPath = False modname = node.modname if hasattr(node, 'level') and node.level > 0: absPath = True modname = self.relative_import_context.split('.') level = node.level - 1 if len(modname) <= level: raise TranslationError( "Attempted relative import beyond toplevel package", node, self.module_name) if level: modname = '.'.join(modname[:-node.level]) else: modname = self.relative_import_context if node.modname: modname += '.' + node.modname for name in node.names: if name[0] == "*": self._doImport(((modname, name[0]),), current_klass, root_level, False, absPath, True) continue sub = modname + '.' + name[0] ass_name = name[1] or name[0] self._doImport(((sub, ass_name),), current_klass, root_level, True, absPath)
AttributeError
dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/translator_proto.py/Translator._from
9,425
def _callfunc_code(self, v, current_klass, is_statement=False, optlocal_var=False): self.ignore_debug = False method_name = None if isinstance(v.node, self.ast.Name): name_type, pyname, jsname, depth, is_local = self.lookup(v.node.name) if name_type == '__pyjamas__': try: raw_js = getattr(__pyjamas__, v.node.name) if callable(raw_js): raw_js, has_js_return = raw_js(self, v, current_klass, is_statement=is_statement) if has_js_return: self.has_js_return = True else: raw_js = self.translate_escaped_names(raw_js, current_klass) return raw_js except __HOLE__, e: raise TranslationError( "Unknown __pyjamas__ function %s" % pyname, v.node, self.module_name) except TranslationError, e: raise TranslationError(e.msg, v, self.module_name) elif v.node.name == 'locals': return """$p.dict({%s})""" % (",".join(["'%s': %s" % (pyname, self.lookup_stack[-1][pyname][2]) for pyname in self.lookup_stack[-1] if self.lookup_stack[-1][pyname][0] not in ['__pyjamas__', 'global']])) elif v.node.name == 'globals': # XXX: Should be dictproxy, to handle changes return "@{{_globals}}(%s)" % self.modpfx()[:-1] elif v.node.name == 'len' and depth == -1 and len(v.args) == 1: expr = self.expr(v.args[0], current_klass) return self.inline_len_code(expr) else: if name_type is None: # What to do with a (yet) unknown name? # Just nothing... if optlocal_var: call_name = '(typeof %s == "undefined"?%s:%s)' % ( v.node.name, self.scopeName(v.node.name, depth, is_local), v.node.name, ) else: call_name = self.scopeName(v.node.name, depth, is_local) else: call_name = jsname call_args = [] elif isinstance(v.node, self.ast.Getattr): attrname = self.attrib_remap(v.node.attrname) if isinstance(v.node.expr, self.ast.Name): call_name, method_name = self._name2(v.node.expr, current_klass, attrname) call_args = [] elif isinstance(v.node.expr, self.ast.Getattr): call_name = self._getattr2(v.node.expr, current_klass, v.node.attrname) method_name = call_name.pop() call_name = self.attrib_join(call_name) call_args = [] elif isinstance(v.node.expr, self.ast.CallFunc): call_name = self._callfunc(v.node.expr, current_klass) method_name = attrname call_args = [] elif isinstance(v.node.expr, self.ast.Subscript): call_name = self._subscript(v.node.expr, current_klass) method_name = attrname call_args = [] elif isinstance(v.node.expr, self.ast.Const): call_name = self.expr(v.node.expr, current_klass) method_name = attrname call_args = [] elif isinstance(v.node.expr, self.ast.Slice): call_name = self._slice(v.node.expr, current_klass) method_name = attrname call_args = [] else: raise TranslationError( "unsupported type (in _callfunc)", v.node.expr, self.module_name) elif isinstance(v.node, self.ast.CallFunc): call_name = self._callfunc(v.node, current_klass) call_args = [] elif isinstance(v.node, self.ast.Subscript): call_name = self._subscript(v.node, current_klass) call_args = [] else: raise TranslationError( "unsupported type (in _callfunc)", v.node, self.module_name) if method_name in pyjs_attrib_remap: method_name = pyjs_attrib_remap[method_name] call_name = strip_py(call_name) kwargs = [] star_arg_name = None if v.star_args: star_arg_name = self.expr(v.star_args, current_klass) dstar_arg_name = None if v.dstar_args: dstar_arg_name = self.expr(v.dstar_args, current_klass) for ch4 in v.args: if isinstance(ch4, self.ast.Keyword): kwarg = self.vars_remap(ch4.name) + ":" + \ self.expr(ch4.expr, current_klass) kwargs.append(kwarg) else: arg = self.expr(ch4, current_klass) call_args.append(arg) if kwargs: fn_args = ", ".join(['{' + ', '.join(kwargs) + '}']+call_args) else: fn_args = ", ".join(['{}']+call_args) if kwargs or star_arg_name or dstar_arg_name: if not star_arg_name: star_arg_name = 'null' if not dstar_arg_name: dstar_arg_name = 'null' if method_name is None: call_code = ("$pyjs_kwargs_call(null, "+call_name+", " + star_arg_name + ", " + dstar_arg_name + ", ["+fn_args+"]" + ")") else: call_code = ("$pyjs_kwargs_call("+call_name+", '"+method_name+"', " + star_arg_name + ", " + dstar_arg_name + ", ["+fn_args+"]" + ")") else: if not method_name is None: call_name = "%s['%s']" % (call_name, method_name) call_code = call_name + "(" + ", ".join(call_args) + ")" return call_code
AttributeError
dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/translator_proto.py/Translator._callfunc_code
9,426
def zAxis(self, row, zStructuralNode, zAspectStructuralNodes, discriminatorsTable): if zStructuralNode is not None: label = zStructuralNode.header(lang=self.lang) choiceLabel = None effectiveStructuralNode = zStructuralNode if zStructuralNode.choiceStructuralNodes: # same as combo box selection in GUI mode if not discriminatorsTable: self.zStrNodesWithChoices.insert(0, zStructuralNode) # iteration from last is first try: effectiveStructuralNode = zStructuralNode.choiceStructuralNodes[zStructuralNode.choiceNodeIndex] choiceLabel = effectiveStructuralNode.header(lang=self.lang) if not label and choiceLabel: label = choiceLabel # no header for choice choiceLabel = None except __HOLE__: pass if choiceLabel: if self.dataCols > 3: zLabelSpan = 2 else: zLabelSpan = 1 zChoiceLabelSpan = self.dataCols - zLabelSpan else: zLabelSpan = self.dataCols if self.type == HTML: etree.SubElement(self.rowElts[row-1], "{http://www.w3.org/1999/xhtml}th", attrib={"class":"zAxisHdr", "style":"max-width:200pt;text-align:left;border-bottom:.5pt solid windowtext", "colspan": str(zLabelSpan)} # "2"} ).text = label if choiceLabel: etree.SubElement(self.rowElts[row-1], "{http://www.w3.org/1999/xhtml}th", attrib={"class":"zAxisHdr", "style":"max-width:200pt;text-align:left;border-bottom:.5pt solid windowtext", "colspan": str(zChoiceLabelSpan)} # "2"} ).text = choiceLabel elif self.type == XML: # headers element built for first pass on z axis if discriminatorsTable: brkdownNode = zStructuralNode.breakdownNode if zStructuralNode.choiceStructuralNodes: # same as combo box selection in GUI mode # hdrElt.set("label", label) if discriminatorsTable: def zSpan(zNode, startNode=False): if startNode: thisSpan = 0 elif zStructuralNode.choiceStructuralNodes: thisSpan = len(zStructuralNode.choiceStructuralNodes) else: thisSpan = 1 return sum(zSpan(z) for z in zNode.childStructuralNodes) + thisSpan span = zSpan(zStructuralNode, True) for i, choiceStructuralNode in enumerate(zStructuralNode.choiceStructuralNodes): choiceLabel = choiceStructuralNode.header(lang=self.lang) cellElt = etree.Element(self.tableModelQName("cell"), attrib={"span": str(span)} if span > 1 else None) self.headerCells[i].append((brkdownNode, cellElt)) # self.structuralNodeModelElements.append((zStructuralNode, cellElt)) elt = etree.SubElement(cellElt, self.tableModelQName("label")) if choiceLabel: elt.text = choiceLabel #else: # choiceLabel from above # etree.SubElement(hdrElt, self.tableModelQName("label") # ).text = choiceLabel else: # no combo choices, single label cellElt = etree.Element(self.tableModelQName("cell")) self.headerCells[0].append((brkdownNode, cellElt)) # self.structuralNodeModelElements.append((zStructuralNode, cellElt)) elt = etree.SubElement(cellElt, self.tableModelQName("label")) if label: elt.text = label for aspect in aspectModels[self.aspectModel]: if effectiveStructuralNode.hasAspect(aspect, inherit=True): #implies inheriting from other z axes if aspect == Aspect.DIMENSIONS: for dim in (effectiveStructuralNode.aspectValue(Aspect.DIMENSIONS, inherit=True) or emptyList): zAspectStructuralNodes[dim].add(effectiveStructuralNode) else: zAspectStructuralNodes[aspect].add(effectiveStructuralNode) for zStructuralNode in zStructuralNode.childStructuralNodes: self.zAxis(row + 1, zStructuralNode, zAspectStructuralNodes, discriminatorsTable)
KeyError
dataset/ETHPy150Open Arelle/Arelle/arelle/ViewFileRenderedGrid.py/ViewRenderedGrid.zAxis
9,427
def __init__(self, element): # No call to super(), the type object will process that. self.name = testXMLAttribute(element, "name") try: self.content = eval(element[-1].tag.split("}")[-1])(element[-1]) except __HOLE__: self.content = None except BaseException: raise # Revert to the content if attribute does not exists
IndexError
dataset/ETHPy150Open geopython/OWSLib/owslib/swe/common.py/NamedObject.__init__
9,428
def get_time(value, referenceTime, uom): try: value = parser.parse(value) except (AttributeError, __HOLE__): # Most likely an integer/float using a referenceTime try: if uom.lower() == "s": value = referenceTime + timedelta(seconds=float(value)) elif uom.lower() == "min": value = referenceTime + timedelta(minutes=float(value)) elif uom.lower() == "h": value = referenceTime + timedelta(hours=float(value)) elif uom.lower() == "d": value = referenceTime + timedelta(days=float(value)) except (AttributeError, ValueError): pass except OverflowError: # Too many numbers (> 10) or INF/-INF if value.lower() == "inf": value = InfiniteDateTime() elif value.lower() == "-inf": value = NegativeInfiniteDateTime() return value
ValueError
dataset/ETHPy150Open geopython/OWSLib/owslib/swe/common.py/get_time
9,429
def __init__(self, element): super(Time, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, __HOLE__): self.referenceTime = None value = testXMLValue(element.find(nspv("swe20:value"))) # TimePosition, min=0, max=1 self.value = get_time(value, self.referenceTime, self.uom)
ValueError
dataset/ETHPy150Open geopython/OWSLib/owslib/swe/common.py/Time.__init__
9,430
def __init__(self, element): super(TimeRange, self).__init__(element) # Elements self.uom = get_uom(element.find(nspv("swe20:uom"))) try: self.constraint = AllowedTimes(element.find(nspv("swe20:constraint/swe20:AllowedTimes"))) # AllowedTimes, min=0, max=1 except: self.constraint = None # Attributes self.localFrame = testXMLAttribute(element,"localFrame") # anyURI, optional try: self.referenceTime = parser.parse(testXMLAttribute(element,"referenceTime")) # dateTime, optional except (AttributeError, __HOLE__): self.referenceTime = None values = make_pair(testXMLValue(element.find(nspv("swe20:value")))) # TimePosition, min=0, max=1 self.value = [get_time(t, self.referenceTime, self.uom) for t in values]
ValueError
dataset/ETHPy150Open geopython/OWSLib/owslib/swe/common.py/TimeRange.__init__
9,431
def action(self): ''' Read in a command and execute it, send the return back up to the main master process ''' self.lane_stack.value.serviceAll() while self.lane_stack.value.rxMsgs: msg, sender = self.lane_stack.value.rxMsgs.popleft() try: s_estate, s_yard, s_share = msg['route']['src'] d_estate, d_yard, d_share = msg['route']['dst'] except (ValueError, __HOLE__): log.error('Received invalid message: {0}'.format(msg)) return log.debug("**** Worker Router rxMsg\n msg= {0}\n".format(msg)) if 'load' in msg: cmd = msg['load'].get('cmd') if not cmd: continue elif cmd.startswith('__'): continue ret = {} if d_share == 'remote_cmd': if hasattr(self.remote_loader.value, cmd): ret['return'] = getattr(self.remote_loader.value, cmd)(msg['load']) elif d_share == 'local_cmd': if hasattr(self.local_loader.value, cmd): ret['return'] = getattr(self.local_loader.value, cmd)(msg['load']) else: ret = {'error': 'Invalid request'} if cmd == 'publish' and 'pub' in ret.get('return', {}): r_share = 'pub_ret' ret['__worker_verify'] = self.worker_verify.value else: r_share = s_share if cmd not in INHIBIT_RETURN: ret['route'] = { 'src': (None, self.lane_stack.value.local.name, None), 'dst': (s_estate, s_yard, r_share) } self.lane_stack.value.transmit(ret, self.lane_stack.value.fetchUidByName('manor')) self.lane_stack.value.serviceAll()
IndexError
dataset/ETHPy150Open saltstack/salt/salt/daemons/flo/worker.py/SaltRaetWorkerRouter.action
9,432
def test_abstract_manager(self): # Accessing the manager on an abstract model should # raise an attribute error with an appropriate message. try: AbstractBase3.objects.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: # This error message isn't ideal, but if the model is abstract and # a lot of the class instantiation logic isn't invoked; if the # manager is implied, then we don't get a hook to install the # error-raising manager. self.assertEqual(str(e), "type object 'AbstractBase3' has no attribute 'objects'")
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_abstract_manager
9,433
def test_custom_abstract_manager(self): # Accessing the manager on an abstract model with an custom # manager should raise an attribute error with an appropriate # message. try: AbstractBase2.restricted.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: self.assertEqual(str(e), "Manager isn't available; AbstractBase2 is abstract")
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_custom_abstract_manager
9,434
def test_explicit_abstract_manager(self): # Accessing the manager on an abstract model with an explicit # manager should raise an attribute error with an appropriate # message. try: AbstractBase1.objects.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: self.assertEqual(str(e), "Manager isn't available; AbstractBase1 is abstract")
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_explicit_abstract_manager
9,435
def test_swappable_manager(self): try: # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. old_app_models = copy.deepcopy(cache.app_models) old_app_store = copy.deepcopy(cache.app_store) settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent' class SwappableModel(models.Model): class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model should # raise an attribute error with a helpful message try: SwappableModel.objects.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: del settings.TEST_SWAPPABLE_MODEL cache.app_models = old_app_models cache.app_store = old_app_store
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_swappable_manager
9,436
def test_custom_swappable_manager(self): try: # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. old_app_models = copy.deepcopy(cache.app_models) old_app_store = copy.deepcopy(cache.app_store) settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent' class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message try: SwappableModel.stuff.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: del settings.TEST_SWAPPABLE_MODEL cache.app_models = old_app_models cache.app_store = old_app_store
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_custom_swappable_manager
9,437
def test_explicit_swappable_manager(self): try: # This test adds dummy models to the app cache. These # need to be removed in order to prevent bad interactions # with the flush operation in other tests. old_app_models = copy.deepcopy(cache.app_models) old_app_store = copy.deepcopy(cache.app_store) settings.TEST_SWAPPABLE_MODEL = 'managers_regress.Parent' class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message try: SwappableModel.objects.all() self.fail('Should raise an AttributeError') except __HOLE__ as e: self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: del settings.TEST_SWAPPABLE_MODEL cache.app_models = old_app_models cache.app_store = old_app_store
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/managers_regress/tests.py/ManagersRegressionTests.test_explicit_swappable_manager
9,438
def _final_version(parsed_version): try: return not parsed_version.is_prerelease except __HOLE__: # Older setuptools for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True
AttributeError
dataset/ETHPy150Open faassen/graphql-wsgi/bootstrap-buildout.py/_final_version
9,439
def _get_results(self): try: return self._cached_results except __HOLE__: self._cached_results = simplejson.loads(self._results) return self._cached_results
AttributeError
dataset/ETHPy150Open mollyproject/mollyproject/molly/geolocation/models.py/Geocode._get_results
9,440
def __init__(self, external_file=None): """Initialize the error fixer. Args: external_file: If included, all output will be directed to this file instead of overwriting the files the errors are found in. """ errorhandler.ErrorHandler.__init__(self) self._file_name = None self._file_token = None self._external_file = external_file try: self._fix_error_codes = set([errors.ByName(error.upper()) for error in FLAGS.fix_error_codes]) except __HOLE__ as ke: raise ValueError('Unknown error code ' + ke.args[0])
KeyError
dataset/ETHPy150Open google/closure-linter/closure_linter/error_fixer.py/ErrorFixer.__init__
9,441
def __eq__(self, other): """ :param other: an IP set :return: ``True`` if this IP set is equivalent to the ``other`` IP set, ``False`` otherwise. """ try: return self._cidrs == other._cidrs except __HOLE__: return NotImplemented
AttributeError
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/sets.py/IPSet.__eq__
9,442
def __ne__(self, other): """ :param other: an IP set :return: ``False`` if this IP set is equivalent to the ``other`` IP set, ``True`` otherwise. """ try: return self._cidrs != other._cidrs except __HOLE__: return NotImplemented
AttributeError
dataset/ETHPy150Open drkjam/netaddr/netaddr/ip/sets.py/IPSet.__ne__
9,443
def __enter__(self): self.lockfile = open(self.fname, 'w') while True: try: # Using non-blocking locks since green threads are not # patched to deal with blocking locking calls. # Also upon reading the MSDN docs for locking(), it seems # to have a laughable 10 attempts "blocking" mechanism. self.trylock() return self except __HOLE__ as e: if e.errno in (errno.EACCES, errno.EAGAIN): # external locks synchronise things like iptables # updates - give it some time to prevent busy spinning time.sleep(0.01) else: raise
IOError
dataset/ETHPy150Open openstack/rack/rack/openstack/common/lockutils.py/_InterProcessLock.__enter__
9,444
def __exit__(self, exc_type, exc_val, exc_tb): try: self.unlock() self.lockfile.close() except __HOLE__: LOG.exception(_("Could not release the acquired lock `%s`"), self.fname)
IOError
dataset/ETHPy150Open openstack/rack/rack/openstack/common/lockutils.py/_InterProcessLock.__exit__
9,445
@contextlib.contextmanager def lock(name, lock_file_prefix=None, external=False, lock_path=None): """Context based lock This function yields a `threading.Semaphore` instance (if we don't use eventlet.monkey_patch(), else `semaphore.Semaphore`) unless external is True, in which case, it'll yield an InterProcessLock instance. :param lock_file_prefix: The lock_file_prefix argument is used to provide lock files on disk with a meaningful prefix. :param external: The external keyword argument denotes whether this lock should work across multiple processes. This means that if two different workers both run a a method decorated with @synchronized('mylock', external=True), only one of them will execute at a time. :param lock_path: The lock_path keyword argument is used to specify a special location for external lock files to live. If nothing is set, then CONF.lock_path is used as a default. """ with _semaphores_lock: try: sem = _semaphores[name] except __HOLE__: sem = threading.Semaphore() _semaphores[name] = sem with sem: LOG.debug(_('Got semaphore "%(lock)s"'), {'lock': name}) # NOTE(mikal): I know this looks odd if not hasattr(local.strong_store, 'locks_held'): local.strong_store.locks_held = [] local.strong_store.locks_held.append(name) try: if external and not CONF.disable_process_locking: LOG.debug(_('Attempting to grab file lock "%(lock)s"'), {'lock': name}) # We need a copy of lock_path because it is non-local local_lock_path = lock_path or CONF.lock_path if not local_lock_path: raise cfg.RequiredOptError('lock_path') if not os.path.exists(local_lock_path): fileutils.ensure_tree(local_lock_path) LOG.info(_('Created lock path: %s'), local_lock_path) def add_prefix(name, prefix): if not prefix: return name sep = '' if prefix.endswith('-') else '-' return '%s%s%s' % (prefix, sep, name) # NOTE(mikal): the lock name cannot contain directory # separators lock_file_name = add_prefix(name.replace(os.sep, '_'), lock_file_prefix) lock_file_path = os.path.join(local_lock_path, lock_file_name) try: lock = InterProcessLock(lock_file_path) with lock as lock: LOG.debug(_('Got file lock "%(lock)s" at %(path)s'), {'lock': name, 'path': lock_file_path}) yield lock finally: LOG.debug(_('Released file lock "%(lock)s" at %(path)s'), {'lock': name, 'path': lock_file_path}) else: yield sem finally: local.strong_store.locks_held.remove(name)
KeyError
dataset/ETHPy150Open openstack/rack/rack/openstack/common/lockutils.py/lock
9,446
def search(self, terms): torrents = [] url = self.search_uri % quote_plus(terms) try: f = urlopen(url) soup = BeautifulStoneSoup(f.read()) for item in soup.findAll('item'): torrents.append({ 'url': item.enclosure['url'], 'name': item.title.text, 'seeds': int(item.find('torrent:seeds').text), 'leechers': int(item.find('torrent:peers').text), }) except __HOLE__ as e: if e.code == 404: pass else: raise return torrents
HTTPError
dataset/ETHPy150Open correl/Transmission-XBMC/resources/lib/search.py/Kickass.search
9,447
def is_valid_mac(addr): """Check the syntax of a given mac address. The acceptable format is xx:xx:xx:xx:xx:xx """ addrs = addr.split(':') if len(addrs) != 6: return False for m in addrs: try: if int(m, 16) > 255: return False except __HOLE__: return False return True
ValueError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/common/utils.py/is_valid_mac
9,448
def make_cidr(gw, mask): """Create network address in CIDR format. Return network address for a given gateway address and netmask. """ try: int_mask = (0xFFFFFFFF << (32 - int(mask))) & 0xFFFFFFFF gw_addr_int = struct.unpack('>L', socket.inet_aton(gw))[0] & int_mask return (socket.inet_ntoa(struct.pack("!I", gw_addr_int)) + '/' + str(mask)) except (socket.error, struct.error, ValueError, __HOLE__): return
TypeError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/common/utils.py/make_cidr
9,449
def find_agent_host_id(this_host): """Returns the neutron agent host id for RHEL-OSP6 HA setup.""" host_id = this_host try: for root, dirs, files in os.walk('/run/resource-agents'): for fi in files: if 'neutron-scale-' in fi: host_id = 'neutron-n-' + fi.split('-')[2] break return host_id except __HOLE__: return host_id
IndexError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/common/utils.py/find_agent_host_id
9,450
def introspect_module(module, module_doc, module_name=None, preliminary=False): """ Add API documentation information about the module C{module} to C{module_doc}. """ module_doc.specialize_to(ModuleDoc) # Record the module's docformat if hasattr(module, '__docformat__'): module_doc.docformat = unicode(module.__docformat__) # Record the module's filename if hasattr(module, '__file__'): try: module_doc.filename = unicode(module.__file__) except KeyboardInterrupt: raise except: pass if module_doc.filename is not UNKNOWN: try: module_doc.filename = py_src_filename(module_doc.filename) except ValueError: pass # If this is just a preliminary introspection, then don't do # anything else. (Typically this is true if this module was # imported, but is not included in the set of modules we're # documenting.) module_doc.variables = {} if preliminary: return # Record the module's docstring if hasattr(module, '__doc__'): module_doc.docstring = get_docstring(module) # If the module has a __path__, then it's (probably) a # package; so set is_package=True and record its __path__. if hasattr(module, '__path__'): module_doc.is_package = True try: module_doc.path = [unicode(p) for p in module.__path__] except __HOLE__: raise except: pass else: module_doc.is_package = False # Make sure we have a name for the package. dotted_name = module_doc.canonical_name if dotted_name is UNKNOWN: dotted_name = DottedName(module.__name__) name_without_primes = DottedName(str(dotted_name).replace("'", "")) # Record the module's parent package, if it has one. if len(dotted_name) > 1: package_name = str(dotted_name.container()) package = sys.modules.get(package_name) if package is not None: module_doc.package = introspect_docs(package) else: module_doc.package = None # Initialize the submodules property module_doc.submodules = [] # Add the module to its parent package's submodules list. if module_doc.package not in (None, UNKNOWN): module_doc.package.submodules.append(module_doc) # Look up the module's __all__ attribute (public names). public_names = None if hasattr(module, '__all__'): try: public_names = set([str(name) for name in module.__all__]) except KeyboardInterrupt: raise except: pass # Record the module's variables. module_doc.variables = {} for child_name in dir(module): if child_name in UNDOCUMENTED_MODULE_VARS: continue child = getattr(module, child_name) # Create a VariableDoc for the child, and introspect its # value if it's defined in this module. container = get_containing_module(child) if (((container is not None and container == name_without_primes) or (public_names is not None and child_name in public_names)) and not inspect.ismodule(child)): # Local variable. child_val_doc = introspect_docs(child, context=module_doc, module_name=dotted_name) child_var_doc = VariableDoc(name=child_name, value=child_val_doc, is_imported=False, container=module_doc, docs_extracted_by='introspecter') elif ((container is None or module_doc.canonical_name is UNKNOWN) and not inspect.ismodule(child)): # Don't introspect stuff "from __future__" if is_future_feature(child): continue # Possibly imported variable. child_val_doc = introspect_docs(child, context=module_doc) child_var_doc = VariableDoc(name=child_name, value=child_val_doc, container=module_doc, docs_extracted_by='introspecter') else: # Imported variable. child_val_doc = _get_valuedoc(child) child_var_doc = VariableDoc(name=child_name, value=child_val_doc, is_imported=True, container=module_doc, docs_extracted_by='introspecter') # If the module's __all__ attribute is set, use it to set the # variables public/private status and imported status. if public_names is not None: if child_name in public_names: child_var_doc.is_public = True if not isinstance(child_var_doc, ModuleDoc): child_var_doc.is_imported = False else: child_var_doc.is_public = False module_doc.variables[child_name] = child_var_doc return module_doc #//////////////////////////////////////////////////////////// # Class Introspection #//////////////////////////////////////////////////////////// #: A list of class variables that should not be included in a #: class's API documentation.
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/introspect_module
9,451
def introspect_class(cls, class_doc, module_name=None): """ Add API documentation information about the class C{cls} to C{class_doc}. """ class_doc.specialize_to(ClassDoc) # Record the class's docstring. class_doc.docstring = get_docstring(cls) # Record the class's __all__ attribute (public names). public_names = None if hasattr(cls, '__all__'): try: public_names = set([str(name) for name in cls.__all__]) except __HOLE__: raise except: pass # Record the class's metaclass class_doc.metaclass = introspect_docs(type(cls)) # Start a list of subclasses. class_doc.subclasses = [] # Sometimes users will define a __metaclass__ that copies all # class attributes from bases directly into the derived class's # __dict__ when the class is created. (This saves the lookup time # needed to search the base tree for an attribute.) But for the # docs, we only want to list these copied attributes in the # parent. So only add an attribute if it is not identical to an # attribute of a base class. (Unfortunately, this can sometimes # cause an attribute to look like it was inherited, even though it # wasn't, if it happens to have the exact same value as the # corresponding base's attribute.) An example of a case where # this helps is PyQt -- subclasses of QWidget get about 300 # methods injected into them. base_children = {} # Record the class's base classes; and add the class to its # base class's subclass lists. if hasattr(cls, '__bases__'): try: bases = list(cls.__bases__) except: bases = None log.warning("Class '%s' defines __bases__, but it does not " "contain an iterable; ignoring base list." % getattr(cls, '__name__', '??')) if bases is not None: class_doc.bases = [] for base in bases: basedoc = introspect_docs(base) class_doc.bases.append(basedoc) basedoc.subclasses.append(class_doc) bases.reverse() for base in bases: if hasattr(base, '__dict__'): base_children.update(base.__dict__) # The module name is not defined if the class is being introspected # as another class base. if module_name is None and class_doc.defining_module not in (None, UNKNOWN): module_name = class_doc.defining_module.canonical_name # Record the class's local variables. class_doc.variables = {} if hasattr(cls, '__dict__'): private_prefix = '_%s__' % getattr(cls, '__name__', '<none>') for child_name, child in cls.__dict__.items(): if (child_name in base_children and base_children[child_name] == child): continue if child_name.startswith(private_prefix): child_name = child_name[len(private_prefix)-2:] if child_name in UNDOCUMENTED_CLASS_VARS: continue val_doc = introspect_docs(child, context=class_doc, module_name=module_name) var_doc = VariableDoc(name=child_name, value=val_doc, container=class_doc, docs_extracted_by='introspecter') if public_names is not None: var_doc.is_public = (child_name in public_names) class_doc.variables[child_name] = var_doc return class_doc #//////////////////////////////////////////////////////////// # Routine Introspection #////////////////////////////////////////////////////////////
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/introspect_class
9,452
def get_docstring(value, module_name=None): """ Return the docstring for the given value; or C{None} if it does not have a docstring. @rtype: C{unicode} """ docstring = getattr(value, '__doc__', None) if docstring is None: return None elif isinstance(docstring, unicode): return docstring elif isinstance(docstring, str): try: return unicode(docstring, 'ascii') except UnicodeDecodeError: if module_name is None: module_name = get_containing_module(value) if module_name is not None: try: module = get_value_from_name(module_name) filename = py_src_filename(module.__file__) encoding = epydoc.docparser.get_module_encoding(filename) return unicode(docstring, encoding) except __HOLE__: raise except Exception: pass if hasattr(value, '__name__'): name = value.__name__ else: name = repr(value) log.warning("%s's docstring is not a unicode string, but it " "contains non-ascii data -- treating it as " "latin-1." % name) return unicode(docstring, 'latin-1') return None elif value is BuiltinMethodType: # Don't issue a warning for this special case. return None else: if hasattr(value, '__name__'): name = value.__name__ else: name = repr(value) log.warning("%s's docstring is not a string -- ignoring it." % name) return None
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/get_docstring
9,453
def _find_function_module(func): """ @return: The module that defines the given function. @rtype: C{module} @param func: The function whose module should be found. @type func: C{function} """ if hasattr(func, '__module__'): return func.__module__ try: module = inspect.getmodule(func) if module: return module.__name__ except __HOLE__: raise except: pass # This fallback shouldn't usually be needed. But it is needed in # a couple special cases (including using epydoc to document # itself). In particular, if a module gets loaded twice, using # two different names for the same file, then this helps. for module in sys.modules.values(): if (hasattr(module, '__dict__') and hasattr(func, 'func_globals') and func.func_globals is module.__dict__): return module.__name__ return None #//////////////////////////////////////////////////////////// # Introspection Dispatch Table #////////////////////////////////////////////////////////////
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/_find_function_module
9,454
def get_value_from_name(name, globs=None): """ Given a name, return the corresponding value. @param globs: A namespace to check for the value, if there is no module containing the named value. Defaults to __builtin__. """ name = DottedName(name) # Import the topmost module/package. If we fail, then check if # the requested name refers to a builtin. try: module = _import(name[0]) except __HOLE__, e: if globs is None: globs = __builtin__.__dict__ if name[0] in globs: try: return _lookup(globs[name[0]], name[1:]) except: raise e else: raise # Find the requested value in the module/package or its submodules. for i in range(1, len(name)): try: return _lookup(module, name[i:]) except ImportError: pass module = _import('.'.join(name[:i+1])) module = _lookup(module, name[1:i+1]) return module
ImportError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/get_value_from_name
9,455
def _lookup(module, name): val = module for i, identifier in enumerate(name): try: val = getattr(val, identifier) except __HOLE__: exc_msg = ('no variable named %s in %s' % (identifier, '.'.join(name[:1+i]))) raise ImportError(exc_msg) return val
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/_lookup
9,456
def _import(name, filename=None): """ Run the given callable in a 'sandboxed' environment. Currently, this includes saving and restoring the contents of sys and __builtins__; and suppressing stdin, stdout, and stderr. """ # Note that we just do a shallow copy of sys. In particular, # any changes made to sys.modules will be kept. But we do # explicitly store sys.path. old_sys = sys.__dict__.copy() old_sys_path = sys.path[:] old_builtins = __builtin__.__dict__.copy() # Add the current directory to sys.path, in case they're trying to # import a module by name that resides in the current directory. # But add it to the end -- otherwise, the explicit directory added # in get_value_from_filename might get overwritten sys.path.append('') # Suppress input and output. (These get restored when we restore # sys to old_sys). sys.stdin = sys.stdout = sys.stderr = _dev_null sys.__stdin__ = sys.__stdout__ = sys.__stderr__ = _dev_null # Remove any command-line arguments sys.argv = ['(imported)'] try: try: if filename is None: return __import__(name) else: # For importing scripts: return imp.load_source(name, filename) except __HOLE__: raise except: exc_typ, exc_val, exc_tb = sys.exc_info() if exc_val is None: estr = '%s' % (exc_typ,) else: estr = '%s: %s' % (exc_typ.__name__, exc_val) if exc_tb.tb_next is not None: estr += ' (line %d)' % (exc_tb.tb_next.tb_lineno,) raise ImportError(estr) finally: # Restore the important values that we saved. __builtin__.__dict__.clear() __builtin__.__dict__.update(old_builtins) sys.__dict__.clear() sys.__dict__.update(old_sys) sys.path = old_sys_path
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/_import
9,457
def introspect_docstring_lineno(api_doc): """ Try to determine the line number on which the given item's docstring begins. Return the line number, or C{None} if the line number can't be determined. The line number of the first line in the file is 1. """ if api_doc.docstring_lineno is not UNKNOWN: return api_doc.docstring_lineno if isinstance(api_doc, ValueDoc) and api_doc.pyval is not UNKNOWN: try: lines, lineno = inspect.findsource(api_doc.pyval) if not isinstance(api_doc, ModuleDoc): lineno += 1 for lineno in range(lineno, len(lines)): if lines[lineno].split('#', 1)[0].strip(): api_doc.docstring_lineno = lineno + 1 return lineno + 1 except __HOLE__: pass except TypeError: pass except IndexError: log.warning('inspect.findsource(%s) raised IndexError' % api_doc.canonical_name) return None
IOError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/docintrospecter.py/introspect_docstring_lineno
9,458
def inference(self, kern, X, Z, likelihood, Y, mean_function=None, Y_metadata=None, Lm=None, dL_dKmm=None, psi0=None, psi1=None, psi2=None): assert Y.shape[1]==1, "ep in 1D only (for now!)" Kmm = kern.K(Z) if psi1 is None: try: Kmn = kern.K(Z, X) except __HOLE__: Kmn = kern.psi1(Z, X).T else: Kmn = psi1.T if getattr(self, '_ep_approximation', None) is None: mu, Sigma, mu_tilde, tau_tilde, Z_tilde = self._ep_approximation = self.expectation_propagation(Kmm, Kmn, Y, likelihood, Y_metadata) else: mu, Sigma, mu_tilde, tau_tilde, Z_tilde = self._ep_approximation return super(EPDTC, self).inference(kern, X, Z, likelihood, mu_tilde, mean_function=mean_function, Y_metadata=Y_metadata, precision=tau_tilde, Lm=Lm, dL_dKmm=dL_dKmm, psi0=psi0, psi1=psi1, psi2=psi2, Z_tilde=np.log(Z_tilde).sum())
TypeError
dataset/ETHPy150Open SheffieldML/GPy/GPy/inference/latent_function_inference/expectation_propagation.py/EPDTC.inference
9,459
def main(): try: si = None try: print "Trying to connect to VCENTER SERVER . . ." si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password']) except __HOLE__, e: pass atexit.register(Disconnect, si) print "Connected to VCENTER SERVER !" content = si.RetrieveContent() if inputs['operation'] == 'stop' or inputs['operation'] == 'suspend': force = inputs['force'] vm = get_obj(content, [vim.VirtualMachine], inputs['vm_name']) #current_state = vm.runtime.powerState if inputs['operation'] == 'start': invoke_and_track(vm.PowerOn, None) elif inputs['operation'] == 'stop': if not force: invoke_and_track(vm.ShutdownGuest) else: invoke_and_track(vm. PowerOff) elif inputs['operation'] == 'suspend': if not force: invoke_and_track(vm.StandbyGuest) else: invoke_and_track(vm. Suspend) #wait_for_task(task, si) except vmodl.MethodFault, e: print "Caught vmodl fault: %s" % e.msg return 1 except Exception, e: if str(e) == 'Query': return 1 print "Caught exception: %s" % str(e) return 1 # Start program
IOError
dataset/ETHPy150Open rreubenur/vmware-pyvmomi-examples/vm_power_ops.py/main
9,460
def test04(): class Bogus(object): pass m = get_mapper(dom1) try: cls = m[Bogus] assert False, "should have raised a KeyError" except __HOLE__, _: pass
KeyError
dataset/ETHPy150Open haxsaw/actuator/src/tests/utils_tests.py/test04
9,461
def get_item_len(self, data, **kwargs): """ Get the max_item_id parameter :param kwargs: :return: """ try: return self._max_item_id or kwargs["max_item_id"] except __HOLE__: return len(set([row["item"] for _, row in data.iterrows()]))
KeyError
dataset/ETHPy150Open grafos-ml/test.fm/src/testfm/okapi/connector.py/BaseOkapiModel.get_item_len
9,462
@click.command() @click.argument('identifier') @environment.pass_env def cli(env, identifier): """Edit firewall rules.""" mgr = SoftLayer.FirewallManager(env.client) firewall_type, firewall_id = firewall.parse_id(identifier) if firewall_type == 'vlan': orig_rules = mgr.get_dedicated_fwl_rules(firewall_id) else: orig_rules = mgr.get_standard_fwl_rules(firewall_id) # open an editor for the user to enter their rules edited_rules = open_editor(rules=orig_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the rules. " "Continue?"): while True: try: rules = parse_rules(edited_rules) if firewall_type == 'vlan': rules = mgr.edit_dedicated_fwl_rules(firewall_id, rules) else: rules = mgr.edit_standard_fwl_rules(firewall_id, rules) break except (SoftLayer.SoftLayerError, __HOLE__) as error: env.out("Unexpected error({%s})" % (error)) if formatting.confirm("Would you like to continue editing " "the rules. Continue?"): edited_rules = open_editor(content=edited_rules) env.out(edited_rules) if formatting.confirm("Would you like to submit the " "rules. Continue?"): continue else: raise exceptions.CLIAbort('Aborted.') else: raise exceptions.CLIAbort('Aborted.') env.fout('Firewall updated!') else: raise exceptions.CLIAbort('Aborted.')
ValueError
dataset/ETHPy150Open softlayer/softlayer-python/SoftLayer/CLI/firewall/edit.py/cli
9,463
def check_exists(fips_dir=None) : """test if git is in the path :returns: True if git is in the path """ try : subprocess.check_output(['git', '--version']) return True except (__HOLE__, subprocess.CalledProcessError) : return False #-------------------------------------------------------------------------------
OSError
dataset/ETHPy150Open floooh/fips/mod/tools/git.py/check_exists
9,464
def main(): global endflag if len(sys.argv)<>3: usage() sys.exit() else: port1 = int(sys.argv[1]) port2 = int(sys.argv[2]) controlThreads = [] try: socketServer = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socketServer.bind(('',port1)) socketServer.listen(20) socketClient = socket.socket(socket.AF_INET,socket.SOCK_STREAM) socketClient.bind(('',port2)) socketClient.listen(20) clientNum = 0 #the number of client connection. while True: currentLink = clientNum +1 print "[Link %s] Listening on port %s,waiting for server connect..." % (currentLink,port1) serverConn,serverAddr = socketServer.accept() print "[Link %s] Server %s connect! " % (currentLink,serverAddr) while True: print "[Link %s] Listening on port %s,waiting for client connect..." % (currentLink,port2) client_Conn,client_Addr = socketClient.accept() print "[Link %s] Get a client connection from %s !" % (currentLink,client_Addr) serverConn.send('__newLink__') # send current client info,to create a new thread in reprocks_client to connect with current reprocks_server. temp = control(serverConn,client_Conn,serverAddr,client_Addr,clientNum) temp.setDaemon(True) controlThreads.append(temp) controlThreads[clientNum].start() clientNum += 1 break except __HOLE__: print "Catch ctrl+c pressed,program will exit." for m in endflag: m = True
KeyboardInterrupt
dataset/ETHPy150Open RicterZ/reprocks/server/reprocks_server.py/main
9,465
def find_first_remote_branch(remotes, branch_name): """Find the remote branch matching the name of the given branch or raise InvalidGitRepositoryError""" for remote in remotes: try: return remote.refs[branch_name] except __HOLE__: continue # END exception handling # END for remote raise InvalidGitRepositoryError("Didn't find remote branch '%r' in any of the given remotes" % branch_name) #} END utilities #{ Classes
IndexError
dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/submodule/util.py/find_first_remote_branch
9,466
@staticmethod def _start_key(expr): """Return start (if possible) else S.Infinity. adapted from Set._infimum_key """ try: start = expr.start except (NotImplementedError, AttributeError, __HOLE__): start = S.Infinity return start
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/series/sequences.py/SeqBase._start_key
9,467
def request(host, port, child_num, con_num, bytes): # spawn child_num children processes for cnum in range(child_num): pid = os.fork() if pid == 0: # child for i in range(con_num): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.sendall(str(bytes)) data = sock.recv(bytes) if len(data) != bytes: raise Exception('Server returned only %d bytes' % len(data)) sock.close() # TIME_WAIT state on the client print 'Child %d is done' % cnum os._exit(0) # wait for all children to finish while True: try: pid, status = os.wait() except __HOLE__ as e: if e.errno == errno.ECHILD: break else: raise if pid == 0: break
OSError
dataset/ETHPy150Open rspivak/csdesign/client.py/request
9,468
def __init__(self, data_stream, minimum_shape, resample='nearest', **kwargs): self.minimum_shape = minimum_shape try: self.resample = getattr(Image, resample.upper()) except __HOLE__: raise ValueError("unknown resampling filter '{}'".format(resample)) kwargs.setdefault('produces_examples', data_stream.produces_examples) kwargs.setdefault('axis_labels', data_stream.axis_labels) super(MinimumImageDimensions, self).__init__(data_stream, **kwargs)
AttributeError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/fuel/fuel/transformers/image.py/MinimumImageDimensions.__init__
9,469
def has_valid_birthday(self, value): """ This function would grab the birthdate from the ID card number and test whether it is a valid date. """ from datetime import datetime if len(value) == 15: # 1st generation ID card time_string = value[6:12] format_string = "%y%m%d" else: # 2nd generation ID card time_string = value[6:14] format_string = "%Y%m%d" try: datetime.strptime(time_string, format_string) return True except __HOLE__: # invalid date return False
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/localflavor/cn/forms.py/CNIDCardField.has_valid_birthday
9,470
def _word_tokenizer_re(self): """Compiles and returns a regular expression for word tokenization""" try: return self._re_word_tokenizer except __HOLE__: self._re_word_tokenizer = re.compile( self._word_tokenize_fmt % { 'NonWord': self._re_non_word_chars, 'MultiChar': self._re_multi_char_punct, 'WordStart': self._re_word_start, }, re.UNICODE | re.VERBOSE ) return self._re_word_tokenizer
AttributeError
dataset/ETHPy150Open reefeed/wanish/wanish/tokenizers.py/PunktLanguageVars._word_tokenizer_re
9,471
def subscribe(self): """Subscribe self.handlers to signals.""" for sig, func in self.handlers.items(): try: self.set_handler(sig, func) except __HOLE__: pass
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/SignalHandler.subscribe
9,472
def unsubscribe(self): """Unsubscribe self.handlers from signals.""" for signum, handler in self._previous_handlers.items(): signame = self.signals[signum] if handler is None: self.bus.log("Restoring %s handler to SIG_DFL." % signame) handler = _signal.SIG_DFL else: self.bus.log("Restoring %s handler %r." % (signame, handler)) try: our_handler = _signal.signal(signum, handler) if our_handler is None: self.bus.log("Restored old %s handler %r, but our " "handler was not registered." % (signame, handler), level=30) except __HOLE__: self.bus.log("Unable to restore %s handler %r." % (signame, handler), level=40, traceback=True)
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/SignalHandler.unsubscribe
9,473
def set_handler(self, signal, listener=None): """Subscribe a handler for the given signal (number or name). If the optional 'listener' argument is provided, it will be subscribed as a listener for the given signal's channel. If the given signal name or number is not available on the current platform, ValueError is raised. """ if isinstance(signal, basestring): signum = getattr(_signal, signal, None) if signum is None: raise ValueError("No such signal: %r" % signal) signame = signal else: try: signame = self.signals[signal] except __HOLE__: raise ValueError("No such signal: %r" % signal) signum = signal prev = _signal.signal(signum, self._handle_signal) self._previous_handlers[signum] = prev if listener is not None: self.bus.log("Listening for %s." % signame) self.bus.subscribe(signame, listener)
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/SignalHandler.set_handler
9,474
def _set_umask(self, val): if val is not None: try: os.umask except __HOLE__: self.bus.log("umask function not available; ignoring umask.", level=30) val = None self._umask = val
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/DropPrivileges._set_umask
9,475
def start(self): if self.finalized: self.bus.log('Already deamonized.') # forking has issues with threads: # http://www.opengroup.org/onlinepubs/000095399/functions/fork.html # "The general problem with making fork() work in a multi-threaded # world is what to do with all of the threads..." # So we check for active threads: if threading.activeCount() != 1: self.bus.log('There are %r active threads. ' 'Daemonizing now may cause strange failures.' % threading.enumerate(), level=30) # See http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 # (or http://www.faqs.org/faqs/unix-faq/programmer/faq/ section 1.7) # and http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 # Finish up with the current stdout/stderr sys.stdout.flush() sys.stderr.flush() # Do first fork. try: pid = os.fork() if pid == 0: # This is the child process. Continue. pass else: # This is the first parent. Exit, now that we've forked. self.bus.log('Forking once.') os._exit(0) except OSError: # Python raises OSError rather than returning negative numbers. exc = sys.exc_info()[1] sys.exit("%s: fork #1 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) os.setsid() # Do second fork try: pid = os.fork() if pid > 0: self.bus.log('Forking twice.') os._exit(0) # Exit second parent except __HOLE__: exc = sys.exc_info()[1] sys.exit("%s: fork #2 failed: (%d) %s\n" % (sys.argv[0], exc.errno, exc.strerror)) os.chdir("/") os.umask(0) si = open(self.stdin, "r") so = open(self.stdout, "a+") se = open(self.stderr, "a+") # os.dup2(fd, fd2) will close fd2 if necessary, # so we don't explicitly close stdin/out/err. # See http://docs.python.org/lib/os-fd-ops.html os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) self.bus.log('Daemonized to PID: %s' % os.getpid()) self.finalized = True
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/Daemonizer.start
9,476
def exit(self): try: os.remove(self.pidfile) self.bus.log('PID file removed: %r.' % self.pidfile) except (__HOLE__, SystemExit): raise except: pass
KeyboardInterrupt
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/PIDFile.exit
9,477
def run(self): """Reload the process if registered files have been modified.""" for filename in self.sysfiles() | self.files: if filename: if filename.endswith('.pyc'): filename = filename[:-1] oldtime = self.mtimes.get(filename, 0) if oldtime is None: # Module with no .py file. Skip it. continue try: mtime = os.stat(filename).st_mtime except __HOLE__: # Either a module with no .py file, or it's been deleted. mtime = None if filename not in self.mtimes: # If a module has no .py file, this will be None. self.mtimes[filename] = mtime else: if mtime is None or mtime > oldtime: # The file has been deleted or modified. self.bus.log("Restarting because %s changed." % filename) self.thread.cancel() self.bus.log("Stopped thread %r." % self.thread.getName()) self.bus.restart() return
OSError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/process/plugins.py/Autoreloader.run
9,478
def _iter_lines(proc, decode, linesize): try: from selectors import DefaultSelector, EVENT_READ except __HOLE__: # Pre Python 3.4 implementation from select import select def selector(): while True: rlist, _, _ = select([proc.stdout, proc.stderr], [], []) for stream in rlist: yield (stream is proc.stderr), decode(stream.readline(linesize)) else: # Python 3.4 implementation def selector(): sel = DefaultSelector() sel.register(proc.stdout, EVENT_READ, 0) sel.register(proc.stderr, EVENT_READ, 1) while True: for key, mask in sel.select(): yield key.data, decode(key.fileobj.readline(linesize)) for ret in selector(): yield ret if proc.poll() is not None: break for line in proc.stdout: yield 0, decode(line) for line in proc.stderr: yield 1, decode(line) #=================================================================================================== # Exceptions #===================================================================================================
ImportError
dataset/ETHPy150Open tomerfiliba/plumbum/plumbum/commands/processes.py/_iter_lines
9,479
def load_app(self, app_name, can_postpone=False): """ Loads the app with the provided fully qualified name, and returns the model module. """ self.handled[app_name] = None self.nesting_level += 1 app_module = import_module(app_name) try: models = import_module('.models', app_name) except __HOLE__: self.nesting_level -= 1 # If the app doesn't have a models module, we can just ignore the # ImportError and return no models for it. if not module_has_submodule(app_module, 'models'): return None # But if the app does have a models module, we need to figure out # whether to suppress or propagate the error. If can_postpone is # True then it may be that the package is still being imported by # Python and the models module isn't available yet. So we add the # app to the postponed list and we'll try it again after all the # recursion has finished (in populate). If can_postpone is False # then it's time to raise the ImportError. else: if can_postpone: self.postponed.append(app_name) return None else: raise self.nesting_level -= 1 if models not in self.app_store: self.app_store[models] = len(self.app_store) self.app_labels[self._label_for(models)] = models return models
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/db/models/loading.py/AppCache.load_app
9,480
def get_models(self, app_mod=None, include_auto_created=False, include_deferred=False, only_installed=True): """ Given a module containing models, returns a list of the models. Otherwise returns a list of all installed models. By default, auto-created models (i.e., m2m models without an explicit intermediate table) are not included. However, if you specify include_auto_created=True, they will be. By default, models created to satisfy deferred attribute queries are *not* included in the list of models. However, if you specify include_deferred, they will be. """ cache_key = (app_mod, include_auto_created, include_deferred, only_installed) try: return self._get_models_cache[cache_key] except __HOLE__: pass self._populate() if app_mod: if app_mod in self.app_store: app_list = [self.app_models.get(self._label_for(app_mod), SortedDict())] else: app_list = [] else: if only_installed: app_list = [self.app_models.get(app_label, SortedDict()) for app_label in self.app_labels.iterkeys()] else: app_list = self.app_models.itervalues() model_list = [] for app in app_list: model_list.extend( model for model in app.values() if ((not model._deferred or include_deferred) and (not model._meta.auto_created or include_auto_created)) ) self._get_models_cache[cache_key] = model_list return model_list
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/db/models/loading.py/AppCache.get_models
9,481
def _safe_remove(filepath): if not filepath: return try: os.remove(filepath) except __HOLE__: pass
OSError
dataset/ETHPy150Open openstack/cloudbase-init/cloudbaseinit/tests/plugins/common/test_userdatautils.py/_safe_remove
9,482
def build_pipewelder(conn, config): """ Return a Pipewelder object defined by *config*. """ try: pw = Pipewelder(conn, config['template']) except __HOLE__ as e: print(e) return 1 for d in config['dirs']: p = pw.add_pipeline(d) for k, v in config["values"].items(): p.values[k] = v return pw
IOError
dataset/ETHPy150Open SimpleFinance/pipewelder/pipewelder/cli.py/build_pipewelder
9,483
def visit_Assign(self, node): """Looking for 'p1 = self.config.get("param1", "default1")' This is the canonical form of getting test case parameters in a test implementation. This ends up with an AST looking like: Assign(targets=[Name(id='p1', ctx=Store())], value=Call(func=Attribute(value=Attribute(value=Name(id='self', ctx=Load()), attr='config', ctx=Load()), attr='get', ctx=Load()), args=[Str(s='param1'), Str(s='default1')], keywords=[], starargs=None, kwargs=None)) """ if isinstance(node.value, ast.Call) and isinstance(node.value.func, ast.Attribute): try: if (node.value.func.value.value.id == "self" and node.value.func.value.attr == "config" and node.value.func.attr == "get"): lhs = node.targets[0].id param = node.value.args[0].s default = node.value.args[1].s if self._currentclass is not None: self._classes.setdefault(self._currentclass, []).append( (lhs, param, default) ) else: raise ValueError("Didn't see class before config get") except __HOLE__: return
AttributeError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/testinspector.py/TestmoduleVisitor.visit_Assign
9,484
def http_request(self, method, path, body=None, response_formatter=None, error_formatter=None, **params): try: # Check if it's ok to submit if not self._should_submit(): raise HttpBackoff("Too many timeouts. Won't try again for {1} seconds.".format(*self._backoff_status())) # Construct the url if self.api_key: params['api_key'] = self.api_key if self.application_key: params['application_key'] = self.application_key url = "/api/%s/%s?%s" % (self.api_version, path.lstrip('/'), urlencode(params)) try: conn = self.http_conn_cls(self.api_host, timeout=self.timeout) except __HOLE__: # timeout= parameter is only supported 2.6+ conn = self.http_conn_cls(self.api_host) # Construct the body, if necessary headers = {} if isinstance(body, dict): body = json.dumps(body) headers['Content-Type'] = 'application/json' try: start_time = time.time() # Make the request try: conn.request(method, url, body, headers) except timeout_exceptions: # Keep a count of the timeouts to know when to back off self._timeout_counter += 1 raise HttpTimeout('%s %s timed out after %d seconds.' % (method, url, self.timeout)) except socket.error as e: # Translate the low level socket error into a more # descriptive one raise ClientError("Could not request %s %s%s: %s" % (method, self.api_host, url, e)) # If the request succeeded, reset the timeout counter self._timeout_counter = 0 # Parse the response as json response = conn.getresponse() duration = round((time.time() - start_time) * 1000., 4) log.info("%s %s %s (%sms)" % (response.status, method, url, duration)) response_str = response.read() if response_str: try: if is_p3k(): response_obj = json.loads(response_str.decode('utf-8')) else: response_obj = json.loads(response_str) except ValueError: raise ValueError('Invalid JSON response: {0}'.format(response_str)) if response_obj and 'errors' in response_obj: raise ApiError(response_obj) else: response_obj = None if response_obj is None and self.json_responses: response_obj = {} if self.json_responses or response_formatter is None: return response_obj else: return response_formatter(response_obj) finally: conn.close() except ClientError as e: if self.swallow: log.error(str(e)) if self.json_responses or error_formatter is None: return {'errors': e.args[0]} else: return error_formatter({'errors': e.args[0]}) else: raise except ApiError as e: if self.swallow: for error in e.args[0]['errors']: log.error(str(error)) if self.json_responses or error_formatter is None: return e.args[0] else: return error_formatter(e.args[0]) else: raise
TypeError
dataset/ETHPy150Open DataDog/dogapi/src/dogapi/http/base.py/BaseDatadog.http_request
9,485
def _get_memory(string, offset): try: return memoryview(string)[offset:] except __HOLE__: return buffer(string, offset)
TypeError
dataset/ETHPy150Open benoitc/flower/flower/net/sock.py/_get_memory
9,486
def read(self): if self.closing: return "" while True: try: retval = self.queue.popleft() if self.cr.balance < 0: self.cr.send(retval) if isinstance(retval, bomb): retval.raise_() return retval except __HOLE__: pass msg = None buf = bytearray(DEFAULT_BUFFER_SIZE) try: recvd = recv_into(self.client, buf) msg = bytes(buf[0:recvd]) except socket.error: ex = sys.exc_info()[1] if ex.args[0] == EBADF: msg = "" self.closing = True if ex.args[0] != EWOULDBLOCK or self.timeout == 0.0: msg = bomb(ex, sys.exc_info()[2]) self.closing = True exc_clear() if msg is None: res = self._watch_read() if res is not None: self.queue.append(res) else: self.queue.append(msg)
IndexError
dataset/ETHPy150Open benoitc/flower/flower/net/sock.py/SockConn.read
9,487
def __init__(self, addr, *args, **kwargs): fd = kwargs.get('fd') if fd is None: try: os.remove(addr) except __HOLE__: pass sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if fd is None: sock.bind(addr) sock.setblocking(0) self.sock = sock self.fd = fd self.addr = addr self.backlog = kwargs.get('backlog', 128) self.timeout = socket.getdefaulttimeout() # start to listen self.sock.listen(self.backlog)
OSError
dataset/ETHPy150Open benoitc/flower/flower/net/sock.py/PipeSockListen.__init__
9,488
def interpfx(time,fx,time_pre): opens = np.zeros(len(time)) f = sp.interpolate.interp1d(time_pre, fx) for t in range(len(time)): try: opens[t] = f(time[t]) except __HOLE__: if time[t] < min(time_pre): opens[t] = f(min(time_pre)) elif time[t] > max(time_pre): opens[t] = f(max(time_pre)) else: raise ValueError('Interpolation error') return opens # User input
ValueError
dataset/ETHPy150Open srcole/fxml/scraper/format_fxdata.py/interpfx
9,489
def process_sd(self, dn, obj): sd_attr = "nTSecurityDescriptor" sd_val = obj[sd_attr] sd = ndr_unpack(security.descriptor, str(sd_val)) is_deleted = 'isDeleted' in obj and obj['isDeleted'][0].upper() == 'TRUE' if is_deleted: # we don't fix deleted objects return (sd, None) sd_clean = security.descriptor() sd_clean.owner_sid = sd.owner_sid sd_clean.group_sid = sd.group_sid sd_clean.type = sd.type sd_clean.revision = sd.revision broken = False last_inherited_type = None aces = [] if sd.sacl is not None: aces = sd.sacl.aces for i in range(0, len(aces)): ace = aces[i] if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE: sd_clean.sacl_add(ace) continue t = self.ace_get_effective_inherited_type(ace) if t is None: continue if last_inherited_type is not None: if t != last_inherited_type: # if it inherited from more than # one type it's very likely to be broken # # If not the recalculation will calculate # the same result. broken = True continue last_inherited_type = t aces = [] if sd.dacl is not None: aces = sd.dacl.aces for i in range(0, len(aces)): ace = aces[i] if not ace.flags & security.SEC_ACE_FLAG_INHERITED_ACE: sd_clean.dacl_add(ace) continue t = self.ace_get_effective_inherited_type(ace) if t is None: continue if last_inherited_type is not None: if t != last_inherited_type: # if it inherited from more than # one type it's very likely to be broken # # If not the recalculation will calculate # the same result. broken = True continue last_inherited_type = t if broken: return (sd_clean, sd) if last_inherited_type is None: # ok return (sd, None) cls = None try: cls = obj["objectClass"][-1] except __HOLE__, e: pass if cls is None: res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE, attrs=["isDeleted", "objectClass"], controls=["show_recycled:1"]) o = res[0] is_deleted = 'isDeleted' in o and o['isDeleted'][0].upper() == 'TRUE' if is_deleted: # we don't fix deleted objects return (sd, None) cls = o["objectClass"][-1] t = self.lookup_class_schemaIDGUID(cls) if t != last_inherited_type: # broken return (sd_clean, sd) # ok return (sd, None)
KeyError
dataset/ETHPy150Open byt3bl33d3r/pth-toolkit/lib/python2.7/site-packages/samba/dbchecker.py/dbcheck.process_sd
9,490
@util.use_cassette def test_delete(vcr_live_sleep): user = User() their_profile = user.quickmatch() message_info = their_profile.message('text') assert message_info.thread_id != None thread_id = user.outbox[0].id user.outbox[0].delete() vcr_live_sleep(2) user.outbox() try: assert user.outbox[0].id != thread_id except __HOLE__: pass
IndexError
dataset/ETHPy150Open IvanMalison/okcupyd/tests/messaging_test.py/test_delete
9,491
def Decompress(self, compressed_data): """Decompresses the compressed data. Args: compressed_data: a byte string containing the compressed data. Returns: A tuple containing a byte string of the uncompressed data and the remaining compressed data. Raises: BackEndError: if the BZIP2 compressed stream cannot be decompressed. """ try: uncompressed_data = self._bz2_decompressor.decompress(compressed_data) remaining_compressed_data = getattr( self._bz2_decompressor, u'unused_data', b'') except (EOFError, __HOLE__) as exception: raise errors.BackEndError(( u'Unable to decompress BZIP2 compressed stream with error: ' u'{0!s}.').format(exception)) return uncompressed_data, remaining_compressed_data
IOError
dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/compression/bzip2_decompressor.py/BZIP2Decompressor.Decompress
9,492
def get_cost_fns(self, topic): """Returns a list of tuples containing weights and cost functions to use for weighing hosts """ if topic in self.cost_fns_cache: return self.cost_fns_cache[topic] cost_fns = [] for cost_fn_str in FLAGS.least_cost_scheduler_cost_functions: if '.' in cost_fn_str: short_name = cost_fn_str.split('.')[-1] else: short_name = cost_fn_str cost_fn_str = "%s.%s.%s" % ( __name__, self.__class__.__name__, short_name) if not (short_name.startswith('%s_' % topic) or short_name.startswith('noop')): continue try: # NOTE(sirp): import_class is somewhat misnamed since it can # any callable from a module cost_fn = utils.import_class(cost_fn_str) except exception.ClassNotFound: raise exception.SchedulerCostFunctionNotFound( cost_fn_str=cost_fn_str) try: flag_name = "%s_weight" % cost_fn.__name__ weight = getattr(FLAGS, flag_name) except __HOLE__: raise exception.SchedulerWeightFlagNotFound( flag_name=flag_name) cost_fns.append((weight, cost_fn)) self.cost_fns_cache[topic] = cost_fns return cost_fns
AttributeError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/scheduler/least_cost.py/LeastCostScheduler.get_cost_fns
9,493
def get_summoner_by_id(id_): """ Gets a summoner by ID Args: id_ (int): the ID of the summoner Returns: Summoner: the summoner """ summoner = cassiopeia.core.requests.data_store.get(cassiopeia.type.core.summoner.Summoner, id_, "id") if summoner: return summoner try: summoner = cassiopeia.dto.summonerapi.get_summoners_by_id(id_)[str(id_)] summoner = cassiopeia.type.core.summoner.Summoner(summoner) except __HOLE__: return None cassiopeia.core.requests.data_store.store(summoner, id_) cassiopeia.core.requests.data_store.store(summoner, summoner.name) return summoner
KeyError
dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/summonerapi.py/get_summoner_by_id
9,494
def get_summoner_by_name(name): """ Gets a summoner by name Args: name (str): the name of the summoner Returns: Summoner: the summoner """ summoner = cassiopeia.core.requests.data_store.get(cassiopeia.type.core.summoner.Summoner, name, "name") if summoner: return summoner try: summoner = cassiopeia.dto.summonerapi.get_summoners_by_name(name)[__standardize(name)] summoner = cassiopeia.type.core.summoner.Summoner(summoner) except __HOLE__: return None cassiopeia.core.requests.data_store.store(summoner, name) cassiopeia.core.requests.data_store.store(summoner, summoner.id) return summoner
KeyError
dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/summonerapi.py/get_summoner_by_name
9,495
def get_summoners_by_id(ids): """ Gets a bunch of summoners by ID Args: ids (list<int>): the IDs of the summoners Returns: list<Summoner>: the summoners """ summoners = cassiopeia.core.requests.data_store.get(cassiopeia.type.core.summoner.Summoner, ids, "id") # Find which summoners weren't cached missing = [] loc = [] for i in range(len(ids)): if not summoners[i]: missing.append(ids[i]) loc.append(i) if not missing: return summoners # Make requests to get them new = cassiopeia.core.requests.call_with_ensured_size(cassiopeia.dto.summonerapi.get_summoners_by_id, 40, missing) to_store = [] for i in range(len(missing)): try: summoner = cassiopeia.type.core.summoner.Summoner(new[str(missing[i])]) to_store.append(summoner) except __HOLE__: summoner = None summoners[loc[i]] = summoner cassiopeia.core.requests.data_store.store(to_store, [summoner.id for summoner in to_store]) cassiopeia.core.requests.data_store.store(to_store, [summoner.name for summoner in to_store]) return summoners
KeyError
dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/summonerapi.py/get_summoners_by_id
9,496
def get_summoners_by_name(names): """ Gets a bunch of summoners by name Args: names (list<str>): the names of the summoners Returns: list<Summoner>: the summoners """ summoners = cassiopeia.core.requests.data_store.get(cassiopeia.type.core.summoner.Summoner, names, "name") # Find which summoners weren't cached missing = [] loc = [] for i in range(len(names)): if not summoners[i]: missing.append(names[i]) loc.append(i) if not missing: return summoners # Make requests to get them new = cassiopeia.core.requests.call_with_ensured_size(cassiopeia.dto.summonerapi.get_summoners_by_name, 40, missing) to_store = [] for i in range(len(missing)): try: summoner = cassiopeia.type.core.summoner.Summoner(new[__standardize(missing[i])]) to_store.append(summoner) except __HOLE__: summoner = None summoners[loc[i]] = summoner cassiopeia.core.requests.data_store.store(to_store, [summoner.id for summoner in to_store]) cassiopeia.core.requests.data_store.store(to_store, [summoner.name for summoner in to_store]) return summoners
KeyError
dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/summonerapi.py/get_summoners_by_name
9,497
def is_connection(graph, src, dest): try: return 'conn' in graph.edge[src][dest] except __HOLE__: return False
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/depgraph.py/is_connection
9,498
def var_edge_iter(self, source, reverse=False): """Iterater over edges from the given source to the nearest basevars. """ # Adapted from the networkx bfs_edges function if reverse and isinstance(self, nx.DiGraph): neighbors = self.predecessors_iter else: neighbors = self.neighbors_iter visited = set() queue = deque([(source, neighbors(source))]) while queue: parent, children = queue[0] try: child = next(children) if (parent,child) not in visited: visited.add((parent,child)) if reverse: yield child, parent else: yield parent, child if not is_basevar_node(self, child) and not is_comp_node(self, child): queue.append((child, neighbors(child))) except __HOLE__: queue.popleft()
StopIteration
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/depgraph.py/DependencyGraph.var_edge_iter
9,499
def _dfs_connections(G, source, visited, reverse=False): """Produce connections in a depth-first-search starting at source.""" # Slightly modified version of the networkx function dfs_edges if reverse: neighbors = G.predecessors_iter else: neighbors = G.successors_iter stack = [] if source in G: stack.append((source, neighbors(source))) while stack: parent, children = stack[-1] try: child = next(children) if reverse: tup = (child, parent) else: tup = (parent, child) if tup not in visited: yield tup visited.add(tup) stack.append((child, neighbors(child))) except __HOLE__: stack.pop()
StopIteration
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/depgraph.py/_dfs_connections