Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,700
def setProperty(self, name, value): if name == 'voice': token = self._tokenFromId(value) self._tts.Voice = token a, b = E_REG.get(value, E_REG[MSMARY]) self._tts.Rate = int(math.log(self._rateWpm/a, b)) elif name == 'rate': id = self._tts.Voice...
TypeError
dataset/ETHPy150Open parente/pyttsx/pyttsx/drivers/sapi5.py/SAPI5Driver.setProperty
1,701
def memoize(fun): """A simple memoize decorator for functions supporting (hashable) positional arguments. It also provides a cache_clear() function for clearing the cache: >>> @memoize ... def foo() ... return 1 ... >>> foo() 1 >>> foo.cache_clear() >>> """ @func...
KeyError
dataset/ETHPy150Open giampaolo/psutil/psutil/_common.py/memoize
1,702
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except __HOLE__ as err: if err.errno in (errno.EPERM, errno.EACCES): ...
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_common.py/isfile_strict
1,703
def path_exists_strict(path): """Same as os.path.exists() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: os.stat(path) except __HOLE__ as err: if err.errno in (errno.EPERM, errno.EACCES): ...
OSError
dataset/ETHPy150Open giampaolo/psutil/psutil/_common.py/path_exists_strict
1,704
def sockfam_to_enum(num): """Convert a numeric socket family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressFamily(num) except (__HOLE__, ...
ValueError
dataset/ETHPy150Open giampaolo/psutil/psutil/_common.py/sockfam_to_enum
1,705
def socktype_to_enum(num): """Convert a numeric socket type value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressType(num) except (__HOLE__, Att...
ValueError
dataset/ETHPy150Open giampaolo/psutil/psutil/_common.py/socktype_to_enum
1,706
def get_model(self, file_path): """ Loads the model from okapi style file. >>> from pkg_resources import resource_filename >>> import testfm >>> path = resource_filename(testfm.__name__, "data/okapi.tsv") >>> okapi = Load_Okapi() >>> model = okapi.get_model(path) ...
KeyError
dataset/ETHPy150Open grafos-ml/test.fm/src/testfm/fmio/load_model.py/Load_Okapi.get_model
1,707
def getMessageFromUser(self, prompt=''): editor = os.environ.get("EDITOR", "/bin/vi") (fd, name) = tempfile.mkstemp() if not prompt: prompt = 'Enter your change log message.' msg = "\n-----\n%s\n" % prompt os.write(fd, msg) os.close(fd) def _getMessag...
OSError
dataset/ETHPy150Open sassoftware/conary/conary/changelog.py/ChangeLog.getMessageFromUser
1,708
def prof_leftup(self, event=None): if len(self.map.shape) != 2: return if self.rbbox is not None: zdc = wx.ClientDC(self.panel.canvas) zdc.SetLogicalFunction(wx.XOR) zdc.SetBrush(wx.TRANSPARENT_BRUSH) zdc.SetPen(wx.Pen('White', 2, wx.SOLID)) ...
AttributeError
dataset/ETHPy150Open xraypy/xraylarch/plugins/wx/mapimageframe.py/MapImageFrame.prof_leftup
1,709
def run(self): logger.info(u'Starting update loop.') try: while True: self.update() time.sleep(self.refresh_rate) except (KeyboardInterrupt, __HOLE__): pass except Exception as e: logger.exception(u"Found exception %s, e...
SystemExit
dataset/ETHPy150Open rbarrois/mpdlcd/mpdlcd/lcdrunner.py/MpdRunner.run
1,710
def gen_zonal_stats( vectors, raster, layer=0, band_num=1, nodata=None, affine=None, stats=None, all_touched=False, categorical=False, category_map=None, add_stats=None, raster_out=False, prefix=None, geojson_out=False, **kwargs): """Zonal statistics of raster val...
KeyError
dataset/ETHPy150Open perrygeo/python-rasterstats/src/rasterstats/main.py/gen_zonal_stats
1,711
def convert(self, value): value = _force_dict(value) errors = {} result = {} for name, field in self.fields.iteritems(): try: result[name] = field(value.get(name)) except __HOLE__, e: errors[name] = e if errors: ...
ValidationError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/Mapping.convert
1,712
def convert(self, value): value = self._remove_empty(_force_list(value)) if self.min_size is not None and len(value) < self.min_size: message = self.messages['too_small'] if message is None: message = self.ngettext( u'Please provide at least %d...
ValidationError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/Multiple.convert
1,713
def convert(self, value): if isinstance(value, datetime): return value value = _to_string(value) if not value: if self.required: message = self.messages['required'] if message is None: message = self.gettext(u'This field...
ValueError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/DateTimeField.convert
1,714
def convert(self, value): if isinstance(value, date): return value value = _to_string(value) if not value: if self.required: message = self.messages['required'] if message is None: message = self.gettext(u'This field is ...
ValueError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/DateField.convert
1,715
def convert(self, value): value = _to_string(value) if not value: if self.required: message = self.messages['required'] if message is None: message = self.gettext(u'This field is required.') raise ValidationError(message) ...
ValueError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/FloatField.convert
1,716
def convert(self, value): value = _to_string(value) if not value: if self.required: message = self.messages['required'] if message is None: message = self.gettext(u'This field is required.') raise ValidationError(message) ...
ValueError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/IntegerField.convert
1,717
def __get__(self, obj, type=None): try: return (obj or type).fields[self.name] except __HOLE__: raise AttributeError(self.name)
KeyError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/FieldDescriptor.__get__
1,718
def validate(self, data=None, from_flat=True): """Validate the form against the data passed. If no data is provided the form data of the current request is taken. By default a flat representation of the data is assumed. If you already have a non-flat representation of the data (JSON f...
ValidationError
dataset/ETHPy150Open mitsuhiko/fungiform/fungiform/forms.py/FormBase.validate
1,719
def handle_charref(self, name): # XXX workaround for a bug in HTMLParser. Remove this once # it's fixed in all supported versions. # http://bugs.python.org/issue13633 if name.startswith('x'): real_name = int(name.lstrip('x'), 16) elif name.startswith('X'): ...
ValueError
dataset/ETHPy150Open akalongman/sublimetext-codeformatter/codeformatter/lib/htmlbeautifier/bs4/builder/_htmlparser.py/BeautifulSoupHTMLParser.handle_charref
1,720
def test_cons_slicing(): """Check that cons slicing works as expected""" cons = HyCons("car", "cdr") assert cons[0] == "car" assert cons[1:] == "cdr" try: cons[:] assert True is False except IndexError: pass try: cons[1] assert True is False excep...
IndexError
dataset/ETHPy150Open hylang/hy/tests/models/test_cons.py/test_cons_slicing
1,721
def test_cons_replacing(): """Check that assigning to a cons works as expected""" cons = HyCons("foo", "bar") cons[0] = "car" assert cons == HyCons("car", "bar") cons[1:] = "cdr" assert cons == HyCons("car", "cdr") try: cons[:] = "foo" assert True is False except __HOL...
IndexError
dataset/ETHPy150Open hylang/hy/tests/models/test_cons.py/test_cons_replacing
1,722
def get_converter(self, x): 'get the converter interface instance for x, or None' if not len(self): return None # nothing registered #DISABLED idx = id(x) #DISABLED cached = self._cached.get(idx) #DISABLED if cached is not None: return cached converter = No...
AttributeError
dataset/ETHPy150Open nipy/nitime/nitime/_mpl_units.py/Registry.get_converter
1,723
def preBuildPage(self, site, page, context, data): """ Special call as we have changed the API for this. We have two calling conventions: - The new one, which passes page, context, data - The deprecated one, which also passes the site (Now accessible via the page) """ ...
NotImplementedError
dataset/ETHPy150Open koenbok/Cactus/cactus/plugin/manager.py/PluginManager.preBuildPage
1,724
@requires(str, 'uri') def fetch(self, environ, request, uri): args = { 'uri': uri, 'after': request.args.get('after', 0) } try: args['limit'] = int(request.args.get('limit')) except __HOLE__: args['limit'] = None except ValueE...
TypeError
dataset/ETHPy150Open posativ/isso/isso/views/comments.py/API.fetch
1,725
def __init__(self, walkers=100, **kwargs): try: import emcee except __HOLE__: raise ImportError("The emcee package needs to be installed in order to use EmceeSampler") self.emcee = emcee self.walkers = walkers super(EmceeSampler, self).__init__(**kwargs)
ImportError
dataset/ETHPy150Open tensorprob/tensorprob/tensorprob/samplers/emcee.py/EmceeSampler.__init__
1,726
def sample(self, variables, cost, gradient=None, samples=None): # Check if variables is iterable try: iter(variables) except __HOLE__: raise ValueError("Variables parameter is not iterable") inits = self.session.run(variables) for v in variables: ...
TypeError
dataset/ETHPy150Open tensorprob/tensorprob/tensorprob/samplers/emcee.py/EmceeSampler.sample
1,727
def startGraph(): # We maintain this globally to make it accessible, pylint: disable=W0603 global graph if Options.shouldCreateGraph(): try: from graphviz import Digraph # pylint: disable=F0401,I0021 graph = Digraph('G') except __HOLE__: warning("Cannot i...
ImportError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/optimizations/Graphs.py/startGraph
1,728
@unittest.skip("FIXME: broken") def test_avg_std(self): # Use integration to test distribution average and standard deviation. # Only works for distributions which do not consume variates in pairs g = random.Random() N = 5000 x = [i/float(N) for i in xrange(1,N)] for ...
IndexError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_random.py/TestDistributions.test_avg_std
1,729
def test_main(verbose=None): testclasses = [WichmannHill_TestBasicOps, MersenneTwister_TestBasicOps, TestDistributions, TestModule] if test_support.is_jython: del MersenneTwister_TestBasicOps.test_genrandbits del MersenneTwist...
NotImplementedError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_random.py/test_main
1,730
def write(data): """ Write data to STDOUT """ if not isinstance(data, str): data = json.dumps(data) sys.stdout.write(data) if not data.endswith('\n'): sys.stdout.write('\n') try: sys.stdout.flush() except __HOLE__: sys.exit()
IOError
dataset/ETHPy150Open srusskih/SublimeJEDI/sublime_jedi/daemon.py/write
1,731
def _parameters_for_completion(self): """ Get function / class' constructor parameters completions list :rtype: list of str """ completions = [] try: in_call = self.script.call_signatures()[0] except IndexError: in_call = None parameters ...
ValueError
dataset/ETHPy150Open srusskih/SublimeJEDI/sublime_jedi/daemon.py/JediFacade._parameters_for_completion
1,732
def _complete_call_assigments(self): """ Get function or class parameters and build Sublime Snippet string for completion :rtype: str """ completions = [] complete_all = auto_complete_function_params == 'all' try: call_definition = self.script.call_s...
ValueError
dataset/ETHPy150Open srusskih/SublimeJEDI/sublime_jedi/daemon.py/JediFacade._complete_call_assigments
1,733
def context_builder(request, **kwargs): ''' (request object, [kwargs...]) -> response dict Builds query via request item contents overriden by kwargs. links_from and instance properties ---------------------------------- * Request object SHOULD HAVE "links_from" property as string which holds ...
ValueError
dataset/ETHPy150Open linkfloyd/linkfloyd/linkfloyd/links/utils.py/context_builder
1,734
def ustr(s, encoding="utf-8"): """ Convert argument to unicode string. """ if isinstance(s, str): return s try: return s.decode(encoding) except __HOLE__: return str(s)
AttributeError
dataset/ETHPy150Open nigelsmall/py2neo/py2neo/compat.py/ustr
1,735
def __get__(self, instance, instance_type=None): try: return super(WidgyGenericForeignKey, self).__get__(instance, instance_type) except __HOLE__: # The model for this content type couldn't be loaded. Use an # UnknownWidget instead. from widgy.models impor...
AttributeError
dataset/ETHPy150Open fusionbox/django-widgy/widgy/generic/__init__.py/WidgyGenericForeignKey.__get__
1,736
def find_template(self, name, dirs=None): """ RemovedInDjango20Warning: An internal method to lookup the template name in all the configured loaders. """ key = self.cache_key(name, dirs) try: result = self.find_template_cache[key] except __HOLE__: ...
KeyError
dataset/ETHPy150Open django/django/django/template/loaders/cached.py/Loader.find_template
1,737
@staticmethod def lookup_class(xsi_type): try: return stix.lookup_extension(xsi_type, default=VocabString) except __HOLE__: return VocabString
ValueError
dataset/ETHPy150Open STIXProject/python-stix/stix/common/vocabs.py/VocabString.lookup_class
1,738
@property def path(self): """Return the config file path creating basedir, if needed.""" path = self._get_path() try: os.makedirs(os.path.dirname(path), mode=0o700) except __HOLE__ as e: if e.errno != errno.EEXIST: raise return path
OSError
dataset/ETHPy150Open jkbrzt/httpie/httpie/config.py/BaseConfigDict.path
1,739
def load(self): try: with open(self.path, 'rt') as f: try: data = json.load(f) except ValueError as e: raise ValueError( 'Invalid %s JSON: %s [%s]' % (type(self).__name__, str(e), ...
IOError
dataset/ETHPy150Open jkbrzt/httpie/httpie/config.py/BaseConfigDict.load
1,740
def delete(self): try: os.unlink(self.path) except __HOLE__ as e: if e.errno != errno.ENOENT: raise
OSError
dataset/ETHPy150Open jkbrzt/httpie/httpie/config.py/BaseConfigDict.delete
1,741
def _migrate_implicit_content_type(self): """Migrate the removed implicit_content_type config option""" try: implicit_content_type = self.pop('implicit_content_type') except __HOLE__: pass else: if implicit_content_type == 'form': self[...
KeyError
dataset/ETHPy150Open jkbrzt/httpie/httpie/config.py/Config._migrate_implicit_content_type
1,742
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False): if nodeName_ == 'Title': Title_ = child_.text Title_ = self.gds_validate_string(Title_, node, 'Title') self.Title = Title_ elif nodeName_ == 'Description': obj_ = stix_common_binding.St...
TypeError
dataset/ETHPy150Open STIXProject/python-stix/stix/bindings/exploit_target.py/VulnerabilityType.buildChildren
1,743
def addItemBefore(self, caption, icon, command, itemToAddBefore): """Add an item before some item. If the given item does not exist the item is added at the end of the menu. Icon and command can be null, but a caption must be given. @param caption: the text for the me...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/menu_bar.py/MenuBar.addItemBefore
1,744
def addItemBefore(self, caption, icon, command, itemToAddBefore): """Add an item before some item. If the given item does not exist the item is added at the end of the menu. Icon and command can be null, but a caption must be given. @param caption: the text for the me...
ValueError
dataset/ETHPy150Open rwl/muntjac/muntjac/ui/menu_bar.py/MenuItem.addItemBefore
1,745
@webapi_check_local_site @webapi_login_required @webapi_response_errors(DOES_NOT_EXIST, INVALID_FORM_DATA, NOT_LOGGED_IN, PERMISSION_DENIED) @webapi_request_fields( required=dict({ 'filediff_id': { 'type': int, 'description': 'T...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_diff_comment.py/ReviewDiffCommentResource.create
1,746
@webapi_check_local_site @webapi_login_required @webapi_response_errors(DOES_NOT_EXIST, NOT_LOGGED_IN, PERMISSION_DENIED) @webapi_request_fields( optional=dict({ 'first_line': { 'type': int, 'description': 'The line number the comment starts at.', ...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_diff_comment.py/ReviewDiffCommentResource.update
1,747
def __getitem__(self, key): """Return portion of self defined by key. If the key involves a slice then a list will be returned (if key is a single slice) or a matrix (if key was a tuple involving a slice). Examples ======== >>> from sympy import Matrix, I >>> m ...
TypeError
dataset/ETHPy150Open sympy/sympy/sympy/matrices/dense.py/DenseMatrix.__getitem__
1,748
def equals(self, other, failing_expression=False): """Applies ``equals`` to corresponding elements of the matrices, trying to prove that the elements are equivalent, returning True if they are, False if any pair is not, and None (or the first failing expression if failing_expression is T...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/matrices/dense.py/DenseMatrix.equals
1,749
def __eq__(self, other): try: if self.shape != other.shape: return False if isinstance(other, Matrix): return self._mat == other._mat elif isinstance(other, MatrixBase): return self._mat == Matrix(other)._mat except __HO...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/matrices/dense.py/DenseMatrix.__eq__
1,750
def _get_raw_data(self, image, format_, quality, image_info=None, progressive=False): # Increase (but never decrease) PIL buffer size ImageFile.MAXBLOCK = max(ImageFile.MAXBLOCK, image.size[0] * image.size[1]) bf = BufferIO() params = { 'format': format_, 'qualit...
OSError
dataset/ETHPy150Open mariocesar/sorl-thumbnail/sorl/thumbnail/engines/pil_engine.py/Engine._get_raw_data
1,751
@classmethod def initialize(cls): """Initialize the class after plugin load.""" super().initialize() if cls.module is None: return # This is tricky. Unfortunately pyflakes chooses to store # builtins in a class variable and union that with the builtins option ...
ImportError
dataset/ETHPy150Open SublimeLinter/SublimeLinter-flake8/linter.py/Flake8.initialize
1,752
@must_be_valid_project @must_be_logged_in @must_have_permission(READ) def node_setting(auth, node, **kwargs): #check institutions: try: email_domains = [email.split('@')[1] for email in auth.user.emails] inst = Institution.find_one(Q('email_domains', 'in', email_domains)) if inst not in...
IndexError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/node_setting
1,753
@must_be_valid_project @must_be_contributor_or_public @must_not_be_registration def watch_post(auth, node, **kwargs): user = auth.user watch_config = WatchConfig(node=node, digest=request.json.get('digest', False), immediate=request.json.get('immedia...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/watch_post
1,754
@must_be_valid_project @must_be_contributor_or_public @must_not_be_registration def unwatch_post(auth, node, **kwargs): user = auth.user watch_config = WatchConfig(node=node, digest=request.json.get('digest', False), immediate=request.json.get('immed...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/unwatch_post
1,755
@must_be_valid_project @must_be_contributor_or_public @must_not_be_registration def togglewatch_post(auth, node, **kwargs): '''View for toggling watch mode for a node.''' # TODO: refactor this, watch_post, unwatch_post (@mambocab) user = auth.user watch_config = WatchConfig( node=node, d...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/togglewatch_post
1,756
@collect_auth def move_pointers(auth): """Move pointer from one node to another node. """ from_node_id = request.json.get('fromNodeId') to_node_id = request.json.get('toNodeId') pointers_to_move = request.json.get('pointerIds') if from_node_id is None or to_node_id is None or pointers_to_move...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/move_pointers
1,757
@collect_auth def add_pointer(auth): """Add a single pointer to a node using only JSON parameters """ to_node_id = request.json.get('toNodeID') pointer_to_move = request.json.get('pointerID') if not (to_node_id and pointer_to_move): raise HTTPError(http.BAD_REQUEST) pointer = Node.loa...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/add_pointer
1,758
@must_have_permission(WRITE) @must_not_be_registration def add_pointers(auth, node, **kwargs): """Add pointers to a node. """ node_ids = request.json.get('nodeIds') if not node_ids: raise HTTPError(http.BAD_REQUEST) nodes = [ Node.load(node_id) for node_id in node_ids ...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/add_pointers
1,759
@must_have_permission(WRITE) @must_not_be_registration def remove_pointer(auth, node, **kwargs): """Remove a pointer from a node, raising a 400 if the pointer is not in `node.nodes`. """ # TODO: since these a delete request, shouldn't use request body. put pointer # id in the URL instead pointe...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/remove_pointer
1,760
@must_be_valid_project # injects project @must_have_permission(WRITE) @must_not_be_registration def remove_pointer_from_folder(auth, node, pointer_id, **kwargs): """Remove a pointer from a node, raising a 400 if the pointer is not in `node.nodes`. """ if pointer_id is None: raise HTTPError(htt...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/remove_pointer_from_folder
1,761
@must_have_permission(WRITE) @must_not_be_registration def fork_pointer(auth, node, **kwargs): """Fork a pointer. Raises BAD_REQUEST if pointer not provided, not found, or not present in `nodes`. """ pointer_id = request.json.get('pointerId') pointer = Pointer.load(pointer_id) if pointer is No...
ValueError
dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/node.py/fork_pointer
1,762
def tearDown(self): self.top = None os.chdir(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.lib/src/openmdao/lib/casehandlers/test/test_json_filevar.py/TestCase.tearDown
1,763
def test_unique_for_date_with_nullable_date(self): p1 = FlexibleDatePost.objects.create(title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) p = FlexibleDatePost(title="Django 1.0 is released") try: p.full_clean() ...
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/modeltests/validation/test_unique.py/PerformUniqueChecksTest.test_unique_for_date_with_nullable_date
1,764
def _os_supports_avx(): """ Whether the current OS supports AVX, regardless of the CPU. This is necessary because the user may be running a very old Linux kernel (e.g. CentOS 5) on a recent CPU. """ if (not sys.platform.startswith('linux') or platform.machine() not in ('i386', 'i586', '...
OSError
dataset/ETHPy150Open numba/numba/numba/config.py/_os_supports_avx
1,765
def __init__(self, filename): """Initialize writer with a file descriptor.""" self._data = None self._data_queue = deque() self._file = filename self._fd = None self._timer = None try: self._open_file() except __HOLE__, (errno, errmsg): ...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosWriter.__init__
1,766
def doWrite(self): """Write data out to the pipe.""" while self._data or self._data_queue: if not self._data: self._data = self._data_queue.popleft() log.trace("Writing Nagios command to fifo: %s", self._data) try: data_written = os....
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosWriter.doWrite
1,767
def _reopen_file(self): """Attempt to reopen the pipe.""" if self._timer: if not self._timer.called: self._timer.cancel() self._timer = None try: self._open_file() except __HOLE__, (errno, errmsg): log.warn("Failed to reop...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosWriter._reopen_file
1,768
def _close_file(self): """Close the named pipe if open""" if self._fd is not None: self.stopWriting() try: os.close(self._fd) except __HOLE__: pass self._fd = None
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosWriter._close_file
1,769
def __init__(self, command_file, spool_dir): """Create writer and add it to the reactor. command_file is the path to the nagios pipe spool_dir is where to write large commands to """ self.spool_dir = spool_dir # Create or cleanup the spool dir if os.path.isdir(s...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosCommander.__init__
1,770
def _cleanup_spool(self): """Periodically clean up old things in the spool dir. This shouldn't normally be required but if things get screwed up we don't want the directory to get so huge that it keeps things slow after nagios is handling results again. """ # Note: It i...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosCommander._cleanup_spool
1,771
def _groupTokenizer(self, string): string = cStringIO.StringIO(string) lex = shlex.shlex(string, posix=True) lex.escape = "" lex.wordchars = ( "abcdfeghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789_.-:[]?*+^$," ) valid = lex.word...
ValueError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/nagios_api.py/NagiosXMLRPC._groupTokenizer
1,772
def apply(self, fgraph): tasks = defaultdict(list) if self.max_use_ratio is not None: max_uses = self.max_use_ratio * len(fgraph.apply_nodes) runs = defaultdict(int) else: runs = None def importer(node): # ...
KeyError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/gof/sandbox/equilibrium.py/_EquilibriumOptimizer.apply
1,773
def get(self, name, default=None): """Return a key or the default value if no value exists.""" try: return self[name] except __HOLE__: return default
KeyError
dataset/ETHPy150Open IanLewis/kay/kay/utils/datastructures.py/ReadOnlyMultiMapping.get
1,774
def __contains__(self, name): try: self[name] except __HOLE__: return False return True
KeyError
dataset/ETHPy150Open IanLewis/kay/kay/utils/datastructures.py/ReadOnlyMultiMapping.__contains__
1,775
def get_standard_processors(): from django.conf import settings global _standard_context_processors if _standard_context_processors is None: processors = [] collect = [] collect.extend(_builtin_context_processors) collect.extend(settings.TEMPLATE_CONTEXT_PROCESSORS) f...
ImportError
dataset/ETHPy150Open adieu/django-nonrel/django/template/context.py/get_standard_processors
1,776
def __init__(self, app, conf): self.app = app self.memcache_servers = conf.get('memcache_servers') serialization_format = conf.get('memcache_serialization_support') try: # Originally, while we documented using memcache_max_connections # we only accepted max_connec...
ValueError
dataset/ETHPy150Open openstack/swift/swift/common/middleware/memcache.py/MemcacheMiddleware.__init__
1,777
def setup(vim, level, output_file=None): """Setup logging for Deoplete """ global init if init: return init = True if output_file: formatter = logging.Formatter(log_format) handler = logging.FileHandler(filename=output_file) handler.setFormatter(formatter) ...
ImportError
dataset/ETHPy150Open Shougo/deoplete.nvim/rplugin/python3/deoplete/logger.py/setup
1,778
def get_request_id(self): """ This must be called while self.lock is held. """ try: return self.request_ids.popleft() except __HOLE__: self.highest_request_id += 1 # in_flight checks should guarantee this assert self.highest_request...
IndexError
dataset/ETHPy150Open datastax/python-driver/cassandra/connection.py/Connection.get_request_id
1,779
@property def next_timeout(self): try: return self._queue[0][0] except __HOLE__: pass
IndexError
dataset/ETHPy150Open datastax/python-driver/cassandra/connection.py/TimerManager.next_timeout
1,780
def read(self, location): """ Read file from disk. """ location = os.path.expanduser(location) # Try to open this file, using different encodings. for e in ENCODINGS: try: with codecs.open(location, 'r', e) as f: return f.r...
UnicodeDecodeError
dataset/ETHPy150Open jonathanslenders/pyvim/pyvim/io/backends.py/FileIO.read
1,781
def _auto_decode(data): """ Decode bytes. Return a (text, encoding) tuple. """ assert isinstance(data, six.binary_type) for e in ENCODINGS: try: return data.decode(e), e except __HOLE__: pass return data.decode('utf-8', 'ignore')
UnicodeDecodeError
dataset/ETHPy150Open jonathanslenders/pyvim/pyvim/io/backends.py/_auto_decode
1,782
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. ...
ValueError
dataset/ETHPy150Open bernardopires/django-tenant-schemas/tenant_schemas/template_loaders.py/FilesystemLoader.get_template_sources
1,783
def load_template_source(self, template_name, template_dirs=None): tried = [] for filepath in self.get_template_sources(template_name, template_dirs): try: with open(filepath, 'rb') as fp: return (fp.read().decode(settings.FILE_CHARSET), filepath) ...
IOError
dataset/ETHPy150Open bernardopires/django-tenant-schemas/tenant_schemas/template_loaders.py/FilesystemLoader.load_template_source
1,784
@attribute def schema(self): try: m = self._schema except __HOLE__: pass else: return m() self.schema = schema = datashape.dshape(self.dshape.measure) return schema
AttributeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/expressions.py/Expr.schema
1,785
def _len(self): try: return int(self.dshape[0]) except __HOLE__: raise ValueError('Can not determine length of table with the ' 'following datashape: %s' % self.dshape)
TypeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/expressions.py/Expr._len
1,786
def __getattr__(self, key): assert key != '_hash', \ '%s expressions should set _hash in __init__' % type(self).__name__ try: result = object.__getattribute__(self, key) except __HOLE__: fields = dict(zip(map(valid_identifier, self.fields), self.fields)) ...
AttributeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/expressions.py/Expr.__getattr__
1,787
def __exit__(self, *args): """ Exit context Close any open resource if we are called in context """ for value in self._resources().values(): try: value.close() except __HOLE__: pass return True
AttributeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/expressions.py/Expr.__exit__
1,788
@dispatch(object) def shape(expr): """ Shape of expression >>> symbol('s', '3 * 5 * int32').shape (3, 5) Works on anything discoverable >>> shape([[1, 2], [3, 4]]) (2, 2) """ s = list(discover(expr).shape) for i, elem in enumerate(s): try: s[i] = int(elem) ...
TypeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/expressions.py/shape
1,789
def importBundle(org, name, data): hdrs = { 'Content-Type': 'application/octet-stream' } uri = '/v1/organizations/%s/apis?action=import&name=%s' \ % (org, name) print 'Importing new application %s' % name resp = None try: resp = httptools.httpCall('POST', uri, hdrs, data) except __HOLE__, e: ...
IOError
dataset/ETHPy150Open apigee/api-platform-tools/ApigeePlatformTools/deploytools.py/importBundle
1,790
def iter_query(query): """Accept a filename, stream, or string. Returns an iterator over lines of the query.""" try: itr = click.open_file(query).readlines() except __HOLE__: itr = [query] return itr
IOError
dataset/ETHPy150Open mapbox/mapbox-cli-py/mapboxcli/scripts/geocoding.py/iter_query
1,791
def coords_from_query(query): """Transform a query line into a (lng, lat) pair of coordinates.""" try: coords = json.loads(query) except __HOLE__: vals = re.split(r"\,*\s*", query.strip()) coords = [float(v) for v in vals] return tuple(coords[:2])
ValueError
dataset/ETHPy150Open mapbox/mapbox-cli-py/mapboxcli/scripts/geocoding.py/coords_from_query
1,792
@conftest def find_sxx(conf): v = conf.env cc = None if v['CXX']: cc = v['CXX'] elif 'CXX' in conf.environ: cc = conf.environ['CXX'] if not cc: cc = conf.find_program('c++', var='CXX') if not cc: conf.fatal('sunc++ was not found') cc = conf.cmd_to_list(cc) try: if not Utils.cmd_output(cc + ['-flags']): co...
ValueError
dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/suncxx.py/find_sxx
1,793
def __new__(cls, application, request, **kwargs): # http://stackoverflow.com/questions/3209233/how-to-replace-an-instance-in-init-with-a-different-object # Based on upgrade header, websocket request handler must be used try: if request.headers['Upgrade'].lower() == 'websocket': ...
KeyError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/ProxyHandler.__new__
1,794
def set_status(self, status_code, reason=None): """Sets the status code for our response. Overriding is done so as to handle unknown response codes gracefully. """ self._status_code = status_code if reason is not None: self._reason = tornado.escape.native_str(reason)...
KeyError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/ProxyHandler.set_status
1,795
@tornado.web.asynchronous @tornado.gen.coroutine def get(self): """Handle all requests except the connect request. Once ssl stream is formed between browser and proxy, the requests are then processed by this function. """ # The flow starts here self.request.local_timesta...
ValueError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/ProxyHandler.get
1,796
def store_upstream_data(self, message): """Save websocket data sent from client to server. i.e add it to HTTPRequest.response_buffer with direction (>>) """ try: # Cannot write binary content as a string, so catch it self.handshake_request.response_buffer += (">>> %s\r\n" %...
TypeError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/CustomWebSocketHandler.store_upstream_data
1,797
def store_downstream_data(self, message): """Save websocket data sent from client to server. i.e add it to HTTPRequest.response_buffer with direction (<<) """ try: # Cannot write binary content as a string, so catch it. self.handshake_request.response_buffer += ("<<< %s\r\n...
TypeError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/CustomWebSocketHandler.store_downstream_data
1,798
def initialize(self, outbound_options=[], outbound_auth=""): # The tornado application, which is used to pass variables to request handler self.application = tornado.web.Application(handlers=[(r'.*', ProxyHandler)], debug=False, gzip=True,) self.config = self.get_component("config") self...
AssertionError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/proxy.py/ProxyProcess.initialize
1,799
def __init__(self, *args, **kwargs): super(StyledLinkForm, self).__init__(*args, **kwargs) # # Combine object_type and object_id into a single 'int_destination' # field Get all the objects that we want the user to be able to choose # from. # # For the objects, if...
TypeError
dataset/ETHPy150Open mkoistinen/djangocms-styledlink/djangocms_styledlink/forms.py/StyledLinkForm.__init__