Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
1,600
def _randint(seed=None): """Return a randint generator. ``seed`` can be o None - return randomly seeded generator o int - return a generator seeded with the int o list - the values to be returned will be taken from the list in the order given; the provided list is not modified. ...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/utilities/randtest.py/_randint
1,601
def gb(args): """ %prog gb gffile fastafile Convert GFF3 to Genbank format. Recipe taken from: <http://www.biostars.org/p/2492/> """ from Bio.Alphabet import generic_dna try: from BCBio import GFF except __HOLE__: print >> sys.stderr, "You need to install dep first: $ ea...
ImportError
dataset/ETHPy150Open tanghaibao/jcvi/formats/gff.py/gb
1,602
def gtf(args): """ %prog gtf gffile Convert gff to gtf file. In gtf, only exon/CDS features are important. The first 8 columns are the same as gff, but in the attributes field, we need to specify "gene_id" and "transcript_id". """ p = OptionParser(gtf.__doc__) opts, args = p.parse_args(...
IndexError
dataset/ETHPy150Open tanghaibao/jcvi/formats/gff.py/gtf
1,603
def __repr__(self): try: ContentTypeText = ContentType._VALUES_TO_NAMES[self.contentType] except __HOLE__: #print "*** Unknow Content Type", self.contentType ContentTypeText = self.contentType return 'LineMessage (contentType=%s, sender=%s, receiver=%s, msg="%...
KeyError
dataset/ETHPy150Open carpedm20/LINE/line/models.py/LineMessage.__repr__
1,604
def __init__(self, client, group=None, is_joined=True): """LineGroup init :param client: LineClient instance :param group: Group instace :param is_joined: is a user joined or invited to a group """ self._client = client self._group = group self.id ...
TypeError
dataset/ETHPy150Open carpedm20/LINE/line/models.py/LineGroup.__init__
1,605
@patch('kombu.transport.virtual.emergency_dump_state') @patch(PRINT_FQDN) def test_restore_unacked_once_when_unrestored(self, print_, emergency_dump_state): q = self.channel.qos q._flush = Mock() class State(dict): restored =...
KeyError
dataset/ETHPy150Open celery/kombu/kombu/tests/transport/virtual/test_base.py/test_Channel.test_restore_unacked_once_when_unrestored
1,606
def authenticate(self, site, site_url, assertion): """Verifies BrowserID assertion Returns: Object that represents a user with an email verified by the assertion. If a user with such email does not exists, but there are open locations that require login, the user ...
ValidationError
dataset/ETHPy150Open wrr/wwwhisper/wwwhisper_auth/backend.py/BrowserIDBackend.authenticate
1,607
def authenticate(self, site, site_url, token): """Token was a part of a login url that proves email ownership. Returns: Object that represents a user with the verified email encoded in the token. If a user with such email does not exists, but there are open locati...
ValidationError
dataset/ETHPy150Open wrr/wwwhisper/wwwhisper_auth/backend.py/VerifiedEmailBackend.authenticate
1,608
def close(self): if 'less' in self.cmd: self.write("press q to quit") if self.proc: self.file.close() try: self.proc.wait() except __HOLE__: sys.proc.kill() sys.exit(1)
KeyboardInterrupt
dataset/ETHPy150Open jsmits/github-cli/src/github/utils.py/Pager.close
1,609
def clear(self): """ Removes all modes from the editor. All modes are removed from list and deleted. """ import sys while len(self._modes): key = sorted(list(self._modes.keys()))[0] mode = self.remove(key) refcount = sys.getrefcount(mo...
ImportError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/managers/modes.py/ModesManager.clear
1,610
def _instance_or_null(self, instance_class, json): if json is None: return NullObject(instance_class.__name__) if not isinstance(json, dict): return exceptions.UnprocessableResponseBody( "GitHub's API returned a body that could not be handled", json ) ...
TypeError
dataset/ETHPy150Open sigmavirus24/github3.py/github3/models.py/GitHubCore._instance_or_null
1,611
def type_match(self,value): is_match = 0 try: if value.IsA('vtkObject'): is_match = 1 except __HOLE__: pass return is_match
AttributeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/vtk_spec.py/vtk_converter.type_match
1,612
def test_evaluations(): # Create an Evaluation name = 'Test Evaluation %s' % str(uuid.uuid4()) ev = Evaluation(name=name, description='Evaluation for testing', contentSource=project['id'], status='CLOSED') ev = syn.store(ev) try: # -- Get the Evaluation by name...
AssertionError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/integration/test_evaluations.py/test_evaluations
1,613
def test_teams(): name = "My Uniquely Named Team " + str(uuid.uuid4()) team = syn.store(Team(name=name, description="A fake team for testing...")) schedule_for_cleanup(team) found_team = syn.getTeam(team.id) assert team == found_team p = syn.getUserProfile() found = None for m in syn.g...
ValueError
dataset/ETHPy150Open Sage-Bionetworks/synapsePythonClient/tests/integration/test_evaluations.py/test_teams
1,614
def __init__(self, _exception): try: data = self._parser.match(_exception.message).groupdict() except __HOLE__: raise _exception self._instance = data['ins'] self._caught = data['cg'] self._exception = data['ex'] self._primary_error_code = data['p...
AttributeError
dataset/ETHPy150Open tdevelioglu/python-f5/f5/exceptions.py/BigSudsExceptionParser.__init__
1,615
def make_path(self, parameter_name): """Parse a parameter name and build a full path to a message value. The path of a method is a tuple of 2-tuples describing the names and indexes within repeated fields from the root message (the message being constructed by the builder) to an arbitrarily nested mess...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/protourlencode.py/URLEncodedRequestBuilder.make_path
1,616
def add_parameter(self, parameter, values): """Add a single parameter. Adds a single parameter and its value to the request message. Args: parameter: Query string parameter to map to request. values: List of values to assign to request message. Returns: True if parameter was valid a...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/protourlencode.py/URLEncodedRequestBuilder.add_parameter
1,617
def _check_file_syntax(filename, temp_dir, override_lang=None, enforce=True): """ Checks that the code in FILENAME parses, attempting to autodetect the language if necessary. Raises IOError if the file cannot be read. Raises DXSyntaxError if there is a problem and "enforce" is True. """ de...
OSError
dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/scripts/dx_build_app.py/_check_file_syntax
1,618
def _verify_app_source_dir_impl(src_dir, temp_dir, mode, enforce=True): """Performs syntax and lint checks on the app source. Precondition: the dxapp.json file exists and can be parsed. """ _lint(os.path.join(src_dir, "dxapp.json"), mode) # Check that the entry point file parses as the type it is ...
IOError
dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/scripts/dx_build_app.py/_verify_app_source_dir_impl
1,619
def _subtractAndCompareToZero(a, b, op): """Helper function for comparison operators. Subtracts b from a, exactly if possible, and compares the result with 0 using op, in such a way that the comparison won't recurse. If the difference raises a TypeError, returns NotImpleme...
TypeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/fractions.py/Fraction._subtractAndCompareToZero
1,620
def serialize_comments(self, comments): result = {} serialized_comments = \ super(ImageReviewUI, self).serialize_comments(comments) for serialized_comment in serialized_comments: try: position = '%(x)sx%(y)s+%(width)s+%(height)s' \ ...
KeyError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/reviews/ui/image.py/ImageReviewUI.serialize_comments
1,621
def get_comment_thumbnail(self, comment): try: x = int(comment.extra_data['x']) y = int(comment.extra_data['y']) width = int(comment.extra_data['width']) height = int(comment.extra_data['height']) except (__HOLE__, ValueError): # This may be a ...
KeyError
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/reviews/ui/image.py/ImageReviewUI.get_comment_thumbnail
1,622
def camshift(): cam = Camera() img = cam.getImage() d = Display(img.size()) bb1 = getBBFromUser(cam,d) fs1=[] while True: try: img1 = cam.getImage() fs1 = img1.track("camshift",fs1,img,bb1,num_frames=5, nframes=60, lower=(0, 40, 40), upper=(80, 200, 200)) ...
KeyboardInterrupt
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/examples/tracking/camshift.py/camshift
1,623
def getBBFromUser(cam, d): p1 = None p2 = None img = cam.getImage() while d.isNotDone(): try: img = cam.getImage() img.save(d) dwn = d.leftButtonDownPosition() up = d.leftButtonUpPosition() if dwn: p1 = dwn ...
KeyboardInterrupt
dataset/ETHPy150Open sightmachine/SimpleCV/SimpleCV/examples/tracking/camshift.py/getBBFromUser
1,624
def finalize_order(request): '''Helper function that actually complete the order when the payment provider tells us so. ''' order_id = provider.get_order_id(request) order = Order.objects.get(pk=order_id) #Order is already completed if order.payment_done: return #Simul...
TypeError
dataset/ETHPy150Open thomasWajs/cartridge-external-payment/cartridge_external_payment/views.py/finalize_order
1,625
def serialize_session(self, data): """Serializes values for a session. :param data: A dict with session data. :returns: A list with session data. """ try: assert len(data) >= len(self.session_attributes) return [data.get(k) for k i...
AssertionError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webapp2-2.3/webapp2_extras/auth.py/AuthStore.serialize_session
1,626
def deserialize_session(self, data): """Deserializes values for a session. :param data: A list with session data. :returns: A dict with session data. """ try: assert len(data) >= len(self.session_attributes) return dict(zip(self.se...
AssertionError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webapp2-2.3/webapp2_extras/auth.py/AuthStore.deserialize_session
1,627
def _generate_audio(songs, beats, new_beats, new_beats_cost, music_labels, volume=None, volume_breakpoints=None, springs=None, fade_in_len=3.0, fade_out_len=5.0): # assuming same sample rate for all songs logging.info("Building volume") if volume is not None and volu...
ValueError
dataset/ETHPy150Open ucbvislab/radiotool/radiotool/algorithms/retarget.py/_generate_audio
1,628
def get_remote_dir(remote_dir, local_dir='.', extension=None, verbose=False): if extension is not None: remote_dir = '{}/*.{}'.format(remote_dir, extension) gsutil = shutil.which('gsutil') cmd = [gsutil, '-m', 'cp', '-r', remote_dir, local_dir] if verbose: print(cmd) try: ...
OSError
dataset/ETHPy150Open panoptes/POCS/scripts/gather_pec_data.py/get_remote_dir
1,629
def pytest_configure(): from django.conf import settings settings.configure( DEBUG_PROPAGATE_EXCEPTIONS=True, DATABASES={'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}}, SITE_ID=1, SECRET_KEY='not very secret in tests', ...
AttributeError
dataset/ETHPy150Open umutbozkurt/django-rest-framework-mongoengine/tests/conftest.py/pytest_configure
1,630
def list(self): try: files = os.listdir(self.folder) except __HOLE__: files = [] return files
IOError
dataset/ETHPy150Open tallstreet/Whoosh-AppEngine/src/whoosh/store.py/FileStorage.list
1,631
def get_column_name(self, index): """ Return the name of the column specified by the (zero-based) index. """ if self.columns is not None: # if we have an explicit declaration then use it try: name = self.columns[index].label except __HOLE__: ...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.get_column_name
1,632
def is_column_read_only(self, index): """ Return True if the column specified by the zero-based index is read-only. """ # if there is no declaration then assume the column is not # read only read_only = False if self.columns is not None: # if we have an expli...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.is_column_read_only
1,633
def get_row_name(self, index): """ Return the name of the row specified by the (zero-based) index. """ if self.rows is not None: # if we have an explicit declaration then use it try: name = self.rows[index].label except __HOLE__: ...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.get_row_name
1,634
def is_row_read_only(self, index): """ Return True if the row specified by the zero-based index is read-only. """ # if there is no declaration then assume the row is not # read only read_only = False if self.rows is not None: # if we have an explicit declarat...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.is_row_read_only
1,635
def get_value(self, row, col): """ Return the value stored in the table at (row, col). """ try: return self.data[row][col] except __HOLE__: pass return ''
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.get_value
1,636
def is_cell_empty(self, row, col): """ Returns True if the cell at (row, col) has a None value, False otherwise.""" if row >= self.get_row_count() or col >= self.get_column_count(): empty = True else: try: value = self.get_value(row, col) ...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.is_cell_empty
1,637
def _set_value(self, row, col, value): """ Sets the value of the cell at (row, col) to value. Raises a ValueError if the value is vetoed or the cell at (row, col) does not exist. """ new_rows = 0 try: self.data[row][col] = value except __HOLE__: #...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel._set_value
1,638
def __get_data_column(self, col): """ Return a 1-d list of data from the column indexed by col. """ row_count = self.get_row_count() coldata = [] for row in range(row_count): try: coldata.append(self.get_value(row, col)) except __HOLE__: ...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.__get_data_column
1,639
def __get_data_row(self, row): """ Return a 1-d list of data from the row indexed by row. """ col_count = self.get_column_count() rowdata = [] for col in range(col_count): try: rowdata.append(self.get_value(row, col)) except __HOLE__: ...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/wx/grid/simple_grid_model.py/SimpleGridModel.__get_data_row
1,640
def __init__(self, app_title, app_banner, theme, services_service): self.oauth_modules = {} self._error_message = u'' self.services_service = services_service self.app_title = app_title self.app_banner = app_banner self.theme = theme self.content = component.Compo...
TypeError
dataset/ETHPy150Open Net-ng/kansha/kansha/authentication/oauth/forms.py/Login.__init__
1,641
def main(): PROJECT_ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__), "..")) output_dir = os.environ.get("TEST_COVERAGE_OUTPUT_DIR", os.path.join(PROJECT_ROOT, "coverage")) if 'DJANGO_SETTINGS_MODULE' not in os.environ: import settings as sett os.environ["DJANGO_SETTINGS_MODULE...
ValueError
dataset/ETHPy150Open willhardy/django-seo/regressiontests/test-coverage.py/main
1,642
def get_tokens_unprocessed(self, text, stack=('root',)): """ Split ``text`` into (tokentype, text) pairs. Monkeypatched to store the final stack on the object itself. The `text` parameter that gets passed is only the current line, so to highlight things like multiline strings correctly, we...
IndexError
dataset/ETHPy150Open enthought/pyface/pyface/ui/qt4/code_editor/pygments_highlighter.py/get_tokens_unprocessed
1,643
def build(self, dist=False): """ Save the rendered output to the output file. """ logging.info("Building %s", self.path) data = self.render() # Make sure a folder for the output path exists try: os.makedirs( os.path.dirname( ...
OSError
dataset/ETHPy150Open randomknowledge/Cactus_Refactored/cactus/page.py/Page.build
1,644
@permission_required("core.manage_shop") def manage_delivery_times(request): """Dispatches to the first delivery time or to the form to add a delivery time (if there is no delivery time yet). """ try: delivery_time = DeliveryTime.objects.all()[0] url = reverse("lfs_manage_delivery_time",...
IndexError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/views/delivery_times.py/manage_delivery_times
1,645
def main(): sys.path.insert(0, os.getcwd()) # argument parser debug, no_watch = argument_parser() # log make_logging(debug) print_logo() print "pfrock version %s " % pfrock.__version__ time.sleep(1) # parser config_server = PfrockConfigParser.do(pfrockfile) # routes i...
KeyboardInterrupt
dataset/ETHPy150Open knightliao/pfrock/pfrock/console_scripts.py/main
1,646
def file_corpus(filename, encoding='utf8', nltk_stop=True, stop_freq=1, add_stop=None, decode=False, simple=False, tokenizer=word_tokenize): """ `file_corpus` is a convenience function for generating Corpus objects from a a plain text corpus contained in a single string. ...
UnicodeDecodeError
dataset/ETHPy150Open inpho/vsm/vsm/extensions/corpusbuilders/corpusbuilders.py/file_corpus
1,647
def dir_corpus(plain_dir, chunk_name='article', encoding='utf8', paragraphs=True, ignore=['.json','.log','.pickle'], nltk_stop=True, stop_freq=1, add_stop=None, decode=False, verbose=1, simple=False, tokenizer=word_tokenize): """ `dir_corpus` is a convenience func...
UnicodeDecodeError
dataset/ETHPy150Open inpho/vsm/vsm/extensions/corpusbuilders/corpusbuilders.py/dir_corpus
1,648
def coll_corpus(coll_dir, encoding='utf8', ignore=['.json', '.log', '.pickle'], nltk_stop=True, stop_freq=1, add_stop=None, decode=False, verbose=1, simple=False, tokenizer=word_tokenize): """ `coll_corpus` is a convenience function for generating Corpus objects from a direc...
UnicodeDecodeError
dataset/ETHPy150Open inpho/vsm/vsm/extensions/corpusbuilders/corpusbuilders.py/coll_corpus
1,649
def runtests(*test_args): # Setup settings if not settings.configured: settings.configure(**SETTINGS) # New Django 1.7 app registry setup try: from django import setup setup() except ImportError: pass # New Django 1.8 test runner try: from django.tes...
ImportError
dataset/ETHPy150Open bartTC/dpaste/runtests.py/runtests
1,650
def load_handlers(config, handler_names): """ Load handlers """ log = logging.getLogger('diamond') handlers = [] if isinstance(handler_names, basestring): handler_names = [handler_names] for handler in handler_names: log.debug('Loading Handler %s', handler) try: ...
ImportError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/diamond/utils/classes.py/load_handlers
1,651
def load_collectors(paths=None, filter=None): """ Scan for collectors to load from path """ # Initialize return value collectors = {} log = logging.getLogger('diamond') if paths is None: return if isinstance(paths, basestring): paths = paths.split(',') paths = m...
SystemExit
dataset/ETHPy150Open BrightcoveOS/Diamond/src/diamond/utils/classes.py/load_collectors
1,652
def __init__(self, worker_count=None, *args, **kwargs): """Initializes a task executor. This may take a bit to run, as the process pool is primed. Args: worker_count: Number of worker threads to use when building. None to use as many processors as are available. """ super(MultiProce...
OSError
dataset/ETHPy150Open google/anvil-build/anvil/task.py/MultiProcessTaskExecutor.__init__
1,653
def test_retry_on_failure(self): fd, tmpfilename = tempfile.mkstemp() _, tmpfilename2 = tempfile.mkstemp() try: fp = os.fdopen(fd, 'w+') fp.write('''#!/bin/sh # If stdin fails to get passed during one of the runs, make a note. if ! grep -q foo then echo 'failure' > "$...
OSError
dataset/ETHPy150Open openstack/ironic-python-agent/ironic_python_agent/tests/unit/test_utils.py/ExecuteTestCase.test_retry_on_failure
1,654
def test_no_retry_on_success(self): fd, tmpfilename = tempfile.mkstemp() _, tmpfilename2 = tempfile.mkstemp() try: fp = os.fdopen(fd, 'w+') fp.write('''#!/bin/sh # If we've already run, bail out. grep -q foo "$1" && exit 1 # Mark that we've run before. echo foo > "$1" # C...
OSError
dataset/ETHPy150Open openstack/ironic-python-agent/ironic_python_agent/tests/unit/test_utils.py/ExecuteTestCase.test_no_retry_on_success
1,655
def current_knesset(self): if self._current_knesset is None: try: self._current_knesset = self.get_query_set().order_by('-number')[0] except __HOLE__: #FIX: should document when and why this should happen return None return self._cu...
IndexError
dataset/ETHPy150Open ofri/Open-Knesset/mks/managers.py/KnessetManager.current_knesset
1,656
def callback(self, inputs, outputs, errors): try: for s in inputs: if s == self.server: try: conn, addr = self.server.accept() except socket.error, e: if e[0] == 24: # ulimit maxfiles, need to raise ulimit self._root.console_write('Maximum files reached, refused new connect...
KeyError
dataset/ETHPy150Open lunixbochs/uberserver/Dispatcher.py/Dispatcher.callback
1,657
def finishRemove(self, client, reason='Quit'): if client.static or not client._protocol: return # static clients don't disconnect client._protocol._remove(client, reason) s = client.conn if s in self.socketmap: del self.socketmap[s] self.poller.unregister(s) try: s.shutdown(socket.SHUT_RDW...
AttributeError
dataset/ETHPy150Open lunixbochs/uberserver/Dispatcher.py/Dispatcher.finishRemove
1,658
@app.route('/_ping') @app.route('/v1/_ping') def ping(): headers = { 'X-Docker-Registry-Standalone': 'mirror' if mirroring.is_mirror() else (cfg.standalone is True) } infos = {} if cfg.debug: # Versions versions = infos['versions'] = {} ...
AttributeError
dataset/ETHPy150Open docker/docker-registry/docker_registry/app.py/ping
1,659
def load_obj_from_path(import_path, prefix=None, ld=dict()): """ import a python object from an import path `import_path` - a python import path. For instance: mypackage.module.func or mypackage.module.class `prefix` (str) - a value to prepend to the import path ...
ValueError
dataset/ETHPy150Open sailthru/relay/relay/util.py/load_obj_from_path
1,660
def next(itr, default=_undef): "compat wrapper for next()" if default is _undef: return itr.next() try: return itr.next() except __HOLE__: return default
StopIteration
dataset/ETHPy150Open twisted/ldaptor/ldaptor/compat.py/next
1,661
def tearDown(self): 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/openmdao/components/test/test_external_code.py/TestExternalCode.tearDown
1,662
def test_error_code_raise(self): self.extcode.options['command'] = ['python', 'external_code_for_testing.py', 'external_code_output.txt', '--delay', '-3'] self.extcode.options['timeout'] = 1.0 self.extcode.options['external_input_files'] = ['external_code_for_testing.py', ] ...
RuntimeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/components/test/test_external_code.py/TestExternalCode.test_error_code_raise
1,663
def test_badcmd(self): # Set command to nonexistant path. self.extcode.options['command'] = ['no-such-command', ] self.top.setup(check=False) try: self.top.run() except __HOLE__ as exc: msg = "The command to be executed, 'no-such-command', cannot be foun...
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/components/test/test_external_code.py/TestExternalCode.test_badcmd
1,664
def test_nullcmd(self): self.extcode.stdout = 'nullcmd.out' self.extcode.stderr = STDOUT self.top.setup(check=False) try: self.top.run() except __HOLE__ as exc: self.assertEqual(str(exc), 'Empty command list') else: self.fail('Expecte...
ValueError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/components/test/test_external_code.py/TestExternalCode.test_nullcmd
1,665
def check(self, agentConfig): try: os = w.Win32_PerfFormattedData_PerfOS_System()[0] except AttributeError: self.logger.info('Missing Win32_PerfFormattedData_PerfOS_System WMI class.' ' No process metrics will be returned.') return ...
AttributeError
dataset/ETHPy150Open serverdensity/sd-agent/checks/system/win32.py/Processes.check
1,666
def check(self, agentConfig): try: os = w.Win32_OperatingSystem()[0] except __HOLE__: self.logger.info('Missing Win32_OperatingSystem. No memory metrics will be returned.') return total = 0 free = 0 cached = 0 if os.TotalVisibleMemory...
AttributeError
dataset/ETHPy150Open serverdensity/sd-agent/checks/system/win32.py/Memory.check
1,667
def check(self, agentConfig): try: cpu = w.Win32_PerfFormattedData_PerfOS_Processor() except __HOLE__: self.logger.info('Missing Win32_PerfFormattedData_PerfOS_Processor WMI class.' ' No CPU metrics will be returned.') return cpu_...
AttributeError
dataset/ETHPy150Open serverdensity/sd-agent/checks/system/win32.py/Cpu.check
1,668
def check(self, agentConfig): try: net = w.Win32_PerfFormattedData_Tcpip_NetworkInterface() except __HOLE__: self.logger.info('Missing Win32_PerfFormattedData_Tcpip_NetworkInterface WMI class.' ' No network metrics will be returned') retur...
AttributeError
dataset/ETHPy150Open serverdensity/sd-agent/checks/system/win32.py/Network.check
1,669
def check(self, agentConfig): try: disk = w.Win32_PerfFormattedData_PerfDisk_LogicalDisk() except __HOLE__: self.logger.info('Missing Win32_PerfFormattedData_PerfDisk_LogicalDiskUnable WMI class.' ' No I/O metrics will be returned.') retur...
AttributeError
dataset/ETHPy150Open serverdensity/sd-agent/checks/system/win32.py/IO.check
1,670
@property def value(self): "Returns a Python `date` object for the OFTDate field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return date(yy.value, mm.value, dd.value) except (__HOLE__, OGRException): return None
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/gis/gdal/field.py/OFTDate.value
1,671
@property def value(self): "Returns a Python `datetime` object for this OFTDateTime field." # TODO: Adapt timezone information. # See http://lists.osgeo.org/pipermail/gdal-dev/2006-February/007990.html # The `tz` variable has values of: 0=unknown, 1=localtime (ambiguous), #...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/gis/gdal/field.py/OFTDateTime.value
1,672
@property def value(self): "Returns a Python `time` object for this OFTTime field." try: yy, mm, dd, hh, mn, ss, tz = self.as_datetime() return time(hh.value, mn.value, ss.value) except (__HOLE__, OGRException): return None # List fields are also just sub...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/gis/gdal/field.py/OFTTime.value
1,673
@register.filter def namesake_methods(parent_klass, name): namesakes = [m for m in parent_klass.get_methods() if m.name == name] assert(namesakes) # Get the methods in order of the klasses try: result = [next((m for m in namesakes if m.klass == parent_klass))] namesakes.pop(namesakes.ind...
StopIteration
dataset/ETHPy150Open refreshoxford/django-cbv-inspector/cbv/templatetags/cbv_tags.py/namesake_methods
1,674
@register.inclusion_tag('cbv/includes/nav.html') def nav(version, module=None, klass=None): other_versions = ProjectVersion.objects.filter(project=version.project).exclude(pk=version.pk) context = { 'version': version, } if module: context['this_module'] = module if klass: ...
KeyError
dataset/ETHPy150Open refreshoxford/django-cbv-inspector/cbv/templatetags/cbv_tags.py/nav
1,675
def run(self, channel, name, icon_emoji, message, *args, **kwargs): try: # This URL looks like this: # http://hooks.slack.com/services/T024TTTTT/BBB72BBL/AZAAA9u0pA4ad666eMgbi555 # (not a real api url, don't try it :) # # You can get this url by addin...
KeyError
dataset/ETHPy150Open Nextdoor/ndscheduler/simple_scheduler/jobs/slack_job.py/SlackJob.run
1,676
def setup(hass, config): # pylint: disable=too-many-locals """Setup the MySensors component.""" if not validate_config(config, {DOMAIN: [CONF_GATEWAYS]}, _LOGGER): return False if not all(CONF_DEVICE in gateway for gateway in conf...
OSError
dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/components/mysensors.py/setup
1,677
def getObjectType( configId, objectTypeRetriever=[ _post7objectTypeRetriever, _pre7objectTypeRetriever ] ): try: typeName = objectTypeRetriever[0](str(configId)) except __HOLE__, ae: if 'getObjectType' not in ae.args: raise logger.warning( 'def...
AttributeError
dataset/ETHPy150Open WDR/WDR/lib/common/wdr/config.py/getObjectType
1,678
def test_not_implemented_plugin(self): auth = authinfo.ApiAuth("username", "password") hostname = "hostname" plugin = dnsupdater.DnsUpdaterPlugin(auth, hostname) try: plugin.update_dns("10.1.1.1") self.fail("Not implemented plugin should fail: " ...
AttributeError
dataset/ETHPy150Open pv8/noipy/test/test_noipy.py/GeneralTest.test_not_implemented_plugin
1,679
def is_subclass_at_all(cls, class_info): """Return whether ``cls`` is a subclass of ``class_info``. Even if ``cls`` is not a class, don't crash. Return False instead. """ try: return issubclass(cls, class_info) except __HOLE__: return False
TypeError
dataset/ETHPy150Open django-nose/django-nose/django_nose/utils.py/is_subclass_at_all
1,680
def get_db_prep_lookup(self, lookup_type, value): # If we are doing a lookup on a Related Field, we must be # comparing object instances. The value should be the PK of value, # not value itself. def pk_trace(value): # Value may be a primary key, or an object held in a relatio...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/RelatedField.get_db_prep_lookup
1,681
def __set__(self, instance, value): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.related.opts.object_name # Set the value of the related field setattr(value, self.related.field.rel.get_related_field().attname, instance) # Clear the cac...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/SingleRelatedObjectDescriptor.__set__
1,682
def __get__(self, instance, instance_type=None): if instance is None: raise AttributeError, "%s must be accessed via instance" % self.field.name cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) except __HOLE__: val = g...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__get__
1,683
def __set__(self, instance, value): if instance is None: raise AttributeError, "%s must be accessed via instance" % self._field.name # Set the value of the related field try: val = getattr(value, self.field.rel.get_related_field().attname) except __HOLE__: ...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/ReverseSingleRelatedObjectDescriptor.__set__
1,684
def __init__(self, to, to_field=None, **kwargs): try: to_name = to._meta.object_name.lower() except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "ForeignKey(%r) is invalid. First parameter to ForeignKey must ...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/ForeignKey.__init__
1,685
def __init__(self, to, to_field=None, **kwargs): try: to_name = to._meta.object_name.lower() except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "OneToOneField(%r) is invalid. First parameter to OneToOneField...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/OneToOneField.__init__
1,686
def isValidIDList(self, field_data, all_data): "Validates that the value is a valid list of foreign keys" mod = self.rel.to try: pks = map(int, field_data.split(',')) except __HOLE__: # the CommaSeparatedIntegerField validator will catch this error ret...
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/ManyToManyField.isValidIDList
1,687
def __init__(self, to, field_name, num_in_admin=3, min_num_in_admin=None, max_num_in_admin=None, num_extra_on_change=1, edit_inline=False, related_name=None, limit_choices_to=None, lookup_overrides=None, raw_id_admin=False): try: to._meta except __HOLE__: # to._meta doesn't e...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/db/models/fields/related.py/ManyToOneRel.__init__
1,688
def prepare(args, settings, parser): settings['resource'] = BytesIO(b'') settings['survey'] = True settings['receive_postbacks'] = False def get_ping_command(settings, unwrapped=None): params = OrderedDict() if settings['require_knock']: params['knock'] = settings['knock...
ImportError
dataset/ETHPy150Open EnigmaCurry/curlbomb/curlbomb/ping.py/prepare
1,689
def run(self, edit): view = self.view sels = view.sel() sel = sels[0] if 'orgmode.link.internal' not in view.scope_name(sel.end()): return region = view.extract_scope(sel.end()) content = view.substr(region).strip() if content.startswith('{{') and cont...
ImportError
dataset/ETHPy150Open danielmagnussons/orgmode/orgmode.py/OrgmodeCycleInternalLinkCommand.run
1,690
def run(self, commands=None, default_command=None, context=None): """ Context: A dict of namespaces as the key, and their objects as the value. Used to easily inject code into the shell's runtime env. """ if commands: self._commands.update(commands) ...
SystemExit
dataset/ETHPy150Open concordusapps/alchemist/alchemist/management.py/Manager.run
1,691
def _parse_author(commit_name, value, type): try: (real_name, rest) = value.split(' <', 1) except ValueError: msg = 'error parsing %s: no email address found' % (type,) raise BadCommitError(commit_name, msg) try: (email, rest) = rest.split('> ', 1) except ValueError: ...
ValueError
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/git/commit.py/_parse_author
1,692
def _parse_header(commit_name, header): tree = None parents = [] author = None committer = None # We accept the headers in any order. # git itself requires them to be tree, parents, author, committer for line in header.split('\n'): try: (name, value) = line.split(' ', 1)...
ValueError
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/git/commit.py/_parse_header
1,693
def get_commit(repo, name): # Handle the special internal commit names COMMIT_INDEX and COMMIT_WD if name == constants.COMMIT_INDEX: return get_index_commit(repo) elif name == constants.COMMIT_WD: return get_working_dir_commit(repo) # Get the SHA1 value for this commit. sha1 = repo....
ValueError
dataset/ETHPy150Open facebookarchive/git-review/src/gitreview/git/commit.py/get_commit
1,694
def fetch_val_for_key(key, delete_key=False): """Return the overriding config value for a key. A successful search returns a string value. An unsuccessful search raises a KeyError The (decreasing) priority order is: - THEANO_FLAGS - ~./theanorc """ # first try to find it in the FLAGS ...
KeyError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/configparser.py/fetch_val_for_key
1,695
def AddConfigVar(name, doc, configparam, root=config, in_c_key=True): """Add a new variable to theano.config :type name: string for form "[section0.[section1.[etc]]].option" :param name: the full name for this configuration variable. :type doc: string :param doc: What does this variable specify? ...
KeyError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/configparser.py/AddConfigVar
1,696
def __get__(self, cls, type_, delete_key=False): if cls is None: return self if not hasattr(self, 'val'): try: val_str = fetch_val_for_key(self.fullname, delete_key=delete_key) self.is_default = False ...
KeyError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/configparser.py/ConfigParam.__get__
1,697
@expose("read-char", [default(values.W_InputPort, None)], simple=False) def read_char(w_port, env, cont): try: return do_read_one(w_port, False, False, env, cont) except __HOLE__: raise SchemeException("read-char: string is not a well-formed UTF-8 encoding")
UnicodeDecodeError
dataset/ETHPy150Open samth/pycket/pycket/prims/input_output.py/read_char
1,698
@expose("read-byte", [default(values.W_InputPort, None)], simple=False) def read_byte(w_port, env, cont): try: return do_read_one(w_port, True, False, env, cont) except __HOLE__: raise SchemeException("read-byte: string is not a well-formed UTF-8 encoding")
UnicodeDecodeError
dataset/ETHPy150Open samth/pycket/pycket/prims/input_output.py/read_byte
1,699
@expose("peek-char", [default(values.W_InputPort, None), default(values.W_Fixnum, values.W_Fixnum.ZERO)], simple=False) def peek_char(w_port, w_skip, env, cont): try: return do_peek(w_port, False, w_skip.value, env, cont) except __HOLE__: raise SchemeExc...
UnicodeDecodeError
dataset/ETHPy150Open samth/pycket/pycket/prims/input_output.py/peek_char