Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
3,200
def is_ip(self, value): try: ip(value) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open noirbizarre/flask-restplus/flask_restplus/inputs.py/email.is_ip
3,201
def _parse_interval(value): ''' Do some nasty try/except voodoo to get some sort of datetime object(s) out of the string. ''' try: return sorted(aniso8601.parse_interval(value)) except ValueError: try: return aniso8601.parse_datetime(value), None except __HOLE__: return aniso8601.parse_date(value), None
ValueError
dataset/ETHPy150Open noirbizarre/flask-restplus/flask_restplus/inputs.py/_parse_interval
3,202
def iso8601interval(value, argument='argument'): ''' Parses ISO 8601-formatted datetime intervals into tuples of datetimes. Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior: - Intervals are defined as inclusive start, exclusive end - Single datetimes are translated into the interval spanning the largest resolution not specified in the input value, up to the day. - The smallest accepted resolution is 1 second. - All timezones are accepted as values; returned datetimes are localized to UTC. Naive inputs and date inputs will are assumed UTC. Examples:: "2013-01-01" -> datetime(2013, 1, 1), datetime(2013, 1, 2) "2013-01-01T12" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 13) "2013-01-01/2013-02-28" -> datetime(2013, 1, 1), datetime(2013, 2, 28) "2013-01-01/P3D" -> datetime(2013, 1, 1), datetime(2013, 1, 4) "2013-01-01T12:00/PT30M" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 12, 30) "2013-01-01T06:00/2013-01-01T12:00" -> datetime(2013, 1, 1, 6), datetime(2013, 1, 1, 12) :param str value: The ISO8601 date time as a string :return: Two UTC datetimes, the start and the end of the specified interval :rtype: A tuple (datetime, datetime) :raises ValueError: if the interval is invalid. ''' try: start, end = _parse_interval(value) if end is None: end = _expand_datetime(start, value) start, end = _normalize_interval(start, end, value) except __HOLE__: msg = 'Invalid {arg}: {value}. {arg} must be a valid ISO8601 date/time interval.' raise ValueError(msg.format(arg=argument, value=value),) return start, end
ValueError
dataset/ETHPy150Open noirbizarre/flask-restplus/flask_restplus/inputs.py/iso8601interval
3,203
def _get_integer(value): try: return int(value) except (__HOLE__, ValueError): raise ValueError('{0} is not a valid integer'.format(value))
TypeError
dataset/ETHPy150Open noirbizarre/flask-restplus/flask_restplus/inputs.py/_get_integer
3,204
def datetime_from_iso8601(value): ''' Turns an ISO8601 formatted date into a datetime object. Example:: inputs.datetime_from_iso8601("2012-01-01T23:30:00+02:00") :param str value: The ISO8601-complying string to transform :return: A datetime :rtype: datetime :raises ValueError: if value is an invalid date literal ''' try: try: return aniso8601.parse_datetime(value) except __HOLE__: date = aniso8601.parse_date(value) return datetime(date.year, date.month, date.day) except: raise ValueError('Invalid date literal "{0}"'.format(value))
ValueError
dataset/ETHPy150Open noirbizarre/flask-restplus/flask_restplus/inputs.py/datetime_from_iso8601
3,205
def getbuf(): # This was in the original. Avoid non-repeatable sources. # Left here (unused) in case something wants to be done with it. import imp try: t = imp.find_module('test_zlib') file = t[0] except __HOLE__: file = open(__file__) buf = file.read() * 8 file.close() return buf
ImportError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/test/test_zlib.py/getbuf
3,206
def test_odd_flush(self): # Test for odd flushing bugs noted in 2.0, and hopefully fixed in 2.1 import random if hasattr(zlib, 'Z_SYNC_FLUSH'): # Testing on 17K of "random" data # Create compressor and decompressor objects co = zlib.compressobj(zlib.Z_BEST_COMPRESSION) dco = zlib.decompressobj() # Try 17K of data # generate random data stream try: # In 2.3 and later, WichmannHill is the RNG of the bug report gen = random.WichmannHill() except __HOLE__: try: # 2.2 called it Random gen = random.Random() except AttributeError: # others might simply have a single RNG gen = random gen.seed(1) data = genblock(1, 17 * 1024, generator=gen) # compress, sync-flush, and decompress first = co.compress(data) second = co.flush(zlib.Z_SYNC_FLUSH) expanded = dco.decompress(first + second) # if decompressed data is different from the input data, choke. self.assertEqual(expanded, data, "17K random source doesn't match")
AttributeError
dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/test/test_zlib.py/CompressObjectTestCase.test_odd_flush
3,207
def tearDown(self): """ Called after each test in this class. """ self.model.pre_delete() self.model = None os.chdir(self.startdir) SimulationRoot.chroot(self.startdir) if not os.environ.get('OPENMDAO_KEEPDIRS', False): try: shutil.rmtree(self.tempdir) except __HOLE__: pass
OSError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_filevar.py/TestCase.tearDown
3,208
def test_src_failure(self): logging.debug('') logging.debug('test_src_failure') # Turn off source write, verify error message. self.model.source.write_files = False try: self.model.run() except __HOLE__ as exc: if 'source.txt' not in str(exc) and 'source.bin' not in str(exc): self.fail("Wrong message '%s'" % exc) else: self.fail('IOError expected')
RuntimeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_filevar.py/TestCase.test_src_failure
3,209
def test_illegal_src(self): logging.debug('') logging.debug('test_illegal_src') # Set illegal path (during execution of sink), verify error message. self.model.sink.bogus_path = '/illegal' msg = "middle.passthrough (1-middle.1-passthrough): Illegal path '/illegal'," \ " not a descendant of" try: self.model.run() except __HOLE__ as exc: print exc self.assertTrue(msg in str(exc)) else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_filevar.py/TestCase.test_illegal_src
3,210
def test_legal_types(self): logging.debug('') logging.debug('test_legal_types') # Set mismatched type and verify error message. self.model.source.text_file.content_type = 'invalid' msg = ": cannot set 'middle.text_in' from 'source.text_file':" \ " : Content type 'invalid' not one of ['xyzzy', 'txt']" try: self.model.run() except ValueError as exc: print exc self.assertTrue(msg in str(exc)) else: self.fail('ValueError expected') # Set null type and verify error message. self.model.source.text_file.content_type = '' msg = ": cannot set 'middle.text_in' from 'source.text_file':" \ " : Content type '' not one of ['xyzzy', 'txt']" try: self.model.run() except __HOLE__ as exc: self.assertTrue(msg in str(exc)) else: self.fail('ValueError expected')
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/test/test_filevar.py/TestCase.test_legal_types
3,211
def __init__(self, context, socket_type): super(Socket, self).__init__(context, socket_type) on_state_changed_fd = self.getsockopt(_zmq.FD) # NOTE: pyzmq 13.0.0 messed up with setattr (they turned it into a # non-op) and you can't assign attributes normally anymore, hence the # tricks with self.__dict__ here self.__dict__["_readable"] = gevent.event.Event() self.__dict__["_writable"] = gevent.event.Event() try: # gevent>=1.0 self.__dict__["_state_event"] = gevent.hub.get_hub().loop.io( on_state_changed_fd, gevent.core.READ) self._state_event.start(self._on_state_changed) except __HOLE__: # gevent<1.0 self.__dict__["_state_event"] = \ gevent.core.read_event(on_state_changed_fd, self._on_state_changed, persist=True)
AttributeError
dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/gevent_zmq.py/Socket.__init__
3,212
def close(self): if not self.closed and getattr(self, '_state_event', None): try: # gevent>=1.0 self._state_event.stop() except __HOLE__: # gevent<1.0 self._state_event.cancel() super(Socket, self).close()
AttributeError
dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/gevent_zmq.py/Socket.close
3,213
def test_import(self): """ Can import confire """ try: import confire except __HOLE__: self.fail("Unable to import the confire module!")
ImportError
dataset/ETHPy150Open bbengfort/confire/tests/__init__.py/InitializationTest.test_import
3,214
def check_for_result(self, language, translation, result, name): if not result: try: translation = self.translations.get(language_code=language) except __HOLE__: pass else: # pragma: nocover result = getattr(translation, name, '') return translation, result
ObjectDoesNotExist
dataset/ETHPy150Open bitmazk/django-libs/django_libs/models_mixins.py/TranslationModelMixin.check_for_result
3,215
def stream_write(self, path, fp): # Minimum size of upload part size on S3 is 5MB buffer_size = 5 * 1024 * 1024 if self.buffer_size > buffer_size: buffer_size = self.buffer_size path = self._init_path(path) mp = self._boto_bucket.initiate_multipart_upload( path, encrypt_key=(self._config.s3_encrypt is True)) num_part = 1 try: while True: buf = fp.read(buffer_size) if not buf: break io = compat.StringIO(buf) mp.upload_part_from_file(io, num_part) num_part += 1 io.close() except __HOLE__ as e: raise e mp.complete_upload()
IOError
dataset/ETHPy150Open docker/docker-registry/docker_registry/drivers/s3.py/Storage.stream_write
3,216
def process_index(self,url,page): """Process the contents of a PyPI page""" def scan(link): # Process a URL to see if it's for a package page if link.startswith(self.index_url): parts = map( urllib2.unquote, link[len(self.index_url):].split('/') ) if len(parts)==2 and '#' not in parts[1]: # it's a package page, sanitize and index it pkg = safe_name(parts[0]) ver = safe_version(parts[1]) self.package_pages.setdefault(pkg.lower(),{})[link] = True return to_filename(pkg), to_filename(ver) return None, None # process an index page into the package-page index for match in HREF.finditer(page): try: scan( urlparse.urljoin(url, htmldecode(match.group(1))) ) except __HOLE__: pass pkg, ver = scan(url) # ensure this page is in the page index if pkg: # process individual package page for new_url in find_external_links(url, page): # Process the found URL base, frag = egg_info_for_url(new_url) if base.endswith('.py') and not frag: if ver: new_url+='#egg=%s-%s' % (pkg,ver) else: self.need_version_info(url) self.scan_url(new_url) return PYPI_MD5.sub( lambda m: '<a href="%s#md5=%s">%s</a>' % m.group(1,3,2), page ) else: return "" # no sense double-scanning non-package pages
ValueError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/package_index.py/PackageIndex.process_index
3,217
def download(self, spec, tmpdir): """Locate and/or download `spec` to `tmpdir`, returning a local path `spec` may be a ``Requirement`` object, or a string containing a URL, an existing local filename, or a project/version requirement spec (i.e. the string form of a ``Requirement`` object). If it is the URL of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is automatically created alongside the downloaded file. If `spec` is a ``Requirement`` object or a string containing a project/version requirement spec, this method returns the location of a matching distribution (possibly after downloading it to `tmpdir`). If `spec` is a locally existing file or directory name, it is simply returned unchanged. If `spec` is a URL, it is downloaded to a subpath of `tmpdir`, and the local filename is returned. Various errors may be raised if a problem occurs during downloading. """ if not isinstance(spec,Requirement): scheme = URL_SCHEME(spec) if scheme: # It's a url, download it to tmpdir found = self._download_url(scheme.group(1), spec, tmpdir) base, fragment = egg_info_for_url(spec) if base.endswith('.py'): found = self.gen_setup(found,fragment,tmpdir) return found elif os.path.exists(spec): # Existing file or directory, just return it return spec else: try: spec = Requirement.parse(spec) except __HOLE__: raise DistutilsError( "Not a URL, existing file, or requirement spec: %r" % (spec,) ) return getattr(self.fetch_distribution(spec, tmpdir),'location',None)
ValueError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/package_index.py/PackageIndex.download
3,218
def open_url(self, url, warning=None): if url.startswith('file:'): return local_open(url) try: return open_with_auth(url) except (__HOLE__, httplib.InvalidURL), v: msg = ' '.join([str(arg) for arg in v.args]) if warning: self.warn(warning, msg) else: raise DistutilsError('%s %s' % (url, msg)) except urllib2.HTTPError, v: return v except urllib2.URLError, v: if warning: self.warn(warning, v.reason) else: raise DistutilsError("Download error for %s: %s" % (url, v.reason)) except httplib.BadStatusLine, v: if warning: self.warn(warning, v.line) else: raise DistutilsError('%s returned a bad status line. ' 'The server might be down, %s' % \ (url, v.line)) except httplib.HTTPException, v: if warning: self.warn(warning, v) else: raise DistutilsError("Download error for %s: %s" % (url, v))
ValueError
dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/package_index.py/PackageIndex.open_url
3,219
def delete(self, *args, **kwds): # so we have something to give the observer purge = kwds.get('purge', False) if purge: del kwds['purge'] try: purge = purge or observer_disabled except __HOLE__: pass if (purge): super(User, self).delete(*args, **kwds) else: if (not self.write_protect): self.deleted = True self.enacted = None self.save(update_fields=['enacted', 'deleted'])
NameError
dataset/ETHPy150Open open-cloud/xos/xos/core/models/user.py/User.delete
3,220
def __init__(self, file=None): if file is None: try: file = os.path.join(os.environ['HOME'], ".netrc") except __HOLE__: raise IOError("Could not find .netrc: $HOME is not set") self.hosts = {} self.macros = {} with open(file) as fp: self._parse(file, fp)
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/netrc.py/netrc.__init__
3,221
def _stamp_version(filename): found, out = False, list() try: f = open(filename, 'r') except (__HOLE__, OSError): print("Couldn't find file %s to stamp version" % filename, file=sys.stderr) return # END handle error, usually happens during binary builds for line in f: if '__version__ =' in line: line = line.replace("'git'", "'%s'" % VERSION) found = True out.append(line) f.close() if found: f = open(filename, 'w') f.writelines(out) f.close() else: print("WARNING: Couldn't find version line in file %s" % filename, file=sys.stderr)
IOError
dataset/ETHPy150Open gitpython-developers/GitPython/setup.py/_stamp_version
3,222
@csrf_exempt def webhooks_v2(request): """ Handles all known webhooks from stripe, and calls signals. Plug in as you need. """ if request.method != "POST": return HttpResponse("Invalid Request.", status=400) try: event_json = simplejson.loads(request.body) except __HOLE__: # Backwords compatibility # Prior to Django 1.4, request.body was named request.raw_post_data event_json = simplejson.loads(request.raw_post_data) event_key = event_json['type'].replace('.', '_') if event_key in WEBHOOK_MAP: WEBHOOK_MAP[event_key].send(sender=None, full_json=event_json) return HttpResponse(status=200)
AttributeError
dataset/ETHPy150Open GoodCloud/django-zebra/zebra/views.py/webhooks_v2
3,223
def Reset(self): try: self.module.Reset() except __HOLE__: # Reset is optional, but there is no default print 'No Reset function for model program %s' % self.module.__name__ sys.exit()
AttributeError
dataset/ETHPy150Open jon-jacky/PyModel/pymodel/ModelProgram.py/ModelProgram.Reset
3,224
def get_tests(app_module): parts = app_module.__name__.split('.') prefix, last = parts[:-1], parts[-1] try: test_module = import_module('.'.join(prefix + [TEST_MODULE])) except __HOLE__: # Couldn't import tests.py. Was it due to a missing file, or # due to an import error in a tests.py that actually exists? # app_module either points to a models.py file, or models/__init__.py # Tests are therefore either in same directory, or one level up if last == 'models': app_root = import_module('.'.join(prefix)) else: app_root = app_module if not module_has_submodule(app_root, TEST_MODULE): test_module = None else: # The module exists, so there must be an import error in the test # module itself. raise return test_module
ImportError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/test/simple.py/get_tests
3,225
def build_suite(app_module): """ Create a complete Django test suite for the provided application module. """ suite = unittest.TestSuite() # Load unit and doctests in the models.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(app_module, 'suite'): suite.addTest(app_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule( app_module)) try: suite.addTest(make_doctest(app_module)) except ValueError: # No doc tests in models.py pass # Check to see if a separate 'tests' module exists parallel to the # models module test_module = get_tests(app_module) if test_module: # Load unit and doctests in the tests.py module. If module has # a suite() method, use it. Otherwise build the test suite ourselves. if hasattr(test_module, 'suite'): suite.addTest(test_module.suite()) else: suite.addTest(unittest.defaultTestLoader.loadTestsFromModule( test_module)) try: suite.addTest(make_doctest(test_module)) except __HOLE__: # No doc tests in tests.py pass return suite
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/test/simple.py/build_suite
3,226
def build_test(label): """ Construct a test case with the specified label. Label should be of the form model.TestClass or model.TestClass.test_method. Returns an instantiated test or test suite corresponding to the label provided. """ parts = label.split('.') if len(parts) < 2 or len(parts) > 3: raise ValueError("Test label '%s' should be of the form app.TestCase " "or app.TestCase.test_method" % label) # # First, look for TestCase instances with a name that matches # app_module = get_app(parts[0]) test_module = get_tests(app_module) TestClass = getattr(app_module, parts[1], None) # Couldn't find the test class in models.py; look in tests.py if TestClass is None: if test_module: TestClass = getattr(test_module, parts[1], None) try: if issubclass(TestClass, (unittest.TestCase, real_unittest.TestCase)): if len(parts) == 2: # label is app.TestClass try: return unittest.TestLoader().loadTestsFromTestCase( TestClass) except TypeError: raise ValueError( "Test label '%s' does not refer to a test class" % label) else: # label is app.TestClass.test_method return TestClass(parts[2]) except TypeError: # TestClass isn't a TestClass - it must be a method or normal class pass # # If there isn't a TestCase, look for a doctest that matches # tests = [] for module in app_module, test_module: try: doctests = make_doctest(module) # Now iterate over the suite, looking for doctests whose name # matches the pattern that was given for test in doctests: if test._dt_test.name in ( '%s.%s' % (module.__name__, '.'.join(parts[1:])), '%s.__test__.%s' % ( module.__name__, '.'.join(parts[1:]))): tests.append(test) except __HOLE__: # No doctests found. pass # If no tests were found, then we were given a bad test label. if not tests: raise ValueError("Test label '%s' does not refer to a test" % label) # Construct a suite out of the tests that matched. return unittest.TestSuite(tests)
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/test/simple.py/build_test
3,227
@staticmethod def create_from_file(path): try: with open(path) as f: config = json.loads(f.read()) return SystemModel(**config) except (__HOLE__, IOError) as e: msg = 'Failed finding or parsing config at %s.' raise SftpConfigException(msg % path, e)
ValueError
dataset/ETHPy150Open spantaleev/sftpman/sftpman/model.py/SystemModel.create_from_file
3,228
def input_object(prompt_text, cast = None, default = None, prompt_ext = ': ', castarg = [], castkwarg = {}): """Gets input from the command line and validates it. prompt_text A string. Used to prompt the user. Do not include a trailing space. prompt_ext Added on to the prompt at the end. At the moment this must not include any control stuff because it is send directly to raw_input cast This can be any callable object (class, function, type, etc). It simply calls the cast with the given arguements and returns the result. If a ValueError is raised, it will output an error message and prompt the user again. Because some builtin python objects don't do casting in the way that we might like you can easily write a wrapper function that looks and the input and returns the appropriate object or exception. Look in the cast submodule for examples. If cast is None, then it will do nothing (and you will have a string) default function returns this value if the user types nothing in. This is can be used to cancel the input so-to-speek castarg, castkwarg list and dictionary. Extra arguments passed on to the cast. """ while True: stdout.write(prompt_text) value = stdout.raw_input(prompt_ext) if value == '': return default try: if cast != None: value = cast(value, *castarg, **castkwarg) except __HOLE__, details: if cast in NICE_INPUT_ERRORS: # see comment above this constant stderr.write(ERROR_MESSAGE % (NICE_INPUT_ERRORS[cast] % details)) else: stderr.write(ERROR_MESSAGE % (DEFAULT_INPUT_ERRORS % str(details))) continue return value
ValueError
dataset/ETHPy150Open jart/fabulous/fabulous/prompt.py/input_object
3,229
def query(question, values, default=None, list_values = False, ignorecase = True ): """Preset a few options The question argument is a string, nothing magical. The values argument accepts input in two different forms. The simpler form (a tuple with strings) looks like: .. code-block:: Python ('Male','Female') And it will pop up a question asking the user for a gender and requiring the user to enter either 'male' or 'female' (case doesn't matter unless you set the third arguement to false). The other form is something like: .. code-block:: Python ({'values':('Male','M'),'fg':'cyan'}, {'values':('Female','F'),'fg':'magenta'}) This will pop up a question with Male/Female (each with appropriate colouring). Additionally, if the user types in just 'M', it will be treated as if 'Male' was typed in. The first item in the 'values' tuple is treated as default and is the one that is returned by the function if the user chooses one in that group. In addition the function can handle non-string objects quite fine. It simple displays the output object.__str__() and compares the user's input against that. So the the code .. code-block:: Python query("Python rocks? ",(True, False)) will return a bool (True) when the user types in the string 'True' (Of course there isn't any other reasonable answer than True anyways :P) ``default`` is the value function returns if the user types nothing in. This is can be used to cancel the input so-to-speek Using list_values = False will display a list, with descriptions printed out from the 'desc' keyword """ values = list(values) for i in range(len(values)): if not isinstance(values[i], dict): values[i] = {'values': [values[i]]} try: import readline, rlcomplete wordlist = [ str(v) for value in values for v in value['values']] completer = rlcomplete.ListCompleter(wordlist, ignorecase) readline.parse_and_bind("tab: complete") readline.set_completer(completer.complete) except __HOLE__: pass valuelist = [] for item in values: entry = ( display('bright', item.get('fg'), item.get('bg')) + str(item['values'][0]) + display(['default']) ) if str(item['values'][0]) == str(default): entry = '['+entry+']' if list_values: entry += ' : ' + item['desc'] valuelist.append(entry) if list_values: question += os.linesep + os.linesep.join(valuelist) + os.linesep else: question += ' (' + '/'.join(valuelist) + ')' return input_object(question, cast = query_cast, default=default, castarg=[values,ignorecase])
ImportError
dataset/ETHPy150Open jart/fabulous/fabulous/prompt.py/query
3,230
def file_chooser(prompt_text = "Enter File: ", default=None, filearg=[], filekwarg={}): """A simple tool to get a file from the user. Takes keyworded arguemnts and passes them to open(). If the user enters nothing the function will return the ``default`` value. Otherwise it continues to prompt the user until it get's a decent response. filekwarg may contain arguements passed on to ``open()``. """ try: import readline, rlcomplete completer = rlcomplete.PathCompleter() readline.set_completer_delims(completer.delims) readline.parse_and_bind("tab: complete") readline.set_completer(completer.complete) except __HOLE__: pass while True: f = raw_input(prompt_text) if f == '': return default f = os.path.expanduser(f) if len(f) != 0 and f[0] == os.path.sep: f = os.path.abspath(f) try: return open(f, *filearg, **filekwarg) except IOError, e: stderr.write(ERROR_MESSAGE % ("unable to open %s : %s" % (f, e)))
ImportError
dataset/ETHPy150Open jart/fabulous/fabulous/prompt.py/file_chooser
3,231
def operators_to_state(operators, **options): """ Returns the eigenstate of the given operator or set of operators A global function for mapping operator classes to their associated states. It takes either an Operator or a set of operators and returns the state associated with these. This function can handle both instances of a given operator or just the class itself (i.e. both XOp() and XOp) There are multiple use cases to consider: 1) A class or set of classes is passed: First, we try to instantiate default instances for these operators. If this fails, then the class is simply returned. If we succeed in instantiating default instances, then we try to call state._operators_to_state on the operator instances. If this fails, the class is returned. Otherwise, the instance returned by _operators_to_state is returned. 2) An instance or set of instances is passed: In this case, state._operators_to_state is called on the instances passed. If this fails, a state class is returned. If the method returns an instance, that instance is returned. In both cases, if the operator class or set does not exist in the state_mapping dictionary, None is returned. Parameters ========== arg: Operator or set The class or instance of the operator or set of operators to be mapped to a state Examples ======== >>> from sympy.physics.quantum.cartesian import XOp, PxOp >>> from sympy.physics.quantum.operatorset import operators_to_state >>> from sympy.physics.quantum.operator import Operator >>> operators_to_state(XOp) |x> >>> operators_to_state(XOp()) |x> >>> operators_to_state(PxOp) |px> >>> operators_to_state(PxOp()) |px> >>> operators_to_state(Operator) |psi> >>> operators_to_state(Operator()) |psi> """ if not (isinstance(operators, Operator) or isinstance(operators, set) or issubclass(operators, Operator)): raise NotImplementedError("Argument is not an Operator or a set!") if isinstance(operators, set): for s in operators: if not (isinstance(s, Operator) or issubclass(s, Operator)): raise NotImplementedError("Set is not all Operators!") ops = frozenset(operators) if ops in op_mapping: # ops is a list of classes in this case #Try to get an object from default instances of the #operators...if this fails, return the class try: op_instances = [op() for op in ops] ret = _get_state(op_mapping[ops], set(op_instances), **options) except NotImplementedError: ret = op_mapping[ops] return ret else: tmp = [type(o) for o in ops] classes = frozenset(tmp) if classes in op_mapping: ret = _get_state(op_mapping[classes], ops, **options) else: ret = None return ret else: if operators in op_mapping: try: op_instance = operators() ret = _get_state(op_mapping[operators], op_instance, **options) except __HOLE__: ret = op_mapping[operators] return ret elif type(operators) in op_mapping: return _get_state(op_mapping[type(operators)], operators, **options) else: return None
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/physics/quantum/operatorset.py/operators_to_state
3,232
def state_to_operators(state, **options): """ Returns the operator or set of operators corresponding to the given eigenstate A global function for mapping state classes to their associated operators or sets of operators. It takes either a state class or instance. This function can handle both instances of a given state or just the class itself (i.e. both XKet() and XKet) There are multiple use cases to consider: 1) A state class is passed: In this case, we first try instantiating a default instance of the class. If this succeeds, then we try to call state._state_to_operators on that instance. If the creation of the default instance or if the calling of _state_to_operators fails, then either an operator class or set of operator classes is returned. Otherwise, the appropriate operator instances are returned. 2) A state instance is returned: Here, state._state_to_operators is called for the instance. If this fails, then a class or set of operator classes is returned. Otherwise, the instances are returned. In either case, if the state's class does not exist in state_mapping, None is returned. Parameters ========== arg: StateBase class or instance (or subclasses) The class or instance of the state to be mapped to an operator or set of operators Examples ======== >>> from sympy.physics.quantum.cartesian import XKet, PxKet, XBra, PxBra >>> from sympy.physics.quantum.operatorset import state_to_operators >>> from sympy.physics.quantum.state import Ket, Bra >>> state_to_operators(XKet) X >>> state_to_operators(XKet()) X >>> state_to_operators(PxKet) Px >>> state_to_operators(PxKet()) Px >>> state_to_operators(PxBra) Px >>> state_to_operators(XBra) X >>> state_to_operators(Ket) O >>> state_to_operators(Bra) O """ if not (isinstance(state, StateBase) or issubclass(state, StateBase)): raise NotImplementedError("Argument is not a state!") if state in state_mapping: # state is a class state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state]), **options) except (NotImplementedError, TypeError): ret = state_mapping[state] elif type(state) in state_mapping: ret = _get_ops(state, _make_set(state_mapping[type(state)]), **options) elif isinstance(state, BraBase) and state.dual_class() in state_mapping: ret = _get_ops(state, _make_set(state_mapping[state.dual_class()])) elif issubclass(state, BraBase) and state.dual_class() in state_mapping: state_inst = _make_default(state) try: ret = _get_ops(state_inst, _make_set(state_mapping[state.dual_class()])) except (__HOLE__, TypeError): ret = state_mapping[state.dual_class()] else: ret = None return _make_set(ret)
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/physics/quantum/operatorset.py/state_to_operators
3,233
def _get_state(state_class, ops, **options): # Try to get a state instance from the operator INSTANCES. # If this fails, get the class try: ret = state_class._operators_to_state(ops, **options) except __HOLE__: ret = _make_default(state_class) return ret
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/physics/quantum/operatorset.py/_get_state
3,234
def _get_ops(state_inst, op_classes, **options): # Try to get operator instances from the state INSTANCE. # If this fails, just return the classes try: ret = state_inst._state_to_operators(op_classes, **options) except __HOLE__: if isinstance(op_classes, (set, tuple, frozenset)): ret = tuple(_make_default(x) for x in op_classes) else: ret = _make_default(op_classes) if isinstance(ret, set) and len(ret) == 1: return ret[0] return ret
NotImplementedError
dataset/ETHPy150Open sympy/sympy/sympy/physics/quantum/operatorset.py/_get_ops
3,235
def current_flow_closeness_centrality(G, normalized=True, weight='weight', dtype=float, solver='lu'): """Compute current-flow closeness centrality for nodes. A variant of closeness centrality based on effective resistance between nodes in a network. This metric is also known as information centrality. Parameters ---------- G : graph A NetworkX graph normalized : bool, optional If True the values are normalized by 1/(n-1) where n is the number of nodes in G. dtype: data type (float) Default data type for internal matrices. Set to np.float32 for lower memory consumption. solver: string (default='lu') Type of linear solver to use for computing the flow matrix. Options are "full" (uses most memory), "lu" (recommended), and "cg" (uses least memory). Returns ------- nodes : dictionary Dictionary of nodes with current flow closeness centrality as the value. See Also -------- closeness_centrality Notes ----- The algorithm is from Brandes [1]_. See also [2]_ for the original definition of information centrality. References ---------- .. [1] Ulrik Brandes and Daniel Fleischer, Centrality Measures Based on Current Flow. Proc. 22nd Symp. Theoretical Aspects of Computer Science (STACS '05). LNCS 3404, pp. 533-544. Springer-Verlag, 2005. http://www.inf.uni-konstanz.de/algo/publications/bf-cmbcf-05.pdf .. [2] Stephenson, K. and Zelen, M. Rethinking centrality: Methods and examples. Social Networks. Volume 11, Issue 1, March 1989, pp. 1-37 http://dx.doi.org/10.1016/0378-8733(89)90016-6 """ from networkx.utils import reverse_cuthill_mckee_ordering try: import numpy as np except ImportError: raise ImportError('current_flow_closeness_centrality requires NumPy ', 'http://scipy.org/') try: import scipy except __HOLE__: raise ImportError('current_flow_closeness_centrality requires SciPy ', 'http://scipy.org/') if G.is_directed(): raise nx.NetworkXError('current_flow_closeness_centrality ', 'not defined for digraphs.') if G.is_directed(): raise nx.NetworkXError(\ "current_flow_closeness_centrality() not defined for digraphs.") if not nx.is_connected(G): raise nx.NetworkXError("Graph not connected.") solvername={"full" :FullInverseLaplacian, "lu": SuperLUInverseLaplacian, "cg": CGInverseLaplacian} n = G.number_of_nodes() ordering = list(reverse_cuthill_mckee_ordering(G)) # make a copy with integer labels according to rcm ordering # this could be done without a copy if we really wanted to H = nx.relabel_nodes(G,dict(zip(ordering,range(n)))) betweenness = dict.fromkeys(H,0.0) # b[v]=0 for v in H n = G.number_of_nodes() L = laplacian_sparse_matrix(H, nodelist=range(n), weight=weight, dtype=dtype, format='csc') C2 = solvername[solver](L, width=1, dtype=dtype) # initialize solver for v in H: col=C2.get_row(v) for w in H: betweenness[v]+=col[v]-2*col[w] betweenness[w]+=col[v] if normalized: nb=len(betweenness)-1.0 else: nb=1.0 for v in H: betweenness[v]=nb/(betweenness[v]) return dict((ordering[k],float(v)) for k,v in betweenness.items())
ImportError
dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/centrality/current_flow_closeness.py/current_flow_closeness_centrality
3,236
def test(path_data, parameters=''): if not parameters: parameters = '-i mt/mt0.nii.gz -s mt/mt0_seg.nii.gz -vertfile mt/label/template/MNI-Poly-AMU_level.nii.gz -normalize 1 -ref mt/mt0_manual_gmseg.nii.gz -qc 0' parser = sct_segment_graymatter.get_parser() dict_param = parser.parse(parameters.split(), check_file_exist=False) dict_param_with_path = parser.add_path_to_file(dict_param, path_data, input_file=True) #if -model is used : do not add the path before. if '-model' in dict_param_with_path.keys(): dict_param_with_path['-model'] = dict_param_with_path['-model'][len(path_data):] param_with_path = parser.dictionary_to_string(dict_param_with_path) # Check if input files exist if not (os.path.isfile(dict_param_with_path['-i']) and os.path.isfile(dict_param_with_path['-s']) and os.path.isfile(dict_param_with_path['-vertfile']) and os.path.isfile(dict_param_with_path['-ref'])): status = 200 output = 'ERROR: the file(s) provided to test function do not exist in folder: ' + path_data return status, output, DataFrame(data={'status': status, 'output': output, 'dice_gm': float('nan'), 'dice_wm': float('nan'), 'hausdorff': float('nan'), 'med_dist': float('nan'), 'duration_[s]': float('nan')}, index=[path_data]) import time, random subject_folder = path_data.split('/') if subject_folder[-1] == '' and len(subject_folder) > 1: subject_folder = subject_folder[-2] else: subject_folder = subject_folder[-1] path_output = sct.slash_at_the_end('sct_segment_graymatter_' + subject_folder + '_' + time.strftime("%y%m%d%H%M%S") + '_'+str(random.randint(1, 1000000)), slash=1) param_with_path += ' -ofolder ' + path_output cmd = 'sct_segment_graymatter ' + param_with_path time_start = time.time() status, output = sct.run(cmd, 0) duration = time.time() - time_start # initialization of results: must be NaN if test fails result_dice_gm, result_dice_wm, result_hausdorff, result_median_dist = float('nan'), float('nan'), float('nan'), float('nan') if status == 0: target_name = sct.extract_fname(dict_param_with_path["-i"])[1] dice_fname = path_output+'dice_'+target_name+'_'+dict_param_with_path["-res-type"]+'.txt' hausdorff_fname = path_output+'hd_'+target_name+'_'+dict_param_with_path["-res-type"]+'.txt' # Extracting dice results: dice = open(dice_fname, 'r') dice_lines = dice.readlines() dice.close() gm_start = dice_lines.index('Dice coefficient on the Gray Matter segmentation:\n') wm_start = dice_lines.index('Dice coefficient on the White Matter segmentation:\n') # extracting dice on GM gm_dice_lines = dice_lines[gm_start:wm_start-1] gm_dice_lines = gm_dice_lines[gm_dice_lines.index('2D Dice coefficient by slice:\n')+1:-1] null_slices = [] gm_dice = [] for line in gm_dice_lines: n_slice, dc = line.split(' ') # remove \n from dice result dc = dc[:-1] dc = dc[:-4] if '[0m' in dc else dc if dc == '0' or dc == 'nan': null_slices.append(n_slice) else: try: gm_dice.append(float(dc)) except ValueError: gm_dice.append(float(dc[:-4])) result_dice_gm = mean(gm_dice) # extracting dice on WM wm_dice_lines = dice_lines[wm_start:] wm_dice_lines = wm_dice_lines[wm_dice_lines.index('2D Dice coefficient by slice:\n')+1:] wm_dice = [] for line in wm_dice_lines: n_slice, dc = line.split(' ') # remove \n from dice result if line is not wm_dice_lines[-1]: dc = dc[:-1] if n_slice not in null_slices: try: wm_dice.append(float(dc)) except __HOLE__: wm_dice.append(float(dc[:-4])) result_dice_wm = mean(wm_dice) # Extracting hausdorff distance results hd = open(hausdorff_fname, 'r') hd_lines = hd.readlines() hd.close() # remove title of columns and last empty/non important lines hd_lines = hd_lines[1:-4] hausdorff = [] max_med = [] for line in hd_lines: slice_id, res = line.split(':') slice, n_slice = slice_id.split(' ') if n_slice not in null_slices: hd, med1, med2 = res[:-1].split(' - ') hd, med1, med2 = float(hd), float(med1), float(med2) hausdorff.append(hd) max_med.append(max(med1, med2)) result_hausdorff = mean(hausdorff) result_median_dist = mean(max_med) # Integrity check hd_threshold = 1.5 # in mm wm_dice_threshold = 0.8 if result_hausdorff > hd_threshold or result_dice_wm < wm_dice_threshold: status = 99 output += '\nResulting segmentation is too different from manual segmentation:\n' \ 'WM dice: '+str(result_dice_wm)+'\n' \ 'Hausdorff distance: '+str(result_hausdorff)+'\n' # transform results into Pandas structure results = DataFrame(data={'status': status, 'output': output, 'dice_gm': result_dice_gm, 'dice_wm': result_dice_wm, 'hausdorff': result_hausdorff, 'med_dist': result_median_dist, 'duration_[s]': duration}, index=[path_data]) return status, output, results
ValueError
dataset/ETHPy150Open neuropoly/spinalcordtoolbox/testing/test_sct_segment_graymatter.py/test
3,237
def _delete_pack_db_object(self, pack): try: pack_db = Pack.get_by_name(value=pack) except __HOLE__: self.logger.exception('Pack DB object not found') return try: Pack.delete(pack_db) except: self.logger.exception('Failed to remove DB object %s.', pack_db)
ValueError
dataset/ETHPy150Open StackStorm/st2/contrib/packs/actions/pack_mgmt/unload.py/UnregisterPackAction._delete_pack_db_object
3,238
def render(self): data = [] for name, hist in self._data.items(): for idx, v in enumerate(hist["views"]): graph = {"key": name, "view": v["view"], "disabled": hist["disabled"], "values": [{"x": x, "y": y} for x, y in zip(v["x"], v["y"])]} try: data[idx].append(graph) except __HOLE__: data.append([graph]) return {"data": data, "views": [{"id": i, "name": d[0]["view"]} for i, d in enumerate(data)]}
IndexError
dataset/ETHPy150Open openstack/rally/rally/task/processing/charts.py/HistogramChart.render
3,239
def test_conversion(self): # Test __long__() class ClassicMissingMethods: pass if test_support.is_jython: self.assertRaises(TypeError, int, ClassicMissingMethods()) else: self.assertRaises(AttributeError, int, ClassicMissingMethods()) class MissingMethods(object): pass self.assertRaises(TypeError, long, MissingMethods()) class Foo0: def __long__(self): return 42L class Foo1(object): def __long__(self): return 42L class Foo2(long): def __long__(self): return 42L class Foo3(long): def __long__(self): return self class Foo4(long): def __long__(self): return 42 class Foo5(long): def __long__(self): return 42. self.assertEqual(long(Foo0()), 42L) self.assertEqual(long(Foo1()), 42L) self.assertEqual(long(Foo2()), 42L) self.assertEqual(long(Foo3()), 0) self.assertEqual(long(Foo4()), 42) self.assertRaises(TypeError, long, Foo5()) class Classic: pass for base in (object, Classic): class LongOverridesTrunc(base): def __long__(self): return 42 def __trunc__(self): return -12 self.assertEqual(long(LongOverridesTrunc()), 42) class JustTrunc(base): def __trunc__(self): return 42 self.assertEqual(long(JustTrunc()), 42) for trunc_result_base in (object, Classic): class Integral(trunc_result_base): def __int__(self): return 42 class TruncReturnsNonLong(base): def __trunc__(self): return Integral() self.assertEqual(long(TruncReturnsNonLong()), 42) class NonIntegral(trunc_result_base): def __trunc__(self): # Check that we avoid infinite recursion. return NonIntegral() class TruncReturnsNonIntegral(base): def __trunc__(self): return NonIntegral() try: long(TruncReturnsNonIntegral()) except __HOLE__ as e: if not test_support.is_jython: self.assertEqual(str(e), "__trunc__ returned non-Integral" " (type NonIntegral)") else: self.fail("Failed to raise TypeError with %s" % ((base, trunc_result_base),))
TypeError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_long.py/LongTest.test_conversion
3,240
@classmethod def get_master_instance(self, ar, model, pk): """Return the `master_instance` corresponding to the specified primary key. You need to override this only on slave actors whose :attr:`master` is something else than a database model, e.g. the :class:`ProblemsByChecker <lino.modlib.plausibility.models.ProblemsByChecker>` table. `ar` is the action request on this actor. `model` is the :attr:`master`, except if :attr:`master` is `ContentType` (in which case `model` is the *requested* master). """ if issubclass(model, models.Model): try: return model.objects.get(pk=pk) except __HOLE__: return None except model.DoesNotExist: return None msg = "{0} must override get_master_instance" msg = msg.format(self) raise Exception(msg) # from lino.core import choicelists # if issubclass(master, choicelists.Choice): # if master.choicelist is None: # kw['master_instance'] = None # else: # mi = master.choicelist.get_by_values(pk) # kw['master_instance'] = mi # else: # logger.info("Invalid master %s", master)
ValueError
dataset/ETHPy150Open lsaffre/lino/lino/core/actors.py/Actor.get_master_instance
3,241
def verify_has_only_ascii_chars(filename): with open(filename, 'rb') as f: bytes_content = f.read() try: bytes_content.decode('ascii') except __HOLE__ as e: # The test has failed so we'll try to provide a useful error # message. offset = e.start spread = 20 bad_text = bytes_content[offset-spread:e.start+spread] underlined = ' ' * spread + '^' error_text = '\n'.join([bad_text, underlined]) line_number = bytes_content[:offset].count(b'\n') + 1 raise AssertionError( "Non ascii characters found in the examples file %s, line %s:" "\n\n%s\n" % (filename, line_number, error_text))
UnicodeDecodeError
dataset/ETHPy150Open aws/aws-cli/tests/functional/docs/test_examples.py/verify_has_only_ascii_chars
3,242
def sendEvent(self, event): try: value = simplejson.dumps(event) except (__HOLE__, ValueError): log.err(None, "Could not encode event to JSON") return try: d = self.client.lpush(self.key, value) except: log.err() d.addErrback(lambda failure: failure.trap(NoClientError)) d.addErrback(log.err)
TypeError
dataset/ETHPy150Open mochi/udplog/udplog/redis.py/RedisPublisher.sendEvent
3,243
def lpush(self, key, *values, **kwargs): """ Add string to head of list. This selects a factory and attempts a push there, falling back to others until none are left. In that case, L{NoClientError} is fired from the returned deferred. @param key: List key @param values: Sequence of values to push @param value: For backwards compatibility, a single value. """ def eb(failure): failure.trap(RuntimeError) if failure.value.args == ("Not connected",): self._disconnected(factory) return self.lpush(key, *values, **kwargs) else: return failure if not self.factories: return defer.fail(NoClientError()) factory = random.sample(self.factories, 1)[0] try: d = factory.client.lpush(key, *values, **kwargs) except __HOLE__: self._disconnected(factory) return self.lpush(key, *values, **kwargs) d.addErrback(eb) return d
AttributeError
dataset/ETHPy150Open mochi/udplog/udplog/redis.py/RedisPushMultiClient.lpush
3,244
def start_proc_manager(config, logfile): from pycopia import proctools from pycopia import scheduler from pycopia import asyncio pm = proctools.get_procmanager() libexec = config.get("LIBEXEC", "/usr/libexec/pycopia") for name, serverlist in config.VHOSTS.items(): for servername in serverlist: print "Starting %s for %s." % (servername, name) p = pm.spawnpipe("%s/fcgi_server -n %s" % (libexec, servername), persistent=True, logfile=logfile) asyncio.poller.register(p) #scheduler.sleep(1.0) # give it time to init... if config.USEFRONTEND: lighttpd = proctools.which("lighttpd") if asyncio.poller: pm.spawnpipe("%s -D -f %s" % (lighttpd, LTCONFIG), persistent=True, logfile=logfile) else: # no servers, just run frontend alone pm.spawnpipe("%s -f %s" % (lighttpd, LTCONFIG)) try: asyncio.poller.loop() print "No servers, exited loop." except __HOLE__: pass if asyncio.poller: asyncio.poller.unregister_all() for proc in pm.getprocs(): proc.killwait() if os.path.exists(config.PIDFILE): os.unlink(config.PIDFILE)
KeyboardInterrupt
dataset/ETHPy150Open kdart/pycopia/WWW/pycopia/WWW/website.py/start_proc_manager
3,245
def is_failure_notable(self, reason): try: tstamp, last_err = self.history[-1] except __HOLE__: pass else: if type(last_err) is type(reason.value): if time() < self.can_reconnect_at: return False return True
IndexError
dataset/ETHPy150Open driftx/Telephus/telephus/pool.py/CassandraNode.is_failure_notable
3,246
def remove_good_conn(self, f): try: self.good_conns.remove(f) except __HOLE__: pass
KeyError
dataset/ETHPy150Open driftx/Telephus/telephus/pool.py/CassandraClusterPool.remove_good_conn
3,247
def remove_connector(self, f): self.remove_good_conn(f) try: self.connectors.remove(f) except __HOLE__: try: self.dying_conns.remove(f) except KeyError: pass
KeyError
dataset/ETHPy150Open driftx/Telephus/telephus/pool.py/CassandraClusterPool.remove_connector
3,248
def resubmit(self, req, keyspace, req_d, retries): """ Push this request to the front of the line, just to be a jerk. """ self.log('resubmitting %s request' % (req.method,)) self.pushRequest_really(req, keyspace, req_d, retries) try: self.request_queue.pending.remove((req, keyspace, req_d, retries)) except __HOLE__: # it's already been scooped up pass else: self.request_queue.pending.insert(0, (req, keyspace, req_d, retries))
ValueError
dataset/ETHPy150Open driftx/Telephus/telephus/pool.py/CassandraClusterPool.resubmit
3,249
def _parse_resolv(self): self._servers = [] try: with open('/etc/resolv.conf', 'rb') as f: content = f.readlines() for line in content: line = line.strip() if line: if line.startswith(b'nameserver'): parts = line.split() if len(parts) >= 2: server = parts[1] if common.is_ip(server) == socket.AF_INET: if type(server) != str: server = server.decode('utf8') self._servers.append(server) except __HOLE__: pass if not self._servers: self._servers = ['8.8.4.4', '8.8.8.8']
IOError
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/asyncdns.py/DNSResolver._parse_resolv
3,250
def _parse_hosts(self): etc_path = '/etc/hosts' if 'WINDIR' in os.environ: etc_path = os.environ['WINDIR'] + '/system32/drivers/etc/hosts' try: with open(etc_path, 'rb') as f: for line in f.readlines(): line = line.strip() parts = line.split() if len(parts) >= 2: ip = parts[0] if common.is_ip(ip): for i in range(1, len(parts)): hostname = parts[i] if hostname: self._hosts[hostname] = ip except __HOLE__: self._hosts['localhost'] = '127.0.0.1'
IOError
dataset/ETHPy150Open ziggear/shadowsocks/shadowsocks/asyncdns.py/DNSResolver._parse_hosts
3,251
@lib.api_call def rotate(self, rate): """Pass (angular) rate as -100 to +100 (positive is counterclockwise).""" # Validate params self.logger.debug("Rotating with angular rate: {}".format(rate)) try: assert MecDriver.min_angular_rate <= rate <= \ MecDriver.max_angular_rate except __HOLE__: raise AssertionError("Angular rate is out of bounds") # if rate == 0: # TODO deadband (epsilon) check? self.set_motor("front_left", -rate) self.set_motor("front_right", rate) self.set_motor("back_left", -rate) self.set_motor("back_right", rate) # NOTE(napratin, 9/17): # Set motor directions, based on http://goo.gl/B1KEUV # Also see MecanumWheelDirection.png # Only 2 wheels need to be turned on for each direction, but using all # 4 wheels in a conventional differential # rotation works fine
AssertionError
dataset/ETHPy150Open IEEERobotics/bot/bot/driver/mec_driver.py/MecDriver.rotate
3,252
@lib.api_call def move(self, speed, angle=0): """Move holonomically without rotation. :param speed: Magnitude of robot's translation speed (% of max). :type speed: float :param angle: Angle of translation in degrees (90=left, 270=right). :type angle: float """ # Validate params self.logger.debug("speed: {}, angle: {}".format(speed, angle)) try: assert MecDriver.min_speed <= speed <= MecDriver.max_speed except AssertionError: raise AssertionError("Speed is out of bounds") # Angle bounds may be unnecessary try: assert MecDriver.min_angle <= angle <= MecDriver.max_angle except __HOLE__: raise AssertionError("Angle is out of bounds") # Handle zero speed, prevent divide-by-zero error if speed == 0: # TODO deadband (epsilon) check? self.logger.debug("Special case for speed == 0") self.set_motor("front_left", 0) self.set_motor("front_right", 0) self.set_motor("back_left", 0) self.set_motor("back_right", 0) return # Calculate motor speeds # Formulae from Mecanumdrive.pdf in google drive. # TODO Check math: why are all the phase offsets +pi/4? front_left = speed * sin(angle * pi / 180 + pi / 4) front_right = speed * cos(angle * pi / 180 + pi / 4) back_left = speed * cos(angle * pi / 180 + pi / 4) back_right = speed * sin(angle * pi / 180 + pi / 4) self.logger.debug(( "pre-scale : front_left: {:6.2f}, front_right: {:6.2f}," " back_left: {:6.2f}, back_right: {:6.2f}").format( front_left, front_right, back_left, back_right)) # Find largest motor speed, # use that to normalize multipliers and maintain maximum efficiency max_wheel_speed = max( [fabs(front_left), fabs(front_right), fabs(back_left), fabs(back_right)] ) front_left = front_left * speed / max_wheel_speed front_right = front_right * speed / max_wheel_speed back_left = back_left * speed / max_wheel_speed back_right = back_right * speed / max_wheel_speed self.logger.debug( ("post-scale: front_left: {:6.2f}, front_right: {:6.2f}," " back_left: {:6.2f}, back_right: {:6.2f}").format( front_left, front_right, back_left, back_right)) # Set motor speeds self.set_motor("front_left", front_left) self.set_motor("front_right", front_right) self.set_motor("back_left", back_left) self.set_motor("back_right", back_right)
AssertionError
dataset/ETHPy150Open IEEERobotics/bot/bot/driver/mec_driver.py/MecDriver.move
3,253
def _walk_repository(repodir, ignore_file=None, parse_ignore=None, match_ignore=None, path=None, depth=0): """Do the actual repository walking, using repository specific parse and match functions. The `ignore_file` argument specifies the name of the repository specific ignore file (e.g. '.gitignore' for git). The `parse_ignore` argument is a function that can parse the ignore file. Prototype: `parse_ignore(input)` with `input` a file like object or a string. The `match_ignore` argument is a function that is used to match individual files and directories against a hierarchy of ignore files. Prototype: `match_ignore(path)` where path is a list of `(name, parsed_ignore_file, ignore_or_mode)`. The path contains one element per path component. The `name` field the name of the path component. The `parsed_ignore_file` field is the parsed ignore file file for that level, if any. The `ignore` field is a boolean that indicates the result of a previous `match_ignore()` invocation for the level. This field is set for all but the final level. In the final level, this field is multiplexed and instead indicates whether the final path component is a file or directory. """ if path is None: path = [] parsed_ignore_file = None if ignore_file is not None: fullname = os.path.join(repodir, ignore_file) try: st = os.stat(fullname) except __HOLE__: pass else: if stat.S_ISREG(st.st_mode): with open(fullname) as fin: parsed_ignore_file = parse_ignore(fin) path.append(None) contents = os.listdir(repodir) # For each file and directory in the tree, keep track of a path # containing (name, parsed_ignore, ignore) tuples for every path # element up till the top of the tree. for fname in contents: fullname = os.path.join(repodir, fname) try: st = os.stat(fullname) except OSError: continue if stat.S_ISREG(st.st_mode): path[depth] = (fname, parsed_ignore_file, st.st_mode) if not match_ignore or not match_ignore(path): yield os.path.join(*(p[0] for p in path)) elif stat.S_ISDIR(st.st_mode): path[depth] = (fname, parsed_ignore_file, st.st_mode) ignore = match_ignore(path) if match_ignore else INCLUDE path[depth] = (fname, parsed_ignore_file, ignore) if ignore != TRUNCATE: path_yielded = False for elem in _walk_repository(fullname, ignore_file, parse_ignore, match_ignore, path, depth+1): if not path_yielded: yield os.path.join(*(p[0] for p in path[:depth+1])) path_yielded = True yield elem # Ignore anything that is not a file or directory. del path[-1]
OSError
dataset/ETHPy150Open ravello/testmill/lib/testmill/versioncontrol.py/_walk_repository
3,254
def set_selection(self, objects=[], notify=True): """Sets the current selection to a set of specified objects.""" if not isinstance(objects, SequenceTypes): objects = [ objects ] mode = self.factory.selection_mode indexes = [] flags = QtGui.QItemSelectionModel.ClearAndSelect # In the case of row or column selection, we need a dummy value for the # other dimension that has not been filtered. source_index = self.model.mapToSource(self.model.index(0, 0)) source_row, source_column = source_index.row(), source_index.column() # Selection mode is 'row' or 'rows' if mode.startswith('row'): flags |= QtGui.QItemSelectionModel.Rows items = self.items() for obj in objects: try: row = items.index(obj) except ValueError: continue indexes.append(self.source_model.index(row, source_column)) # Selection mode is 'column' or 'columns' elif mode.startswith('column'): flags |= QtGui.QItemSelectionModel.Columns for name in objects: column = self._column_index_from_name(name) if column != -1: indexes.append(self.source_model.index(source_row, column)) # Selection mode is 'cell' or 'cells' else: items = self.items() for obj, name in objects: try: row = items.index(obj) except __HOLE__: continue column = self._column_index_from_name(name) if column != -1: indexes.append(self.source_model.index(row, column)) # Perform the selection so that only one signal is emitted selection = QtGui.QItemSelection() for index in indexes: index = self.model.mapFromSource(index) if index.isValid(): self.table_view.setCurrentIndex(index) selection.select(index, index) smodel = self.table_view.selectionModel() try: smodel.blockSignals(not notify) if len(selection.indexes()): smodel.select(selection, flags) else: smodel.clear() finally: smodel.blockSignals(False) #--------------------------------------------------------------------------- # Private methods: #---------------------------------------------------------------------------
ValueError
dataset/ETHPy150Open enthought/traitsui/traitsui/qt4/table_editor.py/TableEditor.set_selection
3,255
@cached_property def _get_selected_row(self): """Gets the selected row, or the first row if multiple rows are selected.""" mode = self.factory.selection_mode if mode.startswith('column'): return None elif mode == 'row': return self.selected try: if mode == 'rows': return self.selected[0] elif mode == 'cell': return self.selected[0] elif mode == 'cells': return self.selected[0][0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open enthought/traitsui/traitsui/qt4/table_editor.py/TableEditor._get_selected_row
3,256
def render(self, request): """Render me to a web client. Load my file, execute it in a special namespace (with 'request' and '__file__' global vars) and finish the request. Output to the web-page will NOT be handled with print - standard output goes to the log - but with request.write. """ request.setHeader("x-powered-by","Twisted/%s" % copyright.version) namespace = {'request': request, '__file__': self.filename, 'registry': self.registry} try: execfile(self.filename, namespace, namespace) except __HOLE__, e: if e.errno == 2: #file not found request.setResponseCode(http.NOT_FOUND) request.write(resource.NoResource("File not found.").render(request)) except: io = StringIO.StringIO() traceback.print_exc(file=io) request.write(html.PRE(io.getvalue())) request.finish() return server.NOT_DONE_YET
IOError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/web/script.py/PythonScript.render
3,257
def run(self, edit): try: regions = [] for region in self.view.sel(): regions.append(sublime.Region(region.a, region.b)) if region.empty(): selection = sublime.Region(0, self.view.size()) else: selection = region sel_str = self.view.substr(selection).replace('\r\n', '\n') exit_code, out, err = call_and_wait_with_input(['stylish-haskell'], sel_str) out_str = out.replace('\r\n', '\n') if exit_code == 0 and out_str != sel_str: self.view.replace(edit, selection, out_str) self.view.sel().clear() for region in regions: self.view.sel().add(region) except __HOLE__ as e: if e.errno == errno.ENOENT: sublime.error_message("SublimeHaskell: stylish-haskell was not found!")
OSError
dataset/ETHPy150Open SublimeHaskell/SublimeHaskell/stylishhaskell.py/SublimeHaskellStylish.run
3,258
def _clean(self, data, full=True): try: self._obj.full_clean(exclude=self._meta.exclude) except __HOLE__ as e: for k, v in e.message_dict.items(): self._errors.setdefault(k, []).extend(v)
ValidationError
dataset/ETHPy150Open funkybob/django-nap/nap/datamapper/models.py/ModelDataMapper._clean
3,259
def test01d_errors(self): "Testing the Error handlers." # string-based print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n" for err in self.geometries.errors: try: g = fromstr(err.wkt) except (GEOSException, __HOLE__): pass # Bad WKB self.assertRaises(GEOSException, GEOSGeometry, buffer('0')) print "\nEND - expecting GEOS_ERROR; safe to ignore.\n" class NotAGeometry(object): pass # Some other object self.assertRaises(TypeError, GEOSGeometry, NotAGeometry()) # None self.assertRaises(TypeError, GEOSGeometry, None)
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/gis/geos/tests/test_geos.py/GEOSTest.test01d_errors
3,260
def parse(self, source): self._graph = None try: # Compressed? try: # UTF-8? try: source = source.encode('utf-8') except __HOLE__: pass source = gzip.GzipFile(fileobj=StringIO.StringIO(source), mode='rb').read() except IOError: pass xml.sax.parseString(source, self) # Delete 'OPERATOR' from tail nodes tail_nodes = [node for node, degree in self._graph.out_degree().items() if degree == 0] for node in tail_nodes: del self._graph.node[node]['OPERATOR'] except xml.sax._exceptions.SAXParseException: pass return self._graph
UnicodeDecodeError
dataset/ETHPy150Open ikotler/pythonect/pythonect/internal/parsers/dia.py/_DiaParser.parse
3,261
def __init__(self, socketname, sockchmod, sockchown, logger_object): self.ip = socketname self.port = socketname # XXX this is insecure. We really should do something like # http://developer.apple.com/samplecode/CFLocalServer/listing6.html # (see also http://developer.apple.com/technotes/tn2005/tn2083.html#SECUNIXDOMAINSOCKETS) # but it would be very inconvenient for the user to need to get all # the directory setup right. tempname = "%s.%d" % (socketname, os.getpid()) try: os.unlink(tempname) except OSError: pass while 1: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: sock.bind(tempname) os.chmod(tempname, sockchmod) try: # hard link os.link(tempname, socketname) except OSError: # Lock contention, or stale socket. used = self.checkused(socketname) if used: # cooperate with 'openhttpserver' in supervisord raise socket.error(errno.EADDRINUSE) # Stale socket -- delete, sleep, and try again. msg = "Unlinking stale socket %s\n" % socketname sys.stderr.write(msg) try: os.unlink(socketname) except: pass sock.close() time.sleep(.3) continue else: try: os.chown(socketname, sockchown[0], sockchown[1]) except __HOLE__, why: if why[0] == errno.EPERM: msg = ('Not permitted to chown %s to uid/gid %s; ' 'adjust "sockchown" value in config file or ' 'on command line to values that the ' 'current user (%s) can successfully chown') raise ValueError(msg % (socketname, repr(sockchown), pwd.getpwuid( os.geteuid())[0], ), ) else: raise self.prebind(sock, logger_object) break finally: try: os.unlink(tempname) except OSError: pass self.server_name = '<unix domain socket>' self.postbind()
OSError
dataset/ETHPy150Open XiaoMi/minos/supervisor/supervisor/http.py/supervisor_af_unix_http_server.__init__
3,262
def more(self): try: newsz = self.fsize() except __HOLE__: # file descriptor was closed return '' bytes_added = newsz - self.sz if bytes_added < 0: self.sz = 0 return "==> File truncated <==\n" if bytes_added > 0: self.file.seek(-bytes_added, 2) bytes = self.file.read(bytes_added) self.sz = newsz return bytes return NOT_DONE_YET
OSError
dataset/ETHPy150Open XiaoMi/minos/supervisor/supervisor/http.py/tail_f_producer.more
3,263
def handle_request(self, request): if request.command != 'GET': request.error (400) # bad request return path, params, query, fragment = request.split_uri() if '%' in path: path = http_server.unquote(path) # strip off all leading slashes while path and path[0] == '/': path = path[1:] path, process_name_and_channel = path.split('/', 1) try: process_name, channel = process_name_and_channel.split('/', 1) except __HOLE__: # no channel specified, default channel to stdout process_name = process_name_and_channel channel = 'stdout' from supervisor.options import split_namespec group_name, process_name = split_namespec(process_name) group = self.supervisord.process_groups.get(group_name) if group is None: request.error(404) # not found return process = group.processes.get(process_name) if process is None: request.error(404) # not found return logfile = getattr(process.config, '%s_logfile' % channel, None) if logfile is None or not os.path.exists(logfile): # XXX problematic: processes that don't start won't have a log # file and we probably don't want to go into fatal state if we try # to read the log of a process that did not start. request.error(410) # gone return mtime = os.stat(logfile)[stat.ST_MTIME] request['Last-Modified'] = http_date.build_http_date(mtime) request['Content-Type'] = 'text/plain' # the lack of a Content-Length header makes the outputter # send a 'Transfer-Encoding: chunked' response request.push(tail_f_producer(request, logfile, 1024)) request.done()
ValueError
dataset/ETHPy150Open XiaoMi/minos/supervisor/supervisor/http.py/logtail_handler.handle_request
3,264
@property def body(self): if self._body: return self._body try: length = int(self.environ.get("CONTENT_LENGTH", "0")) except __HOLE__: length = 0 if length > 0: self._body = self.environ['wsgi.input'].read(length) return self._body
ValueError
dataset/ETHPy150Open nullism/pycnic/pycnic/core.py/Request.body
3,265
@property def ip(self): try: return self.environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except __HOLE__: return self.environ['REMOTE_ADDR']
KeyError
dataset/ETHPy150Open nullism/pycnic/pycnic/core.py/Request.ip
3,266
def delegate(self): path = self.request.path method = self.request.method for pattern, handler in self.routes: # Set defaults for handler handler.request = self.request handler.response = self.response if hasattr(handler, 'before'): handler.before() m = re.match('^' + pattern + '$', path) if m: args = m.groups() funcname = method.lower() try: func = getattr(handler, funcname) except __HOLE__: raise errors.HTTP_405("%s not allowed"%(method.upper())) output = func(*args) if hasattr(handler, 'after'): handler.after() return output raise errors.HTTP_404("Path %s not found"%(path))
AttributeError
dataset/ETHPy150Open nullism/pycnic/pycnic/core.py/WSGI.delegate
3,267
@destructiveTest @skipIf(os.geteuid() != 0, 'you must be root to run this test') def test_groups_includes_primary(self): # Let's create a user, which usually creates the group matching the # name uname = self.__random_string() if self.run_function('user.add', [uname]) is not True: # Skip because creating is not what we're testing here self.run_function('user.delete', [uname, True, True]) self.skipTest('Failed to create user') try: uinfo = self.run_function('user.info', [uname]) self.assertIn(uname, uinfo['groups']) # This uid is available, store it uid = uinfo['uid'] self.run_function('user.delete', [uname, True, True]) # Now, a weird group id gname = self.__random_string() if self.run_function('group.add', [gname]) is not True: self.run_function('group.delete', [gname, True, True]) self.skipTest('Failed to create group') ginfo = self.run_function('group.info', [gname]) # And create the user with that gid if self.run_function('user.add', [uname, uid, ginfo['gid']]) is False: # Skip because creating is not what we're testing here self.run_function('user.delete', [uname, True, True]) self.skipTest('Failed to create user') uinfo = self.run_function('user.info', [uname]) self.assertIn(gname, uinfo['groups']) except __HOLE__: self.run_function('user.delete', [uname, True, True]) raise
AssertionError
dataset/ETHPy150Open saltstack/salt/tests/integration/modules/pw_user.py/PwUserModuleTest.test_groups_includes_primary
3,268
def runjob(self, app_name, job_name, options): verbosity = int(options.get('verbosity', 1)) if verbosity > 1: print("Executing job: %s (app: %s)" % (job_name, app_name)) try: job = get_job(app_name, job_name) except __HOLE__: if app_name: print("Error: Job %s for applabel %s not found" % (job_name, app_name)) else: print("Error: Job %s not found" % job_name) print("Use -l option to view all the available jobs") return try: job().execute() except Exception: import traceback print("ERROR OCCURED IN JOB: %s (APP: %s)" % (job_name, app_name)) print("START TRACEBACK:") traceback.print_exc() print("END TRACEBACK\n")
KeyError
dataset/ETHPy150Open django-extensions/django-extensions/django_extensions/management/commands/runjob.py/Command.runjob
3,269
def shortcut(request, content_type_id, object_id): "Redirect to an object's page based on a content-type ID and an object ID." # Look up the object, making sure it's got a get_absolute_url() function. try: content_type = ContentType.objects.get(pk=content_type_id) obj = content_type.get_object_for_this_type(pk=object_id) except __HOLE__: raise http.Http404, "Content type %s object %s doesn't exist" % (content_type_id, object_id) try: absurl = obj.get_absolute_url() except AttributeError: raise http.Http404, "%s objects don't have get_absolute_url() methods" % content_type.name # Try to figure out the object's domain, so we can do a cross-site redirect # if necessary. # If the object actually defines a domain, we're done. if absurl.startswith('http://'): return http.HttpResponseRedirect(absurl) object_domain = None # Otherwise, we need to introspect the object's relationships for a # relation to the Site object opts = obj._meta # First, look for an many-to-many relationship to sites for field in opts.many_to_many: if field.rel.to is Site: try: object_domain = getattr(obj, field.name).all()[0].domain except IndexError: pass if object_domain is not None: break # Next look for a many-to-one relationship to site if object_domain is None: for field in obj._meta.fields: if field.rel and field.rel.to is Site: try: object_domain = getattr(obj, field.name).domain except Site.DoesNotExist: pass if object_domain is not None: break # Fall back to the current site (if possible) if object_domain is None: try: object_domain = Site.objects.get_current().domain except Site.DoesNotExist: pass # If all that malarkey found an object domain, use it; otherwise fall back # to whatever get_absolute_url() returned. if object_domain is not None: return http.HttpResponseRedirect('http://%s%s' % (object_domain, absurl)) else: return http.HttpResponseRedirect(absurl)
ObjectDoesNotExist
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/views/defaults.py/shortcut
3,270
def create_argument_parser(self): """ Create a parser for the command-line options. May be overwritten for adding more configuration options. @return: an argparse.ArgumentParser instance """ parser = argparse.ArgumentParser( fromfile_prefix_chars='@', description= """Execute benchmarks for a given tool with a set of input files. Benchmarks are defined in an XML file given as input. Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument. The tool table-generator can be used to create tables for the results. Part of BenchExec: https://github.com/sosy-lab/benchexec/""") parser.add_argument("files", nargs='+', metavar="FILE", help="XML file with benchmark definition") parser.add_argument("-d", "--debug", action="store_true", help="Enable debug output and a debugging helper on signal USR1") parser.add_argument("-r", "--rundefinition", dest="selected_run_definitions", action="append", help="Run only the specified RUN_DEFINITION from the benchmark definition file. " + "This option can be specified several times and can contain wildcards.", metavar="RUN_DEFINITION") parser.add_argument("-t", "--tasks", dest="selected_sourcefile_sets", action="append", help="Run only the tasks from the tasks tag with TASKS as name. " + "This option can be specified several times and can contain wildcards.", metavar="TASKS") parser.add_argument("-n", "--name", dest="name", default=None, help="Set name of benchmark execution to NAME", metavar="NAME") parser.add_argument("-o", "--outputpath", dest="output_path", type=str, default=self.DEFAULT_OUTPUT_PATH, help="Output prefix for the generated results. " + "If the path is a folder files are put into it," + "otherwise it is used as a prefix for the resulting files.") parser.add_argument("-T", "--timelimit", dest="timelimit", default=None, help='Time limit for each run, e.g. "90s" ' '(overwrites time limit and hard time limit from XML file, ' 'use "-1" to disable time limits completely)', metavar="SECONDS") parser.add_argument("-M", "--memorylimit", dest="memorylimit", default=None, help="Memory limit, if no unit is given MB are assumed (-1 to disable)", metavar="BYTES") parser.add_argument("-N", "--numOfThreads", dest="num_of_threads", default=None, type=int, help="Run n benchmarks in parallel", metavar="n") parser.add_argument("-c", "--limitCores", dest="corelimit", default=None, metavar="N", help="Limit each run of the tool to N CPU cores (-1 to disable).") parser.add_argument("--user", dest="users", action="append", metavar="USER", help="Execute benchmarks under given user account(s) (needs password-less sudo setup).") parser.add_argument("--no-compress-results", dest="compress_results", action="store_false", help="Do not compress result files.") def parse_filesize_value(value): try: value = int(value) if value == -1: return None logging.warning( 'Value "%s" for logfile size interpreted as MB for backwards compatibility, ' 'specify a unit to make this unambiguous.', value) value = value * _BYTE_FACTOR * _BYTE_FACTOR except __HOLE__: value = util.parse_memory_value(value) return value parser.add_argument("--maxLogfileSize", dest="maxLogfileSize", type=parse_filesize_value, default=20*_BYTE_FACTOR*_BYTE_FACTOR, metavar="SIZE", help="Shrink logfiles to given size if they are too big. " "(-1 to disable, default value: 20 MB).") parser.add_argument("--commit", dest="commit", action="store_true", help="If the output path is a git repository without local changes, " + "add and commit the result files.") parser.add_argument("--message", dest="commit_message", type=str, default="Results for benchmark run", help="Commit message if --commit is used.") parser.add_argument("--startTime", dest="start_time", type=parse_time_arg, default=None, metavar="'YYYY-MM-DD hh:mm'", help='Set the given date and time as the start time of the benchmark.') parser.add_argument("--version", action="version", version="%(prog)s " + __version__) return parser
ValueError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/benchexec.py/BenchExec.create_argument_parser
3,271
def execute_benchmark(self, benchmark_file): """ Execute a single benchmark as defined in a file. If called directly, ensure that config and executor attributes are set up. @param benchmark_file: the name of a benchmark-definition XML file @return: a result value from the executor module """ benchmark = Benchmark(benchmark_file, self.config, self.config.start_time or time.localtime()) self.check_existing_results(benchmark) self.executor.init(self.config, benchmark) output_handler = OutputHandler(benchmark, self.executor.get_system_info(), self.config.compress_results) logging.debug("I'm benchmarking %r consisting of %s run sets.", benchmark_file, len(benchmark.run_sets)) try: result = self.executor.execute_benchmark(benchmark, output_handler) finally: output_handler.close() # remove useless log folder if it is empty try: os.rmdir(benchmark.log_folder) except: pass if self.config.commit and not self.stopped_by_interrupt: try: util.add_files_to_git_repository(self.config.output_path, output_handler.all_created_files, self.config.commit_message+'\n\n'+output_handler.description) except __HOLE__ as e: logging.warning('Could not add files to git repository: %s', e) return result
OSError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/benchexec.py/BenchExec.execute_benchmark
3,272
def parse_time_arg(s): """ Parse a time stamp in the "year-month-day hour-minute" format. """ try: return time.strptime(s, "%Y-%m-%d %H:%M") except __HOLE__ as e: raise argparse.ArgumentTypeError(e)
ValueError
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/benchexec.py/parse_time_arg
3,273
def main(benchexec=None, argv=None): """ The main method of BenchExec for use in a command-line script. In addition to calling benchexec.start(argv), it also handles signals and keyboard interrupts. It does not return but calls sys.exit(). @param benchexec: An instance of BenchExec for executing benchmarks. @param argv: optionally the list of command-line options to use """ if sys.version_info < (3,): sys.exit('benchexec needs Python 3 to run.') # ignore SIGTERM signal.signal(signal.SIGTERM, signal_handler_ignore) try: if not benchexec: benchexec = BenchExec() sys.exit(benchexec.start(argv or sys.argv)) except __HOLE__: # this block is reached, when interrupt is thrown before or after a run set execution benchexec.stop() util.printOut("\n\nScript was interrupted by user, some runs may not be done.")
KeyboardInterrupt
dataset/ETHPy150Open sosy-lab/benchexec/benchexec/benchexec.py/main
3,274
def resolve_common_type(parser, commontype): try: return _CACHE[commontype] except __HOLE__: cdecl = COMMON_TYPES.get(commontype, commontype) if not isinstance(cdecl, str): result, quals = cdecl, 0 # cdecl is already a BaseType elif cdecl in model.PrimitiveType.ALL_PRIMITIVE_TYPES: result, quals = model.PrimitiveType(cdecl), 0 elif cdecl == 'set-unicode-needed': raise api.FFIError("The Windows type %r is only available after " "you call ffi.set_unicode()" % (commontype,)) else: if commontype == cdecl: raise api.FFIError("Unsupported type: %r. Please file a bug " "if you think it should be." % (commontype,)) result, quals = parser.parse_type_and_quals(cdecl) # recursive assert isinstance(result, model.BaseTypeByIdentity) _CACHE[commontype] = result, quals return result, quals # ____________________________________________________________ # extra types for Windows (most of them are in commontypes.c)
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cffi-1.5.2/cffi/commontypes.py/resolve_common_type
3,275
def losetup_detach_all(root_path): """ Detach all loop devices associated with files contained in ``root_path``. :param FilePath root_path: A directory in which to search for loop device backing files. """ for device_file, backing_file in _losetup_list(): try: backing_file.segmentsFrom(root_path) except __HOLE__: pass else: losetup_detach(device_file)
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/test/test_blockdevice.py/losetup_detach_all
3,276
def setup_key_pair(self, context): key_name = '%s%s' % (context.project_id, CONF.vpn_key_suffix) try: keypair_api = compute.api.KeypairAPI() result, private_key = keypair_api.create_key_pair(context, context.user_id, key_name) key_dir = os.path.join(CONF.keys_path, context.user_id) fileutils.ensure_tree(key_dir) key_path = os.path.join(key_dir, '%s.pem' % key_name) with open(key_path, 'w') as f: f.write(private_key) except (exception.KeyPairExists, os.error, __HOLE__): pass return key_name
IOError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cloudpipe/pipelib.py/CloudPipe.setup_key_pair
3,277
def setup_server(args): with open(args.config, 'r') as config_stream: config = yaml.safe_load(config_stream) if not config['debug_log']: # NOTE(mikal): debug logging _must_ be enabled for the log writing # in lib.utils.execute_to_log to work correctly. raise Exception('Debug log not configured') server = worker_server.Server(config) server.setup_logging(config['debug_log']) def term_handler(signum, frame): server.shutdown() signal.signal(signal.SIGTERM, term_handler) if args.background: server.daemon = True server.start() while not server.stopped(): try: time.sleep(3) except __HOLE__: print "Ctrl + C: asking tasks to exit nicely...\n" server.shutdown()
KeyboardInterrupt
dataset/ETHPy150Open openstack/turbo-hipster/turbo_hipster/cmd/server.py/setup_server
3,278
def qweqwe( PID, SHELLCODE): try: from ctypes import * except __HOLE__ as error: return False page_rwx_value = 0x40 process_all = 0x1F0FFF memcommit = 0x00001000 SHELLCODE = SHELLCODE.replace("\\x", "").decode("hex") print PID,SHELLCODE try: kernel = windll.kernel32 process_id = PID shellcode_length = len(SHELLCODE) process_handle = kernel.OpenProcess(process_all, False, process_id) memory_allocation_variable = kernel.VirtualAllocEx(process_handle, 0, shellcode_length, memcommit, page_rwx_value) kernel.WriteProcessMemory(process_handle, memory_allocation_variable, SHELLCODE, shellcode_length, 0) kernel.CreateRemoteThread(process_handle, None, 0, memory_allocation_variable, 0, 0, 0) except Exception as error: print "Unexpected error : %s " % error
ImportError
dataset/ETHPy150Open b3mb4m/shellsploit-framework/shell/inject/Windows/dllinjector.py/qweqwe
3,279
def get_geo_db(): """ Finds and caches a maxmind database for GeoIP2 from http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz :return: geoip2.database.Reader object """ # Pull everything off the internet if it isn't cached geofilename = 'cache/GeoLite2-City.mmdb' url = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz' gzipfile = 'cache/GeoLite2-City.mmdb.gz' if os.path.isfile(geofilename): try: reader = geoip2.database.Reader(geofilename) except ValueError as e: raise Exception("Error accessing GeoLite database: %s" % e) except maxminddb.errors.InvalidDatabaseError as e: raise Exception("Invalid DB error %s - %s " % (geofilename, e)) return reader else: try: print("Maxmind database not cached. Attempting to pull from {0}".format(url)) download_file(url, gzipfile) except requests.ConnectionError: e = sys.exc_info()[0] print('Connection interrupted while downloading Maxmind Database: {0} - {1}'.format(url, e)) except __HOLE__: e = sys.exc_info()[0] print('Error downloading Maxmind Database: %s - %s'.format(url, e)) # Open Gzip f = gzip.open(gzipfile, 'rb') maxmind = f.read() f.close() # Re-Write uncompressed format f = open(geofilename, 'wb') f.write(maxmind) f.close() # Wrap up reader = geoip2.database.Reader(geofilename) return reader
IOError
dataset/ETHPy150Open jpsenior/threataggregator/threataggregator.py/get_geo_db
3,280
def build_db(dbtype, url, description, db_add, db_del, db_equal): """ Builds reputation database entry based on type Assumes default type 'ipfeed' :param string dbtype: User-specified 'type' for feed name. Constructs filename :param string url: URLLib http GET url to obtain threat entries :param string description: User description of threat feed :param db_add: Entry database for 'new' items :param db_del Entry database for 'new' items :param db_equal: Entry database for 'new' items :return: """ old_filename = 'cache/%s.txt' % dbtype new_filename = 'cache/%s.txt.compare_add' % dbtype if not os.path.exists('cache'): os.makedirs('cache') try: download_file(url, new_filename) except requests.ConnectionError as e: print('Connection interrupted while downloading: {0} - {1}'.format(url, e)) # If there's a problem just keep going. return except IOError: e = sys.exc_info()[0] print('Error downloading: {0} - {1}'.format(url, e)) raise IOError('Something happened {0}'.format(e)) if os.path.isfile(new_filename): with open(new_filename, 'r') as fn: compare_add = fn.read().splitlines() else: compare_add = [] if os.path.isfile(old_filename): with open(old_filename, 'r') as fn: compare_delete = fn.read().splitlines() else: compare_delete = [] print('Comparing {0} downloaded to {1} cached lines'.format(len(compare_add), len(compare_delete))) compare = BuildCompare(compare_delete, compare_add) compare_delete = compare.delete compare_add = compare.add compare_equal = compare.equal print("{0} new, {1} deleted, {2} unchanged lines".format(len(compare_add), len(compare_delete), len(compare_equal))) if dbtype == 'alienvault': db_del.append(alienvault(url, compare_delete)) db_add.append(alienvault(url, compare_add)) db_equal.append(alienvault(url, compare_equal)) elif dbtype == 'emerging-block': db_del.append(emergingthreat(url, compare_delete)) db_add.append(emergingthreat(url, compare_add)) db_equal.append(emergingthreat(url, compare_equal)) elif dbtype == 'ssl-blacklist': db_del.append(sslblacklist(url, compare_delete)) db_add.append(sslblacklist(url, compare_add)) db_equal.append(sslblacklist(url, compare_equal)) elif dbtype == 'ssl-blacklist': db_del.append(autoshun(url, compare_delete)) db_add.append(autoshun(url, compare_add)) db_equal.append(autoshun(url, compare_equal)) else: db_del.append(ipfeed(url, description, compare_delete)) db_add.append(ipfeed(url, description, compare_add)) db_equal.append(ipfeed(url, description, compare_equal)) if not os.path.exists('cache'): os.makedirs('cache') if os.path.isfile(old_filename): try: os.remove(old_filename) except (__HOLE__, OSError) as e: raise OSError('Could not remove file: {0}- {1}'.format(old_filename, e)) try: os.rename(new_filename, old_filename) except (IOError, OSError) as e: raise OSError('Could not rename {0} to {1} - {2}'.format(new_filename, old_filename, e))
IOError
dataset/ETHPy150Open jpsenior/threataggregator/threataggregator.py/build_db
3,281
def create_service_type(apps, schema_editor): service_types = { 1: 'OpenStack', 2: 'DigitalOcean', 3: 'Amazon', 4: 'Jira', 5: 'GitLab', 6: 'Oracle', 7: 'Azure', 8: 'SugarCRM', 9: 'SaltStack', 10: 'Zabbix' } ServiceSettings = apps.get_model('structure', 'ServiceSettings') for service in ServiceSettings.objects.all(): try: service.service_type = service_types[service.type] service.save() except __HOLE__: if service.type in service_types.values(): service.service_type = service.type service.save() else: logger.warning('Cannot migrate service type %s' % service.type)
KeyError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/structure/migrations/0028_servicesettings_service_type2.py/create_service_type
3,282
def read_po(fileobj, locale=None, domain=None, ignore_obsolete=False): """Read messages from a ``gettext`` PO (portable object) file from the given file-like object and return a `Catalog`. >>> from StringIO import StringIO >>> buf = StringIO(''' ... #: main.py:1 ... #, fuzzy, python-format ... msgid "foo %(name)s" ... msgstr "" ... ... # A user comment ... #. An auto comment ... #: main.py:3 ... msgid "bar" ... msgid_plural "baz" ... msgstr[0] "" ... msgstr[1] "" ... ''') >>> catalog = read_po(buf) >>> catalog.revision_date = datetime(2007, 04, 01) >>> for message in catalog: ... if message.id: ... print (message.id, message.string) ... print ' ', (message.locations, message.flags) ... print ' ', (message.user_comments, message.auto_comments) (u'foo %(name)s', '') ([(u'main.py', 1)], set([u'fuzzy', u'python-format'])) ([], []) ((u'bar', u'baz'), ('', '')) ([(u'main.py', 3)], set([])) ([u'A user comment'], [u'An auto comment']) :param fileobj: the file-like object to read the PO file from :param locale: the locale identifier or `Locale` object, or `None` if the catalog is not bound to a locale (which basically means it's a template) :param domain: the message domain :param ignore_obsolete: whether to ignore obsolete messages in the input :return: a catalog object representing the parsed PO file :rtype: `Catalog` """ catalog = Catalog(locale=locale, domain=domain) counter = [0] offset = [0] messages = [] translations = [] locations = [] flags = [] user_comments = [] auto_comments = [] obsolete = [False] context = [] in_msgid = [False] in_msgstr = [False] in_msgctxt = [False] def _add_message(): translations.sort() if len(messages) > 1: msgid = tuple([denormalize(m) for m in messages]) else: msgid = denormalize(messages[0]) if isinstance(msgid, (list, tuple)): string = [] for idx in range(catalog.num_plurals): try: string.append(translations[idx]) except IndexError: string.append((idx, '')) string = tuple([denormalize(t[1]) for t in string]) else: string = denormalize(translations[0][1]) if context: msgctxt = denormalize('\n'.join(context)) else: msgctxt = None message = Message(msgid, string, list(locations), set(flags), auto_comments, user_comments, lineno=offset[0] + 1, context=msgctxt) if obsolete[0]: if not ignore_obsolete: catalog.obsolete[msgid] = message else: catalog[msgid] = message del messages[:]; del translations[:]; del context[:]; del locations[:]; del flags[:]; del auto_comments[:]; del user_comments[:]; obsolete[0] = False counter[0] += 1 def _process_message_line(lineno, line): if line.startswith('msgid_plural'): in_msgid[0] = True msg = line[12:].lstrip() messages.append(msg) elif line.startswith('msgid'): in_msgid[0] = True offset[0] = lineno txt = line[5:].lstrip() if messages: _add_message() messages.append(txt) elif line.startswith('msgstr'): in_msgid[0] = False in_msgstr[0] = True msg = line[6:].lstrip() if msg.startswith('['): idx, msg = msg[1:].split(']') translations.append([int(idx), msg.lstrip()]) else: translations.append([0, msg]) elif line.startswith('msgctxt'): if messages: _add_message() in_msgid[0] = in_msgstr[0] = False context.append(line[7:].lstrip()) elif line.startswith('"'): if in_msgid[0]: messages[-1] += u'\n' + line.rstrip() elif in_msgstr[0]: translations[-1][1] += u'\n' + line.rstrip() elif in_msgctxt[0]: context.append(line.rstrip()) for lineno, line in enumerate(fileobj.readlines()): line = line.strip() if not isinstance(line, unicode): line = line.decode(catalog.charset) if line.startswith('#'): in_msgid[0] = in_msgstr[0] = False if messages and translations: _add_message() if line[1:].startswith(':'): for location in line[2:].lstrip().split(): pos = location.rfind(':') if pos >= 0: try: lineno = int(location[pos + 1:]) except __HOLE__: continue locations.append((location[:pos], lineno)) elif line[1:].startswith(','): for flag in line[2:].lstrip().split(','): flags.append(flag.strip()) elif line[1:].startswith('~'): obsolete[0] = True _process_message_line(lineno, line[2:].lstrip()) elif line[1:].startswith('.'): # These are called auto-comments comment = line[2:].strip() if comment: # Just check that we're not adding empty comments auto_comments.append(comment) else: # These are called user comments user_comments.append(line[1:].strip()) else: _process_message_line(lineno, line) if messages: _add_message() # No actual messages found, but there was some info in comments, from which # we'll construct an empty header message elif not counter[0] and (flags or user_comments or auto_comments): messages.append(u'') translations.append([0, u'']) _add_message() return catalog
ValueError
dataset/ETHPy150Open IanLewis/kay/kay/lib/babel/messages/pofile.py/read_po
3,283
def write_po(fileobj, catalog, width=76, no_location=False, omit_header=False, sort_output=False, sort_by_file=False, ignore_obsolete=False, include_previous=False): r"""Write a ``gettext`` PO (portable object) template file for a given message catalog to the provided file-like object. >>> catalog = Catalog() >>> catalog.add(u'foo %(name)s', locations=[('main.py', 1)], ... flags=('fuzzy',)) >>> catalog.add((u'bar', u'baz'), locations=[('main.py', 3)]) >>> from StringIO import StringIO >>> buf = StringIO() >>> write_po(buf, catalog, omit_header=True) >>> print buf.getvalue() #: main.py:1 #, fuzzy, python-format msgid "foo %(name)s" msgstr "" <BLANKLINE> #: main.py:3 msgid "bar" msgid_plural "baz" msgstr[0] "" msgstr[1] "" <BLANKLINE> <BLANKLINE> :param fileobj: the file-like object to write to :param catalog: the `Catalog` instance :param width: the maximum line width for the generated output; use `None`, 0, or a negative number to completely disable line wrapping :param no_location: do not emit a location comment for every message :param omit_header: do not include the ``msgid ""`` entry at the top of the output :param sort_output: whether to sort the messages in the output by msgid :param sort_by_file: whether to sort the messages in the output by their locations :param ignore_obsolete: whether to ignore obsolete messages and not include them in the output; by default they are included as comments :param include_previous: include the old msgid as a comment when updating the catalog """ def _normalize(key, prefix=''): return normalize(key, prefix=prefix, width=width) \ .encode(catalog.charset, 'backslashreplace') def _write(text): if isinstance(text, unicode): text = text.encode(catalog.charset) fileobj.write(text) def _write_comment(comment, prefix=''): # xgettext always wraps comments even if --no-wrap is passed; # provide the same behaviour if width and width > 0: _width = width else: _width = 76 for line in wraptext(comment, _width): _write('#%s %s\n' % (prefix, line.strip())) def _write_message(message, prefix=''): if isinstance(message.id, (list, tuple)): if message.context: _write('%smsgctxt %s\n' % (prefix, _normalize(message.context, prefix))) _write('%smsgid %s\n' % (prefix, _normalize(message.id[0], prefix))) _write('%smsgid_plural %s\n' % ( prefix, _normalize(message.id[1], prefix) )) for idx in range(catalog.num_plurals): try: string = message.string[idx] except __HOLE__: string = '' _write('%smsgstr[%d] %s\n' % ( prefix, idx, _normalize(string, prefix) )) else: if message.context: _write('%smsgctxt %s\n' % (prefix, _normalize(message.context, prefix))) _write('%smsgid %s\n' % (prefix, _normalize(message.id, prefix))) _write('%smsgstr %s\n' % ( prefix, _normalize(message.string or '', prefix) )) messages = list(catalog) if sort_output: messages.sort() elif sort_by_file: messages.sort(lambda x,y: cmp(x.locations, y.locations)) for message in messages: if not message.id: # This is the header "message" if omit_header: continue comment_header = catalog.header_comment if width and width > 0: lines = [] for line in comment_header.splitlines(): lines += wraptext(line, width=width, subsequent_indent='# ') comment_header = u'\n'.join(lines) + u'\n' _write(comment_header) for comment in message.user_comments: _write_comment(comment) for comment in message.auto_comments: _write_comment(comment, prefix='.') if not no_location: locs = u' '.join([u'%s:%d' % (filename.replace(os.sep, '/'), lineno) for filename, lineno in message.locations]) _write_comment(locs, prefix=':') if message.flags: _write('#%s\n' % ', '.join([''] + list(message.flags))) if message.previous_id and include_previous: _write_comment('msgid %s' % _normalize(message.previous_id[0]), prefix='|') if len(message.previous_id) > 1: _write_comment('msgid_plural %s' % _normalize( message.previous_id[1] ), prefix='|') _write_message(message) _write('\n') if not ignore_obsolete: for message in catalog.obsolete.values(): for comment in message.user_comments: _write_comment(comment) _write_message(message, prefix='#~ ') _write('\n')
IndexError
dataset/ETHPy150Open IanLewis/kay/kay/lib/babel/messages/pofile.py/write_po
3,284
def getbody(file, **options): # get clean body from text file # get xhtml tree try: tree = apply(tidy, (file,), options) if tree is None: return except __HOLE__, v: print "***", v return None NS = NS_XHTML # remove namespace uris for node in tree.getiterator(): if node.tag.startswith(NS): node.tag = node.tag[len(NS):] body = tree.getroot().find("body") return body ## # Same as <b>getbody</b>, but turns plain text at the start of the # document into an H1 tag. This function can be used to parse zone # documents. # # @param file Filename. # @return A <b>body</b> element, or None if not successful.
IOError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/elementtree/TidyTools.py/getbody
3,285
def db_version(): repo_path = _find_migrate_repo() try: return versioning_api.db_version(FLAGS.sql_connection, repo_path) except versioning_exceptions.DatabaseNotControlledError: # If we aren't version controlled we may already have the database # in the state from before we started version control, check for that # and set up version_control appropriately meta = sqlalchemy.MetaData() engine = sqlalchemy.create_engine(FLAGS.sql_connection, echo=False) meta.reflect(bind=engine) try: for table in ('auth_tokens', 'zones', 'export_devices', 'fixed_ips', 'floating_ips', 'instances', 'key_pairs', 'networks', 'projects', 'quotas', 'security_group_instance_association', 'security_group_rules', 'security_groups', 'services', 'migrations', 'users', 'user_project_association', 'user_project_role_association', 'user_role_association', 'virtual_storage_arrays', 'volumes', 'volume_metadata', 'volume_types', 'volume_type_extra_specs'): assert table in meta.tables return db_version_control(1) except __HOLE__: return db_version_control(0)
AssertionError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/db/sqlalchemy/migration.py/db_version
3,286
def db_version_dodai(): repo_path = _find_migrate_repo_dodai() try: return versioning_api.db_version(FLAGS.sql_connection_dodai, repo_path) except versioning_exceptions.DatabaseNotControlledError: # If we aren't version controlled we may already have the database # in the state from before we started version control, check for that # and set up version_control appropriately meta = sqlalchemy.MetaData() engine = sqlalchemy.create_engine(FLAGS.sql_connection_dodai, echo=False) meta.reflect(bind=engine) try: for table in ("bare_metal_machines"): assert table in meta.tables return db_version_control_dodai(1) except __HOLE__: return db_version_control_dodai(0)
AssertionError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/db/sqlalchemy/migration.py/db_version_dodai
3,287
def test_read_pypirc(self): # Guard to make sure we don't write an actual file by mistake try: fp = open(op.join(op.expanduser("~"), ".pypirc"), "rt") fp.close() raise ValueError() except __HOLE__: pass fp = open(op.join(op.expanduser("~"), ".pypirc"), "wt") try: fp.write("") finally: fp.close()
IOError
dataset/ETHPy150Open cournape/Bento/bento/pypi/tests/test_register_utils.py/TestReadPyPIDefault.test_read_pypirc
3,288
def post(self, request, *args, **kwargs): if not request.is_ajax(): return self._dispatch_super(request, *args, **kwargs) try: in_data = json.loads(request.body.decode('utf-8')) except __HOLE__: in_data = request.body.decode('utf-8') if 'action' in in_data: warnings.warn("Using the keyword 'action' inside the payload is deprecated. Please use 'djangoRMI' from module 'djng.forms'", DeprecationWarning) remote_method = in_data.pop('action') else: remote_method = request.META.get('HTTP_DJNG_REMOTE_METHOD') handler = remote_method and getattr(self, remote_method, None) if not callable(handler): return self._dispatch_super(request, *args, **kwargs) if not hasattr(handler, 'allow_rmi'): return HttpResponseForbidden("Method '{0}.{1}' has no decorator '@allow_remote_invocation'" .format(self.__class__.__name__, remote_method), 403) try: response_data = handler(in_data) except JSONResponseException as e: return self.json_response({'message': e.args[0]}, e.status_code) return self.json_response(response_data)
ValueError
dataset/ETHPy150Open jrief/django-angular/djng/views/mixins.py/JSONResponseMixin.post
3,289
def _percent_encode(self, request, encoding=None): encoding = encoding or sys.stdin.encoding or DEFAULT_ENCODING try: s = unicode(request, encoding) except __HOLE__: if not isinstance(request, unicode): # We accept int etc. types as well s = unicode(request) else: s = request res = urllib.quote( s.encode('utf8'), safe='~') return res
TypeError
dataset/ETHPy150Open quixey/python-aliyun/aliyun/connection.py/Connection._percent_encode
3,290
def get_format_info(self): """Returns format information. """ if self.active_formats == True: return { "product_cols": self.product_cols, "product_rows": self.product_rows } else: try: # TODO: Use cache here. Maybe we need a lfs_get_object, # which raise a ObjectDoesNotExist if the object does not # exist from lfs.core.models import Shop shop = Shop.objects.get(pk=1) except __HOLE__: return { "product_cols": 3, "product_rows": 3 } else: return { "product_cols": shop.product_cols, "product_rows": shop.product_rows }
ObjectDoesNotExist
dataset/ETHPy150Open diefenbach/django-lfs/lfs/manufacturer/models.py/Manufacturer.get_format_info
3,291
def take_action(self, parsed_args): if parsed_args.distribution: LOG.debug( 'Loading %s from %s using distribution %s', parsed_args.name, parsed_args.group, parsed_args.distribution, ) dist = pkg_resources.get_distribution(parsed_args.distribution) ep = pkg_resources.get_entry_info( dist, parsed_args.group, parsed_args.name, ) else: LOG.debug( 'Looking for %s in group %s', parsed_args.name, parsed_args.group, ) try: ep = pkg_resources.iter_entry_points( parsed_args.group, parsed_args.name, ).next() except __HOLE__: raise ValueError('Could not find %r in %r' % ( parsed_args.name, parsed_args.group, )) try: ep.load() except Exception: tb = traceback.format_exception(*sys.exc_info()) else: tb = '' return ( ('Module', 'Member', 'Distribution', 'Path', 'Error'), (ep.module_name, '.'.join(ep.attrs), str(ep.dist), ep.dist.location, tb), )
StopIteration
dataset/ETHPy150Open dhellmann/entry_point_inspector/entry_point_inspector/ep.py/EntryPointShow.take_action
3,292
def intCol(elt, attrName, default=None): try: return int(elt.get(attrName, default)) except (__HOLE__, ValueError): return default
TypeError
dataset/ETHPy150Open Arelle/Arelle/arelle/examples/SaveTableToExelle.py/intCol
3,293
def saveTableToExelle(rFilesDir): # get reports from FilingSummary reports = [] try: fsdoc = etree.parse(os.path.join(rFilesDir, "FilingSummary.xml")) for rElt in fsdoc.iter(tag="Report"): reports.append(Report(rElt.findtext("LongName"), rElt.findtext("ShortName"), rElt.findtext("HtmlFileName"))) except (EnvironmentError, etree.LxmlError) as err: print("FilingSummary.xml: directory {0} error: {1}".format(rFilesDir, err)) wb = Workbook(encoding='utf-8') # remove predefined sheets for sheetName in wb.get_sheet_names(): ws = wb.get_sheet_by_name(sheetName) if ws is not None: wb.remove_sheet(ws) sheetNames = set() # prevent duplicates for reportNum, report in enumerate(reports): sheetName = report.shortName[:31] # max length 31 for excel title if sheetName in sheetNames: sheetName = sheetName[:31-len(str(reportNum))] + str(reportNum) sheetNames.add(sheetName) ws = wb.create_sheet(title=sheetName) try: # doesn't detect utf-8 encoding the normal way, pass it a string #htmlSource = '' #with open(os.path.join(rFilesDir, report.htmlFileName), 'rt', encoding='utf-8') as fh: # htmlSource = fh.read() #rdoc = html.document_fromstring(htmlSource) rdoc = html.parse(os.path.join(rFilesDir, report.htmlFileName)) row = -1 mergedAreas = {} # colNumber: (colspan,lastrow) for tableElt in rdoc.iter(tag="table"): # skip pop up tables if tableElt.get("class") == "authRefData": continue if tableElt.getparent().tag == "div": style = tableElt.getparent().get("style") if style and displayNonePattern.match(style): continue colWidths = {} for rowNum, trElt in enumerate(tableElt.iter(tag="tr")): # remove passed mergedAreas for mergeCol in [col for col, mergedArea in mergedAreas.items() if mergedArea[1] > rowNum]: del mergedAreas[mergeCol] col = 0 for coltag in ("th", "td"): for cellElt in trElt.iter(tag=coltag): if col == 0: row += 1 # new row if col in mergedAreas: col += mergedAreas[col][0] - 1 text = cellElt.text_content() colspan = intCol(cellElt, "colspan", 1) rowspan = intCol(cellElt, "rowspan", 1) #if col not in colWidths: # colWidths[col] = 10.0 # some kind of default width for elt in cellElt.iter(): style = elt.get("style") if style and "width:" in style: try: kw, sep, width = style.partition("width:") if "px" in width: width, sep, kw = width.partition("px") width = float(width) * 0.67777777 else: width = float(width) colWidths[col] = width except __HOLE__: pass if rowspan > 1: mergedAreas[col] = (colspan, row + rowspan - 1) cell = ws.cell(row=row,column=col) if text: cell.value = text if numberPattern.match(text): cell.style.alignment.horizontal = Alignment.HORIZONTAL_RIGHT else: cell.style.alignment.wrap_text = True if colspan > 1 or rowspan > 1: ws.merge_cells(start_row=row, end_row=row+rowspan-1, start_column=col, end_column=col+colspan-1) cell.style.alignment.vertical = Alignment.VERTICAL_TOP if coltag == "th": cell.style.alignment.horizontal = Alignment.HORIZONTAL_CENTER cell.style.font.bold = True cell.style.font.size = 9 # some kind of default size col += colspan for col, width in colWidths.items(): ws.column_dimensions[get_column_letter(col+1)].width = width except (EnvironmentError, etree.LxmlError) as err: print("{0}: directory {1} error: {2}".format(report.htmlFileName, rFilesDir, err)) wb.save(os.path.join(rFilesDir, "exelleOut.xlsx"))
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/examples/SaveTableToExelle.py/saveTableToExelle
3,294
def mkdirs(path): try: os.makedirs(path) except __HOLE__ as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
OSError
dataset/ETHPy150Open wooey/Wooey/wooey/backend/utils.py/mkdirs
3,295
def create_job_fileinfo(job): parameters = job.get_parameters() from ..models import WooeyFile, UserFile # first, create a reference to things the script explicitly created that is a parameter files = [] local_storage = get_storage(local=True) for field in parameters: try: if field.parameter.form_field == 'FileField': value = field.value if value is None: continue if isinstance(value, six.string_types): # check if this was ever created and make a fileobject if so if local_storage.exists(value): if not get_storage(local=False).exists(value): get_storage(local=False).save(value, File(local_storage.open(value))) value = field.value else: field.force_value(None) try: with transaction.atomic(): field.save() except: sys.stderr.write('{}\n'.format(traceback.format_exc())) continue d = {'parameter': field, 'file': value} if field.parameter.is_output: full_path = os.path.join(job.save_path, os.path.split(local_storage.path(value))[1]) checksum = get_checksum(value, extra=[job.pk, full_path, 'output']) d['checksum'] = checksum files.append(d) except __HOLE__: continue known_files = {i['file'].name for i in files} # add the user_output files, these are things which may be missed by the model fields because the script # generated them without an explicit arguments reference in the script file_groups = {'archives': []} absbase = os.path.join(settings.MEDIA_ROOT, job.save_path) for root, dirs, dir_files in os.walk(absbase): for filename in dir_files: new_name = os.path.join(job.save_path, filename) if any([i.endswith(new_name) for i in known_files]): continue try: filepath = os.path.join(root, filename) if os.path.isdir(filepath): continue full_path = os.path.join(job.save_path, filename) # this is to make the job output have a unique checksum. If this file is then re-uploaded, it will create # a new file to reference in the uploads directory and not link back to the job output. checksum = get_checksum(filepath, extra=[job.pk, full_path, 'output']) try: storage_file = get_storage_object(full_path) except: sys.stderr.write('Error in accessing stored file {}:\n{}'.format(full_path, traceback.format_exc())) continue d = {'name': filename, 'file': storage_file, 'size_bytes': storage_file.size, 'checksum': checksum} if filename.endswith('.tar.gz') or filename.endswith('.zip'): file_groups['archives'].append(d) else: files.append(d) except IOError: sys.stderr.write('{}'.format(traceback.format_exc())) continue # establish grouping by inferring common things file_groups['all'] = files file_groups['image'] = [] file_groups['tabular'] = [] file_groups['fasta'] = [] for filemodel in files: fileinfo = get_file_info(filemodel['file'].path) filetype = fileinfo.get('type') if filetype is not None: file_groups[filetype].append(dict(filemodel, **{'preview': fileinfo.get('preview')})) else: filemodel['preview'] = json.dumps(None) # Create our WooeyFile models # mark things that are in groups so we don't add this to the 'all' category too to reduce redundancy grouped = set([i['file'].path for file_type, groups in six.iteritems(file_groups) for i in groups if file_type != 'all']) for file_type, group_files in six.iteritems(file_groups): for group_file in group_files: if file_type == 'all' and group_file['file'].path in grouped: continue try: preview = group_file.get('preview') size_bytes = group_file.get('size_bytes') filepath = group_file['file'].path save_path = job.get_relative_path(filepath) parameter = group_file.get('parameter') # get the checksum of the file to see if we need to save it checksum = group_file.get('checksum', get_checksum(filepath)) try: wooey_file = WooeyFile.objects.get(checksum=checksum) file_created = False except ObjectDoesNotExist: wooey_file = WooeyFile( checksum=checksum, filetype=file_type, filepreview=preview, size_bytes=size_bytes, filepath=save_path ) file_created = True userfile_kwargs = { 'job': job, 'parameter': parameter, 'system_file': wooey_file, 'filename': os.path.split(filepath)[1] } try: with transaction.atomic(): if file_created: wooey_file.save() job.save() UserFile.objects.get_or_create(**userfile_kwargs) except: sys.stderr.write('Error in saving DJFile: {}\n'.format(traceback.format_exc())) except: sys.stderr.write('Error in saving DJFile: {}\n'.format(traceback.format_exc())) continue
ValueError
dataset/ETHPy150Open wooey/Wooey/wooey/backend/utils.py/create_job_fileinfo
3,296
def get_grouped_file_previews(files): groups = {'all': []} for file_info in files: system_file = file_info.system_file filedict = {'id': system_file.id, 'object': system_file, 'name': file_info.filename, 'preview': json.loads(system_file.filepreview) if system_file.filepreview else None, 'url': get_storage(local=False).url(system_file.filepath.name), 'slug': file_info.parameter.parameter.script_param if file_info.parameter else None, 'basename': os.path.basename(system_file.filepath.name), 'filetype': system_file.filetype, 'size_bytes': system_file.size_bytes, } try: groups[system_file.filetype].append(filedict) except __HOLE__: groups[system_file.filetype] = [filedict] if system_file.filetype != 'all': groups['all'].append(filedict) return groups
KeyError
dataset/ETHPy150Open wooey/Wooey/wooey/backend/utils.py/get_grouped_file_previews
3,297
def get_payment_costs(request, payment_method): """ Returns the payment price and tax for the given request. """ if payment_method is None: return { "price": 0.0, "tax": 0.0 } try: tax_rate = payment_method.tax.rate except __HOLE__: tax_rate = 0.0 price = criteria_utils.get_first_valid(request, payment_method.prices.all()) # TODO: this assumes that payment price is given as gross price, we have to add payment processor here if price is None: price = payment_method.price tax = (tax_rate / (tax_rate + 100)) * price return { "price": price, "tax": tax } else: tax = (tax_rate / (tax_rate + 100)) * price.price return { "price": price.price, "tax": tax }
AttributeError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/payment/utils.py/get_payment_costs
3,298
def get_pay_link(request, payment_method, order): """ Creates a pay link for the passed payment_method and order. This can be used to display the link within the order mail and/or the thank you page after a customer has payed. """ from lfs.core.utils import import_symbol logger.info("Decprecated: lfs.payment.utils.get_pay_link: this function is deprecated. Please use Order.get_pay_link instead.") if payment_method.module: payment_class = import_symbol(payment_method.module) payment_instance = payment_class(request=request, order=order) try: return payment_instance.get_pay_link() except __HOLE__: return "" else: return ""
AttributeError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/payment/utils.py/get_pay_link
3,299
def executemany(self, sql, param_list): self.set_dirty() start = time() try: return self.cursor.executemany(sql, param_list) finally: stop = time() duration = stop - start try: times = len(param_list) except __HOLE__: # param_list could be an iterator times = '?' self.db.queries.append({ 'sql': '%s times: %s' % (times, sql), 'time': "%.3f" % duration, }) logger.debug('(%.3f) %s; args=%s' % (duration, sql, param_list), extra={'duration': duration, 'sql': sql, 'params': param_list} ) ############################################### # Converters from database (string) to Python # ###############################################
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/util.py/CursorDebugWrapper.executemany