Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,500
def _parse_vtinfo(self, info, use_filename=True): name = None version = None if use_filename and os.path.isfile(info): name = info else: data = info.split(":") if len(data) >= 2: if use_filename: if os.path.isfile(st...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/application.py/VistrailsApplicationInterface._parse_vtinfo
5,501
def safe_int(val, allow_zero=True): """ This function converts the six.moves.input values to integers. It handles invalid entries, and optionally forbids values of zero. """ try: ret = int(val) except __HOLE__: print("Sorry, '%s' is not a valid integer." % val) return Fal...
ValueError
dataset/ETHPy150Open rackspace/pyrax/samples/autoscale/add_webhook.py/safe_int
5,502
def userinfo_endpoint(self, request, **kwargs): access_token = self._parse_access_token(request) shr = SignedHttpRequest(self._get_client_public_key(access_token)) http_signature = self._parse_signature(request) try: shr.verify(http_signature, method=re...
ValidationError
dataset/ETHPy150Open rohe/pyoidc/src/oic/extension/proof_of_possesion.py/PoPProvider.userinfo_endpoint
5,503
def _get_client_public_key(self, access_token): _jws = jws.factory(access_token) if _jws: data = _jws.verify_compact(access_token, self.keyjar.get_verify_key(owner="")) try: return keyrep(data["cnf"]["jwk"]) excep...
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/extension/proof_of_possesion.py/PoPProvider._get_client_public_key
5,504
@task @transaction.commit_manually def verify_count(upload_id, localstore, language): """ Initialize the verification process by counting the number of geounits in the uploaded file. After this step completes, the verify_preload method is called. Parameters: upload_id - The id of the Subjec...
AttributeError
dataset/ETHPy150Open PublicMapping/DistrictBuilder/django/publicmapping/redistricting/tasks.py/verify_count
5,505
def check_ftest_pvalues(results): res = results use_t = res.use_t k_vars = len(res.params) # check default use_t pvals = [res.wald_test(np.eye(k_vars)[k], use_f=use_t).pvalue for k in range(k_vars)] assert_allclose(pvals, res.pvalues, rtol=5e-10, at...
AttributeError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/tools/_testing.py/check_ftest_pvalues
5,506
def parse_parametrs(p): """ Parses the parameters given from POST or websocket reqs expecting the parameters as: "11|par1='asd'|6|par2=1" returns a dict like {par1:'asd',par2:1} """ ret = {} while len(p) > 1 and p.count('|') > 0: s = p.split('|') l = int(s[0]) # length of p...
ValueError
dataset/ETHPy150Open dddomodossola/remi/remi/server.py/parse_parametrs
5,507
def process_all(self, function): self.log.debug('get: %s' % function) static_file = re.match(r"^/*res\/(.*)$", function) attr_call = re.match(r"^\/*(\w+)\/(\w+)\?{0,1}(\w*\={1}\w+\${0,1})*$", function) if (function == '/') or (not function): # build the root page once if nece...
IOError
dataset/ETHPy150Open dddomodossola/remi/remi/server.py/App.process_all
5,508
def start(mainGuiClass, **kwargs): """This method starts the webserver with a specific App subclass.""" try: debug = kwargs.pop('debug') except __HOLE__: debug = False logging.basicConfig(level=logging.DEBUG if debug else logging.INFO, format='%(name)-16s %(leveln...
KeyError
dataset/ETHPy150Open dddomodossola/remi/remi/server.py/start
5,509
def testFrozenPhoneNumber(self): # Python version extra tests gb_mobile = PhoneNumber(country_code=44, national_number=7912345678) it_number = PhoneNumber(country_code=39, national_number=236618300, italian_leading_zero=True) frozen_gb_mobile1 = FrozenPhoneNumber(country_code=44, nationa...
TypeError
dataset/ETHPy150Open daviddrysdale/python-phonenumbers/python/tests/phonenumbertest.py/PhoneNumberTest.testFrozenPhoneNumber
5,510
@require_json @require_POST @require_api_key def update_build_status(request, repository_name, build_number): """ Update a build status. Useful when another separate micro-service runs the builds. """ try: status = request.json['status'] except (__HOLE__, KeyError): return JsonRe...
TypeError
dataset/ETHPy150Open m-vdb/github-buildservice-boilerplate/buildservice/views/api.py/update_build_status
5,511
def play(self, utterance, start=0, end=None): """ Play the given audio sample. :param utterance: The utterance id of the sample to play """ # Method 1: os audio dev. try: import ossaudiodev try: dsp = ossaudiodev.open('w') ...
IOError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/timit.py/TimitCorpusReader.play
5,512
def _GetJdbcTypeForArg(self, arg): """Get the JDBC type which corresponds to the given Python object type.""" arg_jdbc_type = _PYTHON_TYPE_TO_JDBC_TYPE.get(type(arg)) if arg_jdbc_type: return arg_jdbc_type for python_t, jdbc_t in _PYTHON_TYPE_TO_JDBC_TYPE.items(): if isinstance(arg, python...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/storage/speckle/python/api/rdbms.py/Cursor._GetJdbcTypeForArg
5,513
def _AddBindVariablesToRequest(self, statement, args, bind_variable_factory, direction=client_pb2.BindVariableProto.IN): """Add args to the request BindVariableProto list. Args: statement: The SQL statement. args: Sequence of arguments to turn into BindVariableProto...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/storage/speckle/python/api/rdbms.py/Cursor._AddBindVariablesToRequest
5,514
def fetchone(self): """Fetches the next row of a query result set. Returns: A sequence, or None when no more data is available. Raises: InternalError: The cursor has been closed, or no statement has been executed yet. """ self._CheckOpen() self._CheckExecuted('fetchone() ca...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/storage/speckle/python/api/rdbms.py/Cursor.fetchone
5,515
def destroy(self, obj, silent=True): was_dropped = False with self._lock: try: self._used_objs.remove(obj) was_dropped = True except __HOLE__: if not silent: raise if was_dropped and self._after_remove is...
ValueError
dataset/ETHPy150Open pinterest/pymemcache/pymemcache/pool.py/ObjectPool.destroy
5,516
def release(self, obj, silent=True): with self._lock: try: self._used_objs.remove(obj) self._free_objs.append(obj) except __HOLE__: if not silent: raise
ValueError
dataset/ETHPy150Open pinterest/pymemcache/pymemcache/pool.py/ObjectPool.release
5,517
def check_exists(fips_dir) : """test if cmake-gui is in the path :returns: True if cmake-gui is in the path """ try: out = subprocess.check_output(['cmake-gui', '--version']) return True except (__HOLE__, subprocess.CalledProcessError) : return False; #-------...
OSError
dataset/ETHPy150Open floooh/fips/mod/tools/cmake_gui.py/check_exists
5,518
def parseConfigFile(configFile=None): """Returns a configparser.SafeConfigParser instance with configs read from the config file. Default location of the config file is at ~/.wakatime.cfg. """ if not configFile: configFile = os.path.join(os.path.expanduser('~'), '.wakatime.cfg') config...
IOError
dataset/ETHPy150Open wakatime/sublime-wakatime/packages/wakatime/main.py/parseConfigFile
5,519
def parseArguments(): """Parse command line arguments and configs from ~/.wakatime.cfg. Command line arguments take precedence over config file settings. Returns instances of ArgumentParser and SafeConfigParser. """ # define supported command line arguments parser = argparse.ArgumentParser( ...
TypeError
dataset/ETHPy150Open wakatime/sublime-wakatime/packages/wakatime/main.py/parseArguments
5,520
def should_exclude(entity, include, exclude): if entity is not None and entity.strip() != '': try: for pattern in include: try: compiled = re.compile(pattern, re.IGNORECASE) if compiled.search(entity): return False ...
TypeError
dataset/ETHPy150Open wakatime/sublime-wakatime/packages/wakatime/main.py/should_exclude
5,521
def RenderAjax(self, request, response): """Return the count on unseen notifications.""" response = super(NotificationCount, self).RenderAjax(request, response) number = 0 try: user_fd = aff4.FACTORY.Open(aff4.ROOT_URN.Add("users").Add( request.user), token=request.token) notifica...
IOError
dataset/ETHPy150Open google/grr/grr/gui/plugins/notifications.py/NotificationCount.RenderAjax
5,522
def GetUserSettings(self, request): try: user_record = aff4.FACTORY.Open( aff4.ROOT_URN.Add("users").Add(request.user), "GRRUser", token=request.token) return user_record.Get(user_record.Schema.GUI_SETTINGS) except __HOLE__: return aff4.GRRUser.SchemaCls.GUI_SETTINGS()
IOError
dataset/ETHPy150Open google/grr/grr/gui/plugins/notifications.py/UserSettingsDialog.GetUserSettings
5,523
def BuildTable(self, start_row, end_row, request): """Add all the notifications to this table.""" row_index = 0 search_term = request.REQ.get("sSearch") # We modify this object by changing the notification from pending to # shown. try: user_fd = aff4.FACTORY.Open(aff4.ROOT_URN.Add("users"...
IOError
dataset/ETHPy150Open google/grr/grr/gui/plugins/notifications.py/ViewNotifications.BuildTable
5,524
def handle(self, *args, **options): path = options.get('path') @transaction.atomic def do_backup(src_path, dest_path): # perform a simple file-copy backup of the database # first we need a shared lock on the database, issuing a select() # will do this for us ...
IOError
dataset/ETHPy150Open OpenSlides/OpenSlides/openslides/core/management/commands/backupdb.py/Command.handle
5,525
def enableDebug(globals_dict): templates = dict(globals_dict) class TemplateWrapper: """ Wrapper around templates. To better trace and control template usage. """ def __init__(self, name, value): self.name = name self.value = value def __st...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/codegen/templates/TemplateDebugWrapper.py/enableDebug
5,526
def setUp(self): self.__stdoutSaved = sys.stdout try: from StringIO import StringIO except __HOLE__: from io import StringIO self.__out = StringIO() sys.stdout = self.__out
ImportError
dataset/ETHPy150Open Cimpress-MCP/JustReleaseNotes/tests/artifacters/GitHubReleases_Test.py/GitHubReleases_Test.setUp
5,527
def sites_google_site_proxyfree4u(self): proxies = [] url = "https://sites.google.com/site/proxyfree4u/proxy-list?offset=" # fetch the latest 10 pages for i in range(0, 100, 10): # print url + str(i) soup = BeautifulSoup(self.getpage(url + str(i))) htt...
HTTPError
dataset/ETHPy150Open owtf/owtf/framework/http/proxy/outbound_proxyminer.py/Proxy_Miner.sites_google_site_proxyfree4u
5,528
def clean(self, value): "Since the ProductSelectField does not specify choices by itself, accept any returned value" try: return int(value) except __HOLE__: pass
ValueError
dataset/ETHPy150Open awesto/django-shop/shop/cascade/plugin_base.py/ProductSelectField.clean
5,529
def set_initial_product(self, initial): try: # check if that product still exists, otherwise return nothing Model = apps.get_model(*initial['link']['model'].split('.')) initial['product'] = Model.objects.get(pk=initial['link']['pk']).pk except (KeyError, __HOLE__, Mod...
ValueError
dataset/ETHPy150Open awesto/django-shop/shop/cascade/plugin_base.py/CatalogLinkForm.set_initial_product
5,530
def get_render_template(self, context, instance, placeholder): render_type = instance.glossary.get('render_type') if render_type not in ('form', 'summary',): render_type = 'form' try: template_names = [ '{0}/checkout/{1}'.format(shop_settings.APP_LABEL, se...
AttributeError
dataset/ETHPy150Open awesto/django-shop/shop/cascade/plugin_base.py/DialogFormPluginBase.get_render_template
5,531
def create_schema(storage_index_url): # making three tries, in case of communication errors with elasticsearch for _ in xrange(3): try: # delete index if already exist response = requests.head(storage_index_url) if response.status_code == 200: response...
HTTPError
dataset/ETHPy150Open cloudify-cosmo/cloudify-manager/tests/testenv/es_schema_creator.py/create_schema
5,532
def getGameSpeed(self): try: return self.gameSpeed except __HOLE__: self.gameSpeed = 0 return self.gameSpeed
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getGameSpeed
5,533
def getTalentsReader(self): try: return self.talentsReader except __HOLE__: replayVersion = self.reader.getReplayProtocolVersion() try: self.talentsReader = __import__('stormreplay.talents%s' % replayVersion, fromlist=['talents']) except Im...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getTalentsReader
5,534
def getTalents(self): try: return self.talents except __HOLE__: self.talents = [[] for _ in xrange(10)] talentsReader = self.getTalentsReader() generator = talentsReader.decode_game_events_talent_choices(self.reader.getReplayGameEvents(), self.getPlayersHe...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getTalents
5,535
def getTeamTalentTierTimes(self): try: return self.teamTalentTierTimes except __HOLE__: teamTalentTierLevel = [[], []] teamTalentTiersFirstPick = [[], []] teamTalentTiersLastPick = [[], []] players = self.getPlayers() for playerInde...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getTeamTalentTierTimes
5,536
def getTeamLevels(self): try: return self.teamLevels except __HOLE__: teamTalentTierTimes = self.getTeamTalentTierTimes() self.teamLevels = [[], []] for teamIndex in xrange(2): talentTierTimes = teamTalentTierTimes[teamIndex] ...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getTeamLevels
5,537
def getMapName(self): try: return self.mapName except __HOLE__: self.mapName = self.reader.getReplayDetails()['m_title']['utf8'] return self.mapName
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getMapName
5,538
def getPlayersHeroChoiceArray(self): try: return self.playersHeroArray except __HOLE__: self.playersHeroArray = [None] * 10 for i, player in enumerate(self.getPlayerSpawnInfo()): self.playersHeroArray[i] = player['hero'] return self.playersHero...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getPlayersHeroChoiceArray
5,539
def getPlayers(self): try: return self.players except __HOLE__: self.players = [None] * 10 for i, player in enumerate(self.getReplayDetails()['m_playerList']): #TODO: confirm that m_workingSetSlotId == i always toon = player['m_toon'] ...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getPlayers
5,540
def getPlayerSpawnInfo(self): try: return self.playerSpawnInfo except __HOLE__: self.playerSpawnInfo = [None] * 10 playerIdToUserId = {} for event in self.getReplayTrackerEvents(): if event['_event'] == 'NNet.Replay.Tracker.SPlayerSetupEven...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getPlayerSpawnInfo
5,541
def getMatchUTCTimestamp(self): try: return self.utcTimestamp except __HOLE__: self.utcTimestamp = (self.getReplayDetails()['m_timeUTC'] / 10000000) - 11644473600 return self.utcTimestamp
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getMatchUTCTimestamp
5,542
def getChat(self): try: return self.chat except __HOLE__: self.chat = [] for messageEvent in self.getReplayMessageEvents(): if (messageEvent['_event'] != 'NNet.Game.SChatMessage'): continue userId = messageEvent['_us...
AttributeError
dataset/ETHPy150Open karlgluck/heroes-of-the-storm-replay-parser/stormreplay/analyzer.py/StormReplayAnalyzer.getChat
5,543
@app.route('/metrics', methods=methods) @app.route('/metrics/find', methods=methods) def metrics_find(): errors = {} from_time = None until_time = None wildcards = False try: wildcards = bool(int(RequestParams.get('wildcards', 0))) except ValueError: errors['wildcards'] = 'must ...
ValueError
dataset/ETHPy150Open brutasse/graphite-api/graphite_api/app.py/metrics_find
5,544
@app.route('/metrics/expand', methods=methods) def metrics_expand(): errors = {} try: group_by_expr = bool(int(RequestParams.get('groupByExpr', 0))) except ValueError: errors['groupByExpr'] = 'must be 0 or 1.' try: leaves_only = bool(int(RequestParams.get('leavesOnly', 0))) e...
ValueError
dataset/ETHPy150Open brutasse/graphite-api/graphite_api/app.py/metrics_expand
5,545
@app.route('/render', methods=methods) def render(): errors = {} graph_options = { 'width': 600, 'height': 300, } request_options = {} graph_type = RequestParams.get('graphType', 'line') try: graph_class = GraphTypes[graph_type] request_options['graphType'] = grap...
ValueError
dataset/ETHPy150Open brutasse/graphite-api/graphite_api/app.py/render
5,546
def test_pickling(self): try: self.stream = cPickle.loads(cPickle.dumps(self.stream)) server_data = self.stream.get_epoch_iterator() expected_data = get_stream().get_epoch_iterator() for _, s, e in zip(range(3), server_data, expected_data): for dat...
AssertionError
dataset/ETHPy150Open mila-udem/fuel/tests/test_server.py/TestServer.test_pickling
5,547
def is_wxpython_installed(): """Returns True if wxpython is installed""" try: return __import__("wx") except __HOLE__: return False
ImportError
dataset/ETHPy150Open weecology/retriever/setup.py/is_wxpython_installed
5,548
def _addAuthLevelAlias(self, auth_level_uri, alias=None): """Add an auth level URI alias to this request. @param auth_level_uri: The auth level URI to send in the request. @param alias: The namespace alias to use for this auth level in this message. May be None if the a...
KeyError
dataset/ETHPy150Open necaris/python3-openid/openid/extensions/draft/pape5.py/PAPEExtension._addAuthLevelAlias
5,549
def parseExtensionArgs(self, args, is_openid1, strict=False): """Set the state of this request to be that expressed in these PAPE arguments @param args: The PAPE arguments without a namespace @param strict: Whether to raise an exception if the input is out of spec or otherw...
ValueError
dataset/ETHPy150Open necaris/python3-openid/openid/extensions/draft/pape5.py/Request.parseExtensionArgs
5,550
def _getNISTAuthLevel(self): try: return int(self.getAuthLevel(LEVELS_NIST)) except __HOLE__: return None
KeyError
dataset/ETHPy150Open necaris/python3-openid/openid/extensions/draft/pape5.py/Response._getNISTAuthLevel
5,551
def parseExtensionArgs(self, args, is_openid1, strict=False): """Parse the provider authentication policy arguments into the internal state of this object @param args: unqualified provider authentication policy arguments @param strict: Whether to raise an exception when bad...
KeyError
dataset/ETHPy150Open necaris/python3-openid/openid/extensions/draft/pape5.py/Response.parseExtensionArgs
5,552
def get_filename(metadata, directory=None, ext="txt"): """Construct data file name from a metadata dictionary. Returns the file name, as a string. """ metadata = metadata.copy() name = metadata.pop("name", "data") directory = metadata.pop("directory", directory) try: timestamp = met...
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/datafile.py/get_filename
5,553
def compare_metadata(self, other, namelist, missingok=True): for name in namelist: try: if other[name] != self[name]: return False except __HOLE__: if not missingok: return False return True
KeyError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/datafile.py/DataFileData.compare_metadata
5,554
def worker(inqueue, outqueue, initializer=None, initargs=(), maxtasks=None): assert maxtasks is None or (type(maxtasks) == int and maxtasks > 0) put = outqueue.put get = inqueue.get if hasattr(inqueue, '_writer'): inqueue._writer.close() outqueue._reader.close() if initializer is no...
IOError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/multiprocessing/pool.py/worker
5,555
def __init__(self, processes=None, initializer=None, initargs=(), maxtasksperchild=None): self._setup_queues() self._taskqueue = queue.Queue() self._cache = {} self._state = RUN self._maxtasksperchild = maxtasksperchild self._initializer = initializer ...
NotImplementedError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/multiprocessing/pool.py/Pool.__init__
5,556
@staticmethod def _handle_tasks(taskqueue, put, outqueue, pool): thread = threading.current_thread() for taskseq, set_length in iter(taskqueue.get, None): i = -1 for i, task in enumerate(taskseq): if thread._state: debug('task handler foun...
IOError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/multiprocessing/pool.py/Pool._handle_tasks
5,557
@staticmethod def _handle_results(outqueue, get, cache): thread = threading.current_thread() while 1: try: task = get() except (IOError, EOFError): debug('result handler got EOFError/IOError -- exiting') return if ...
IOError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/multiprocessing/pool.py/Pool._handle_results
5,558
def next(self, timeout=None): self._cond.acquire() try: try: item = self._items.popleft() except __HOLE__: if self._index == self._length: raise StopIteration self._cond.wait(timeout) try: ...
IndexError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/multiprocessing/pool.py/IMapIterator.next
5,559
def import_or_raise(pkg_or_module_string, ExceptionType, *args, **kwargs): try: return __import__(pkg_or_module_string) except __HOLE__: raise ExceptionType(*args, **kwargs)
ImportError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/import_or_raise
5,560
def ensure_dir(path): """os.path.makedirs without EEXIST.""" try: os.makedirs(path) except __HOLE__ as e: if e.errno != errno.EEXIST: raise
OSError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/ensure_dir
5,561
def get_prog(): try: if os.path.basename(sys.argv[0]) in ('__main__.py', '-c'): return "%s -m pip" % sys.executable except (AttributeError, __HOLE__, IndexError): pass return 'pip' # Retry every half second for up to 3 seconds
TypeError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/get_prog
5,562
def renames(old, new): """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, tail = os.path.split(old) i...
OSError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/renames
5,563
def untar_file(filename, location): """ Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmo...
KeyError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/untar_file
5,564
def read_text_file(filename): """Return the contents of *filename*. Try to decode the file contents with utf-8, the preferred system encoding (e.g., cp1252 on some Windows machines), and latin1, in that order. Decoding a byte string with latin1 will never raise an error. In the worst case, the retu...
UnicodeDecodeError
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/read_text_file
5,565
def readline(self): try: try: return next(self._gen) except NameError: return self._gen.next() except __HOLE__: return ''
StopIteration
dataset/ETHPy150Open anzev/hedwig/build/pip/pip/utils/__init__.py/FakeFile.readline
5,566
def run_test(base_path, plots_path, test_name, params): def safe_add_key(args, key, name): if name in params: args.extend((key, str(params[name]))) def safe_add_path(args, folder, key, name): if name in params: args.extend((key, os.path.join(folder, params[name]))) ...
KeyError
dataset/ETHPy150Open tp7/Sushi/regression-tests.py/run_test
5,567
def run(): root_logger.setLevel(logging.DEBUG) global console_handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter('%(message)s')) root_logger.addHandler(console_handler) try: with open('tests.json') a...
IOError
dataset/ETHPy150Open tp7/Sushi/regression-tests.py/run
5,568
def process_token_request(r, decoder, *args): try: data = decoder(r.content) return tuple(data[key] for key in args) except __HOLE__ as e: # pragma: no cover bad_key = e.args[0] raise KeyError(PROCESS_TOKEN_ERROR.format(key=bad_key, raw=r.content))
KeyError
dataset/ETHPy150Open litl/rauth/rauth/service.py/process_token_request
5,569
def transkey(self, keyname): self.logger.debug("key name in tk '%s'" % (keyname)) try: return self._keytbl[keyname.lower()] except __HOLE__: return keyname
KeyError
dataset/ETHPy150Open ejeschke/ginga/ginga/tkw/ImageViewTk.py/ImageViewEvent.transkey
5,570
def _entity_criterion(self, entity): #if hasattr(entity, "property"): # entity = entity.property.mapper if hasattr(entity, 'parententity'): # XXX is this used? entity = entity.parententity try: cls = _class_to_mapper(entity).class_ except __...
AttributeError
dataset/ETHPy150Open SmartTeleMax/iktomi/iktomi/unstable/db/sqla/public_query.py/PublicQuery._entity_criterion
5,571
def check(self, code, filename): """Run pep8 on code and return the output.""" options = { 'reporter': self.get_report() } type_map = { 'select': [], 'ignore': [], 'max-line-length': 0, 'max-complexity': 0 } se...
SystemExit
dataset/ETHPy150Open SublimeLinter/SublimeLinter-pep8/linter.py/PEP8.check
5,572
def __init__(self, headers, body=''): # first of all, lets make sure that if headers or body are # unicode strings, it must be converted into a utf-8 encoded # byte string self.raw_headers = utf8(headers.strip()) self.body = utf8(body) # Now let's concatenate the headers...
UnicodeDecodeError
dataset/ETHPy150Open gabrielfalcao/HTTPretty/httpretty/core.py/HTTPrettyRequest.__init__
5,573
def connect(self, address): self._closed = False try: self._address = (self._host, self._port) = address except __HOLE__: # We get here when the address is just a string pointing to a # unix socket path/file # ...
ValueError
dataset/ETHPy150Open gabrielfalcao/HTTPretty/httpretty/core.py/fakesock.socket.connect
5,574
def sendall(self, data, *args, **kw): self._sent_data.append(data) self.fd = FakeSockFile() self.fd.socket = self try: requestline, _ = data.split(b'\r\n', 1) method, path, version = parse_requestline( decode_utf8(reques...
ValueError
dataset/ETHPy150Open gabrielfalcao/HTTPretty/httpretty/core.py/fakesock.socket.sendall
5,575
def validate(self): content_length_keys = 'Content-Length', 'content-length' for key in content_length_keys: got = self.adding_headers.get( key, self.forcing_headers.get(key, None)) if got is None: continue try: igot =...
TypeError
dataset/ETHPy150Open gabrielfalcao/HTTPretty/httpretty/core.py/Entry.validate
5,576
@classmethod @contextlib.contextmanager def record(cls, filename, indentation=4, encoding='utf-8'): try: import urllib3 except __HOLE__: msg = ( 'HTTPretty requires urllib3 installed ' 'for recording actual requests.' ) ...
ImportError
dataset/ETHPy150Open gabrielfalcao/HTTPretty/httpretty/core.py/httpretty.record
5,577
def get_app_commands(app): try: app_command_module = importlib.import_module(app + '.commands') except __HOLE__: return [] ret = {} for command in getattr(app_command_module, 'commands', []): ret[command.name] = command return ret
ImportError
dataset/ETHPy150Open frappe/frappe/frappe/utils/bench_helper.py/get_app_commands
5,578
def start_tracker(): """Start the Torrent Tracker. """ # parse commandline options parser = OptionParser() parser.add_option('-p', '--port', help='Tracker Port', default=0) parser.add_option('-b', '--background', action='store_true', default=False, help='Start in background...
KeyboardInterrupt
dataset/ETHPy150Open semk/Pytt/pytt/tracker.py/start_tracker
5,579
def xhtmlValidate(modelXbrl, elt): from lxml.etree import DTD, XMLSyntaxError from arelle import FunctionIxt ixNsStartTags = ["{" + ns + "}" for ns in XbrlConst.ixbrlAll] isEFM = modelXbrl.modelManager.disclosureSystem.validationType == "EFM" # find ix version for messages _ixNS = elt.modelDocum...
KeyError
dataset/ETHPy150Open Arelle/Arelle/arelle/XhtmlValidate.py/xhtmlValidate
5,580
def ignore_not_implemented(func): def _inner(*args, **kwargs): try: return func(*args, **kwargs) except __HOLE__: return None functional.update_wrapper(_inner, func) return _inner
NotImplementedError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/introspection/tests.py/ignore_not_implemented
5,581
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): """ Double fork-trick. For starting a posix daemon. This forks the current process into a daemon. The stdin, stdout, and stderr arguments are file names that will be opened and be used to replace the standard file descriptors...
OSError
dataset/ETHPy150Open jonathanslenders/pymux/pymux/utils.py/daemonize
5,582
def __cmp__(cls, other): # If the other object is not a Basic subclass, then we are not equal to # it. if not isinstance(other, BasicMeta): return -1 n1 = cls.__name__ n2 = other.__name__ if n1 == n2: return 0 UNKNOWN = len(ordering_of_cla...
ValueError
dataset/ETHPy150Open sympy/sympy/sympy/core/core.py/BasicMeta.__cmp__
5,583
def get_cluster_or_404(id): try: name = id cluster = CLUSTERS.get()[name] except (__HOLE__, ValueError): raise Http404() cluster = { 'id': id, 'nice_name': id, 'host_ports': cluster.HOST_PORTS.get(), 'rest_url': cluster.REST_URL.get(), } return cluster
TypeError
dataset/ETHPy150Open cloudera/hue/apps/zookeeper/src/zookeeper/utils.py/get_cluster_or_404
5,584
def GetValue(self): "Get the value from the editor" s = wx.TextCtrl.GetValue(self).strip() try: return int(s) except __HOLE__: return None
ValueError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/lib/oldOlv/CellEditor.py/IntEditor.GetValue
5,585
def GetValue(self): "Get the value from the editor" s = wx.TextCtrl.GetValue(self).strip() try: return long(s) except __HOLE__: return None
ValueError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/lib/oldOlv/CellEditor.py/LongEditor.GetValue
5,586
def GetValue(self): "Get the value from the editor" s = wx.TextCtrl.GetValue(self).strip() try: return float(s) except __HOLE__: return None
ValueError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/lib/oldOlv/CellEditor.py/FloatEditor.GetValue
5,587
def _ParseDateTime(self, s): # Try the installed format string first try: return datetime.datetime.strptime(s, self.formatString) except __HOLE__: pass for x in self.STD_SEPARATORS: s = s.replace(x, " ") # Because of the logic of st...
ValueError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/lib/oldOlv/CellEditor.py/DateTimeEditor._ParseDateTime
5,588
def GetValue(self): "Get the value from the editor" s = wx.TextCtrl.GetValue(self).strip() fmts = self.STD_TIME_FORMATS[:] if self.formatString not in fmts: fmts.insert(0, self.formatString) for fmt in fmts: try: dt = datetime.datet...
ValueError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/lib/oldOlv/CellEditor.py/TimeEditor.GetValue
5,589
def test_adds_skip(self): result = self._make_one() try: result.addSkip(FakeTestCase(), 'a reason') self.assertEqual( len(result.tracker._test_cases['FakeTestCase']), 1) except __HOLE__: self.assertTrue(True, 'Python 2.6 does not support skip.'...
AttributeError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_result.py/TestTAPTestResult.test_adds_skip
5,590
def test_adds_expected_failure(self): result = self._make_one() try: result.addExpectedFailure(FakeTestCase(), (None, None, None)) line = result.tracker._test_cases['FakeTestCase'][0] self.assertEqual(line.status, 'not ok') self.assertEqual(line.directive,...
AttributeError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_result.py/TestTAPTestResult.test_adds_expected_failure
5,591
def test_adds_unexpected_success(self): result = self._make_one() try: result.addUnexpectedSuccess(FakeTestCase()) line = result.tracker._test_cases['FakeTestCase'][0] self.assertEqual(line.status, 'ok') self.assertEqual(line.directive, '(unexpected succes...
AttributeError
dataset/ETHPy150Open mblayman/tappy/tap/tests/test_result.py/TestTAPTestResult.test_adds_unexpected_success
5,592
def __getattr__(self, name): """ Gets an attribute of this fake module from its attrs. @raise AttributeError: When the requested attribute is missing. """ try: return self._attrs[name] except __HOLE__: raise AttributeError()
KeyError
dataset/ETHPy150Open twisted/twisted/twisted/python/test/test_dist.py/FakeModule.__getattr__
5,593
def __init__(self): try: import _winreg except __HOLE__: # Python 3 import winreg as _winreg if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! prgx = re.compil...
ImportError
dataset/ETHPy150Open pydata/numexpr/numexpr/cpuinfo.py/Win32CPUInfo.__init__
5,594
def deserialize(cassette_string, serializer): try: data = serializer.deserialize(cassette_string) # Old cassettes used to use yaml object thingy so I have to # check for some fairly stupid exceptions here except (__HOLE__, yaml.constructor.ConstructorError): _warn_about_old_cassette_form...
ImportError
dataset/ETHPy150Open kevin1024/vcrpy/vcr/serialize.py/deserialize
5,595
def validate(self, auto_migrate=False): if self.use_autorefs: if not auto_migrate: # don't make reference if auto_migrate is True because this # mean validate was called from __init__ and no collection is # found when validating at __init__ with autore...
KeyError
dataset/ETHPy150Open namlook/mongokit/mongokit/document.py/Document.validate
5,596
def one(self, *args, **kwargs): """ `one()` act like `find()` but will raise a `mongokit.MultipleResultsFound` exception if there is more than one result. If no document is found, `one()` returns `None` """ bson_obj = self.find(*args, **kwargs) count = bs...
StopIteration
dataset/ETHPy150Open namlook/mongokit/mongokit/document.py/Document.one
5,597
def to_json(self): """ convert the document into a json string and return it """ def _convert_to_python(doc, struct): for key in struct: if isinstance(struct[key], dict): if doc: # we don't need to process an empty doc ...
ImportError
dataset/ETHPy150Open namlook/mongokit/mongokit/document.py/Document.to_json
5,598
def from_json(self, json): """ convert a json string and return a SchemaDocument """ def _convert_to_python(doc, struct, path="", root_path=""): for key in struct: if type(key) is type: new_key = '$%s' % key.__name__ else: ...
ImportError
dataset/ETHPy150Open namlook/mongokit/mongokit/document.py/Document.from_json
5,599
@classmethod def parse(cls, image_name): result = cls() # registry.org/namespace/repo:tag s = image_name.split('/', 2) if len(s) == 2: if '.' in s[0] or ':' in s[0]: result.registry = s[0] else: result.namespace = s[0] ...
ValueError
dataset/ETHPy150Open projectatomic/atomic-reactor/atomic_reactor/util.py/ImageName.parse