Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,200
def run(self): '''Run loop''' logger.info("processor starting...") while not self._quit: try: task, response = self.inqueue.get(timeout=1) self.on_task(task, response) self._exceptions = 0 except Queue.Empty as e: ...
KeyboardInterrupt
dataset/ETHPy150Open binux/pyspider/pyspider/processor/processor.py/Processor.run
5,201
def handle(self, *args, **options): logger = logging.getLogger(__name__) logger.info('start django-sockjs-server') self.config = SockJSServerSettings() io_loop = tornado.ioloop.IOLoop.instance() router = SockJSRouterPika( SockJSConnection, self.config.li...
KeyboardInterrupt
dataset/ETHPy150Open alfss/django-sockjs-server/django_sockjs_server/management/commands/sockjs_server.py/Command.handle
5,202
def fake_virtual_interface_delete_by_instance(context, instance_id): vif = copy.copy(virtual_interfacees) addresses = [m for m in vif if m['instance_id'] == instance_id] try: for address in addresses: vif.remove(address) except __HOLE__: pass
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/tests/unit/db/fakes.py/fake_virtual_interface_delete_by_instance
5,203
def base_n_decoder(alphabet=ALPHABET): """Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding """ base = len(alphabet) char_value = dict(((c, v) for v, c in enumerate(alphabet))) def f(string): ...
KeyError
dataset/ETHPy150Open bbangert/velruse/velruse/app/baseconvert.py/base_n_decoder
5,204
def traverse_dot_path(self, traverser): if traverser.remaining_paths: new_value = None name = traverser.next_part try: new_value = self[int(name)] except __HOLE__: raise DotPathNotFound("Invalid index given, must be an integer") ...
ValueError
dataset/ETHPy150Open zbyte64/django-dockit/dockit/schema/common.py/DotPathList.traverse_dot_path
5,205
def traverse_dot_path(self, traverser): if traverser.remaining_paths: new_value = None name = traverser.next_part try: new_value = self[name] except __HOLE__: pass traverser.next(value=new_value) else: ...
KeyError
dataset/ETHPy150Open zbyte64/django-dockit/dockit/schema/common.py/DotPathDict.traverse_dot_path
5,206
@property def program_id(self): try: return self.kwargs['prog_id'] except __HOLE__: raise Http404()
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/programs/views.py/EditProgramView.program_id
5,207
def _undo_manager_default(self): """ Trait initializer. """ # We make sure the undo package is entirely optional. try: from apptools.undo.api import UndoManager except __HOLE__: return None return UndoManager()
ImportError
dataset/ETHPy150Open enthought/pyface/pyface/workbench/workbench.py/Workbench._undo_manager_default
5,208
@cached_property def url_patterns(self): # urlconf_module might be a valid set of patterns, so we default to it patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except __HOLE__: msg = ( "The includ...
TypeError
dataset/ETHPy150Open django/django/django/urls/resolvers.py/RegexURLResolver.url_patterns
5,209
def __init__(self): self.services = {"openvpn": self.openvpn, "rdp": self.rdp, "sshkey": self.sshkey, "vnckey": self.vnckey} self.crowbar_readme = "https://github.com/galkan/crowbar/blob/master/README.md" self.openvpn_path = "/usr/sbin/openvpn" self.vpn_failure = re.compile("SIGTERM\[so...
IOError
dataset/ETHPy150Open galkan/crowbar/lib/main.py/Main.__init__
5,210
def __init__(self, lock): """Constructor for _BaseCondition. @type lock: threading.Lock @param lock: condition base lock """ object.__init__(self) try: self._release_save = lock._release_save except __HOLE__: self._release_save = self._base_release_save try: self._ac...
AttributeError
dataset/ETHPy150Open ganeti/ganeti/lib/locking.py/_BaseCondition.__init__
5,211
def _json_convert(obj): """Recursive helper method that converts BSON types so they can be converted into json. """ from numpy import ndarray if hasattr(obj, 'iteritems') or hasattr(obj, 'items'): # PY3 support return SON(((k, _json_convert(v)) for k, v in obj.iteritems())) elif hasattr...
TypeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/casehandlers/pymongo_bson/json_util.py/_json_convert
5,212
def __getattr__(self, name): try: return self.__getattribute__(name) except __HOLE__: pass def dummy(*args, **kwargs): pass return dummy
AttributeError
dataset/ETHPy150Open Dav1dde/glad/glad/lang/common/loader.py/NullLoader.__getattr__
5,213
def extract_keyword_queries(store, label_store, folders, fid, sid, include_original=False): '''Transforms a folder structure into positive and negative examples to feed to ``linker.model.extract``. This transforms SortingDesk's foldering structure into *supervision* data for the extractor. This works ...
KeyError
dataset/ETHPy150Open dossier/dossier.models/dossier/models/linker/worker.py/extract_keyword_queries
5,214
def unquote(s): """ Undo the effects of quote(). Based heavily on urllib.unquote(). """ mychr = chr myatoi = int list = s.split('_') res = [list[0]] myappend = res.append del list[0] for item in list: if item[1:2]: try: myappend(mychr(myatoi(it...
ValueError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/admin/util.py/unquote
5,215
def get_deleted_objects(deleted_objects, perms_needed, user, obj, opts, current_depth, admin_site): "Helper function that recursively populates deleted_objects." nh = _nest_help # Bind to local variable for performance if current_depth > 16: return # Avoid recursing too deep. opts_seen = [] ...
ObjectDoesNotExist
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/admin/util.py/get_deleted_objects
5,216
def _SelectDownloadStrategy(dst_url): """Get download strategy based on the destination object. Args: dst_url: Destination StorageUrl. Returns: gsutil Cloud API DownloadStrategy. """ dst_is_special = False if dst_url.IsFileUrl(): # Check explicitly first because os.stat doesn't work on 'nul' i...
OSError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/_SelectDownloadStrategy
5,217
def _UploadFileToObjectResumable(src_url, src_obj_filestream, src_obj_size, dst_url, dst_obj_metadata, preconditions, gsutil_api, logger): """Uploads the file using a resumable strategy. Args: src_url: Source FileUrl to upload. Must not be a st...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/_UploadFileToObjectResumable
5,218
def _GetDownloadFile(dst_url, src_obj_metadata, logger): """Creates a new download file, and deletes the file that will be replaced. Names and creates a temporary file for this download. Also, if there is an existing file at the path where this file will be placed after the download is completed, that file wil...
OSError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/_GetDownloadFile
5,219
def _MaintainSlicedDownloadTrackerFiles(src_obj_metadata, dst_url, download_file_name, logger, api_selector, num_components): """Maintains sliced download tracker files in order to permit resumability. Reads or creates a sliced downloa...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/_MaintainSlicedDownloadTrackerFiles
5,220
def _ValidateAndCompleteDownload(logger, src_url, src_obj_metadata, dst_url, need_to_unzip, server_gzip, digesters, hash_algs, download_file_name, api_selector, bytes_transferred, gsutil_api): """Validates and performs ...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/_ValidateAndCompleteDownload
5,221
def _ParseManifest(self): """Load and parse a manifest file. This information will be used to skip any files that have a skip or OK status. """ try: if os.path.exists(self.manifest_path): with open(self.manifest_path, 'rb') as f: first_row = True reader = csv.reade...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/Manifest._ParseManifest
5,222
def _CreateManifestFile(self): """Opens the manifest file and assigns it to the file pointer.""" try: if ((not os.path.exists(self.manifest_path)) or (os.stat(self.manifest_path).st_size == 0)): # Add headers to the new file. with open(self.manifest_path, 'wb', 1) as f: ...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/gsutil/gslib/copy_helper.py/Manifest._CreateManifestFile
5,223
def reset(self): """ resets the storage if it supports being reset """ try: self._storage.reset() self.logger.info("Storage has be reset and all limits cleared") except __HOLE__: self.logger.warning("This storage type does not support being res...
NotImplementedError
dataset/ETHPy150Open alisaifee/flask-limiter/flask_limiter/extension.py/Limiter.reset
5,224
def __check_request_limit(self): endpoint = request.endpoint or "" view_func = current_app.view_functions.get(endpoint, None) name = ("%s.%s" % ( view_func.__module__, view_func.__name__ ) if view_func else "" ) if (not request.endpoint or ...
ValueError
dataset/ETHPy150Open alisaifee/flask-limiter/flask_limiter/extension.py/Limiter.__check_request_limit
5,225
def __limit_decorator(self, limit_value, key_func=None, shared=False, scope=None, per_method=False, methods=None, error_message=None, exempt_when=None): _sc...
ValueError
dataset/ETHPy150Open alisaifee/flask-limiter/flask_limiter/extension.py/Limiter.__limit_decorator
5,226
def ascend(self, obj, depth=1): """Return a nested list containing referrers of the given object.""" depth += 1 parents = [] # Gather all referrers in one step to minimize # cascading references due to repr() logic. refs = gc.get_referrers(obj) self.ignore.append...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/lib/gctools.py/ReferrerTree.ascend
5,227
def send_command_expect(self, command_string, expect_string=None, delay_factor=.2, max_loops=500, auto_find_prompt=True, strip_prompt=True, strip_command=True): ''' Send command to network device retrieve output until router_prompt or expect_string...
ValueError
dataset/ETHPy150Open ktbyers/netmiko/netmiko/base_connection.py/BaseSSHConnection.send_command_expect
5,228
def __init__(self, values, categories=None, ordered=False, name=None, fastpath=False, levels=None): if fastpath: # fast path self._codes = _coerce_indexer_dtype(values, categories) self._categories = self._validate_categories( categories, fas...
TypeError
dataset/ETHPy150Open pydata/pandas/pandas/core/categorical.py/Categorical.__init__
5,229
def map(self, mapper): """ Apply mapper function to its categories (not codes). Parameters ---------- mapper : callable Function to be applied. When all categories are mapped to different categories, the result will be Categorical which has th...
ValueError
dataset/ETHPy150Open pydata/pandas/pandas/core/categorical.py/Categorical.map
5,230
def is_dtype_equal(self, other): """ Returns True if categoricals are the same dtype same categories, and same ordered Parameters ---------- other : Categorical Returns ------- are_equal : boolean """ try: return (s...
TypeError
dataset/ETHPy150Open pydata/pandas/pandas/core/categorical.py/Categorical.is_dtype_equal
5,231
@follows( normaliseBAMs ) @files( [ (("%s/bam/%s.norm.bam" % (x, x.asFile()), "%s/bam/%s.norm.bam" % (getControl(x), getControl(x).asFile())), "%s/sicer/%s.sicer" % (x, x.asFile()) ) for x in TRACKS ] ) def runSICER( infiles, outfile ): '''Run SICER for peak detection.''' infile, controlfile = infil...
OSError
dataset/ETHPy150Open CGATOxford/cgat/obsolete/zinba.py/runSICER
5,232
@follows( dedup ) @files( [ (("%s/bam/%s.norm.bam" % (x, x.asFile()), "%s/bam/%s.norm.bam" % (getControl(x), getControl(x).asFile())), "%s/zinba/%s.peaks" % (x, x.asFile()) ) for x in TRACKS ] ) def runZinba( infiles, outfile ): '''Run Zinba for peak detection.''' infile, controlfile = infiles t...
OSError
dataset/ETHPy150Open CGATOxford/cgat/obsolete/zinba.py/runZinba
5,233
def get_customer(request): """Returns the customer for the given request (which means for the current logged in user/or the session user). """ try: return request.customer except __HOLE__: customer = request.customer = _get_customer(request) return customer
AttributeError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/customer/utils.py/get_customer
5,234
def _get_customer(request): user = request.user if user.is_authenticated(): try: return Customer.objects.get(user=user) except __HOLE__: return None else: session_key = request.session.session_key try: return Customer.objects.get(session=se...
ObjectDoesNotExist
dataset/ETHPy150Open diefenbach/django-lfs/lfs/customer/utils.py/_get_customer
5,235
def update_customer_after_login(request): """Updates the customer after login. 1. If there is no session customer, nothing has to be done. 2. If there is a session customer and no user customer we assign the session customer to the current user. 3. If there is a session customer and a user custo...
ObjectDoesNotExist
dataset/ETHPy150Open diefenbach/django-lfs/lfs/customer/utils.py/update_customer_after_login
5,236
def run(self): """This is the main serving loop.""" if self._stats.error: self._transmit_error() self._close() return self._parse_options() if self._options: self._transmit_oack() else: self._next_block() sel...
KeyboardInterrupt
dataset/ETHPy150Open facebook/fbtftp/fbtftp/base_handler.py/BaseHandler.run
5,237
def clean(self, value): """ (Try to) parse JSON string back to python. """ if isinstance(value, six.string_types): if value == "": value = None try: value = json.loads(value) except __HOLE__: raise ValidationError("Could...
ValueError
dataset/ETHPy150Open potatolondon/djangae/djangae/forms/fields.py/JSONFormField.clean
5,238
@classmethod def to_python(cls, value, model_ref=None, pk=None): if model_ref is None: if value is None: return None if isinstance(value, models.Model): return value model_ref, pk = decode_pk(value) try: pk = int(pk) ...
ValueError
dataset/ETHPy150Open potatolondon/djangae/djangae/forms/fields.py/GenericRelationFormfield.to_python
5,239
def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to ...
AttributeError
dataset/ETHPy150Open kleientertainment/ds_mod_tools/pkg/win32/Python27/Lib/encodings/__init__.py/search_function
5,240
def parse_backend_conf(backend, **kwargs): """ Helper function to parse the backend configuration that doesn't use the URI notation. """ # Try to get the CACHES entry for the given backend name first conf = settings.CACHES.get(backend, None) if conf is not None: args = conf.copy() ...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/cache/__init__.py/parse_backend_conf
5,241
def get_cache(backend, **kwargs): """ Function to load a cache backend dynamically. This is flexible by design to allow different use cases: To load a backend with the old URI-based notation:: cache = get_cache('locmem://') To load a backend that is pre-defined in the settings:: ...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/cache/__init__.py/get_cache
5,242
def __getattr__(self, key): try: return self.data[key] except __HOLE__: raise AttributeError("'%s' object has no attribute '%s'" % ( self.__class__.__name__, key))
KeyError
dataset/ETHPy150Open ask/carrot/tests/test_django.py/DictWrapper.__getattr__
5,243
def test_DjangoBrokerConnection(self): try: from django.conf import settings except __HOLE__: sys.stderr.write( "Django is not installed. \ Not testing django specific features.\n") return configured_or_configure(settings, ...
ImportError
dataset/ETHPy150Open ask/carrot/tests/test_django.py/TestDjangoSpecific.test_DjangoBrokerConnection
5,244
def get_attribution(lang_scr_ext): if not ATTRIBUTION_DATA: attribution_path = path.join(TOOLS_DIR, 'sample_texts', 'attributions.txt') with open(attribution_path, 'r') as f: data = f.readlines() for line in data: line = line.strip() if not line or line[0] == '#': continue ...
KeyError
dataset/ETHPy150Open googlei18n/nototools/nototools/generate_website_2_data.py/get_attribution
5,245
def save_map(map_name, base_dir=MAP_DIR, only_cached=True): _map_dir = os.path.join(base_dir, map_name) #if base_dir == DATA_DIR: # _map_dir = os.path.join(_map_dir, map_name) try: os.makedirs(_map_dir) except: pass for light in WORLD_INFO['lights']: if 'los' in light: del light['los']...
TypeError
dataset/ETHPy150Open flags/Reactor-3/maps.py/save_map
5,246
def has_gravatar(email): """ Returns True if the user has a gravatar, False if otherwise """ # Request a 404 response if the gravatar does not exist url = get_gravatar_url(email, default=GRAVATAR_DEFAULT_IMAGE_404) # Verify an OK response was received try: request = Request(url) ...
HTTPError
dataset/ETHPy150Open twaddington/django-gravatar/django_gravatar/helpers.py/has_gravatar
5,247
def install_twisted(): """ If twisted is available, make `emit' return a DeferredList This has been successfully tested with Twisted 14.0 and later. """ global emit, _call_partial try: from twisted.internet import defer emit = _emit_twisted _call_partial = defer.maybeDef...
ImportError
dataset/ETHPy150Open shaunduncan/smokesignal/smokesignal.py/install_twisted
5,248
def render(self, name, value, attrs=None): # no point trying to come up with sensible semantics for when 'id' is missing from attrs, # so let's make sure it fails early in the process try: id_ = attrs['id'] except (KeyError, __HOLE__): raise TypeError("WidgetWithS...
TypeError
dataset/ETHPy150Open torchbox/wagtail/wagtail/utils/widgets.py/WidgetWithScript.render
5,249
def whoami(hostname=MYHOSTNAME): """Given a hostname return the Romeo object""" try: for host in foundation.RomeoKeyValue.search('HOSTNAME', value=hostname): for ancestor in host.ANCESTORS: if ancestor.KEY != 'SERVER': continue return ancestor except __HOL...
IndexError
dataset/ETHPy150Open OrbitzWorldwide/droned/romeo/lib/romeo/__init__.py/whoami
5,250
def __getattr__(self, param): #compatibility hack try: return self._data[param] except __HOLE__: raise AttributeError("%s has no attribute \"%s\"" % (self, param))
KeyError
dataset/ETHPy150Open OrbitzWorldwide/droned/romeo/lib/romeo/__init__.py/_Romeo.__getattr__
5,251
def dump(self, obj, tag = None, typed = 1, ns_map = {}): if Config.debug: print "In dump.", "obj=", obj ns_map = ns_map.copy() self.depth += 1 if type(tag) not in (NoneType, StringType, UnicodeType): raise KeyError, "tag must be a string or None" if isinstance(obj, an...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/SOAPpy/SOAPBuilder.py/SOAPBuilder.dump
5,252
def get_products_from_tiids(tiids, ignore_order=False): # @ignore_order makes it slightly faster by not sorting if not tiids: return [] unsorted_products = Product.query.filter(Product.tiid.in_(tiids)).all() ret = [] if ignore_order: ret = unsorted_products else: ...
IndexError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/get_products_from_tiids
5,253
@cached_property def clean_biblio_dedup_dict(self): dedup_key_dict = {} try: dedup_key_dict["title"] = remove_unneeded_characters(self.biblio.display_title).lower() except (__HOLE__, TypeError): dedup_key_dict["title"] = self.biblio.display_title dedup_key_dic...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.clean_biblio_dedup_dict
5,254
@cached_property def is_true_product(self): try: if self.biblio.is_account: return False except __HOLE__: pass return True
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.is_true_product
5,255
@cached_property def genre_icon(self): try: return configs.genre_icons[self.genre] except __HOLE__: return configs.genre_icons["unknown"] #@cached_property #def genre_url_representation(self): # return self.display_genre_plural
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.genre_icon
5,256
@cached_property def mendeley_discipline(self): top_discipline = None discipline_snaps = [snap for snap in self.snaps if snap.provider=="mendeley" and snap.interaction=="discipline"] if discipline_snaps: most_recent_discipline_snap = sorted( discipline_sna...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.mendeley_discipline
5,257
@cached_property def is_account_product(self): try: if self.biblio.is_account: return True except __HOLE__: pass return False
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.is_account_product
5,258
@cached_property def latest_diff_timestamp(self): ts_list = [m.latest_nonzero_refresh_timestamp for m in self.metrics] if not ts_list: return None try: return sorted(ts_list, reverse=True)[0] except __HOLE__: return None
IndexError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.latest_diff_timestamp
5,259
@cached_property def countries(self): my_countries = countries.CountryList() try: country_data = self.get_metric_raw_value("altmetric_com", "demographics")["geo"]["twitter"] for country in country_data: my_countries.add_from_metric( countr...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.countries
5,260
def has_metric_this_good(self, provider, interaction, count): requested_metric = self.get_metric_by_name(provider, interaction) try: return requested_metric.display_count >= count except __HOLE__: return False
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.has_metric_this_good
5,261
def get_pdf(self): if self.has_file: return self.get_file() try: pdf_url = self.get_pdf_url() if pdf_url: r = requests.get(pdf_url, timeout=10) return r.content except (__HOLE__, requests.exceptions.Timeout): pass ...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.get_pdf
5,262
def get_embed_markup(self): # logger.debug(u"in get_embed_markup for {tiid}".format( # tiid=self.tiid)) if self.is_account_product: return None html = None if self.aliases and self.aliases.best_url and "github" in self.aliases.best_url: html = embed...
RuntimeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.get_embed_markup
5,263
def to_markup_dict(self, markup, hide_keys=None, show_keys="all"): keys_to_show = [ "tiid", "aliases", "biblio", "awards", "genre", "genre_icon", "display_genre_plural", "countries_str", # for sorting ...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/Product.to_markup_dict
5,264
def refresh_status(tiid, myredis): task_ids = myredis.get_provider_task_ids(tiid) if not task_ids: status = "SUCCESS: no recent refresh" return {"short": status, "long": status} statuses = {} if "STARTED" in task_ids: if (len(task_ids) > 1): task_ids.remove("STARTE...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/refresh_status
5,265
def refresh_products_from_tiids(profile_id, tiids, analytics_credentials={}, source="webapp"): # assume the profile is the same one as the first product if not profile_id: temp_profile = Product.query.get(tiids[0]) profile_id = temp_profile.profile_id from totalimpactwebapp.profile impo...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpactwebapp/product.py/refresh_products_from_tiids
5,266
def _try_services(self, method_name, *args, **kwargs): """ Try each service until one returns a response. This function only catches the bare minimum of exceptions from the service class. We want exceptions to be raised so the service classes can be debugged and fixed quickly. ...
TypeError
dataset/ETHPy150Open priestc/moneywagon/moneywagon/core.py/AutoFallbackFetcher._try_services
5,267
def get_optimal_services(crypto, type_of_service): from .crypto_data import crypto_data try: # get best services from curated list return crypto_data[crypto.lower()]['services'][type_of_service] except __HOLE__: raise ValueError("Invalid cryptocurrency symbol: %s" % crypto)
KeyError
dataset/ETHPy150Open priestc/moneywagon/moneywagon/core.py/get_optimal_services
5,268
def get_magic_bytes(crypto): from .crypto_data import crypto_data try: pub_byte = crypto_data[crypto]['address_version_byte'] priv_byte = crypto_data[crypto]['private_key_prefix'] if priv_byte >= 128: priv_byte -= 128 #pybitcointools bug return pub_byte, priv_byte ...
KeyError
dataset/ETHPy150Open priestc/moneywagon/moneywagon/core.py/get_magic_bytes
5,269
def getRhymingWord(self, curLine, person): """What word should go on the end of this line so it rhymes with the previous?""" try: rhymeLine = self.getRhymeLine(curLine) except __HOLE__: return None rhymeWord = self.poem[rhymeLine].split()[-1] ...
ValueError
dataset/ETHPy150Open capnrefsmmat/seuss/rhyme.py/RhymingMarkovGenerator.getRhymingWord
5,270
def validate_number(self, number): try: number = int(number) except (TypeError, __HOLE__): raise PageNotAnInteger('That page number is not an integer') if number < 1: raise EmptyPage('That page number is less than 1') return number
ValueError
dataset/ETHPy150Open CenterForOpenScience/scrapi/api/webview/pagination.py/PaginatorWithoutCount.validate_number
5,271
def parseargs(): global DEBUGSTREAM try: opts, args = getopt.getopt( sys.argv[1:], 'nVhc:d', ['class=', 'nosetuid', 'version', 'help', 'debug']) except getopt.error, e: usage(1, e) options = Options() for opt, arg in opts: if opt in ('-h', '--help'): ...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/smtpd.py/parseargs
5,272
def run_tests(): import django from django.conf import global_settings from django.conf import settings settings.configure( INSTALLED_APPS=[ 'corsheaders', ], DATABASES={ 'default': { 'ENGINE': 'django.db.backends.sqlite3', ...
ImportError
dataset/ETHPy150Open ottoyiu/django-cors-headers/tests.py/run_tests
5,273
def run(self): logger.debug('Proxying connection %r at address %r' % (self.client.conn, self.client.addr)) try: self._process() except __HOLE__: pass except Exception as e: logger.exception('Exception while handling connection %r with reason %r' % (sel...
KeyboardInterrupt
dataset/ETHPy150Open abhinavsingh/proxy.py/proxy.py/Proxy.run
5,274
def main(): parser = argparse.ArgumentParser( description='proxy.py v%s' % __version__, epilog='Having difficulty using proxy.py? Report at: %s/issues/new' % __homepage__ ) parser.add_argument('--hostname', default='127.0.0.1', help='Default: 127.0.0.1') parser.add_argument('--port'...
KeyboardInterrupt
dataset/ETHPy150Open abhinavsingh/proxy.py/proxy.py/main
5,275
def _validate_constant(constants, option_value, option_name): try: constant_value = constants.lookupByValue(option_value) except __HOLE__: raise UsageError( "The option '--{}' got unsupported value: '{}'. " "Must be one of: {}.".format( option_name, option...
ValueError
dataset/ETHPy150Open ClusterHQ/flocker/admin/installer/_images.py/_validate_constant
5,276
def get_jsons(grid_file): with open(grid_file) as f: f.readline() # Pop off the top f.readline() for line in f: try: yield json.loads(line[:-2]) except __HOLE__: yield json.loads(line) break
ValueError
dataset/ETHPy150Open CenterForOpenScience/scrapi/institutions/grid.py/get_jsons
5,277
def run(self): """ Run the Node Server. Exit when triggered. Generally, this method should not be overwritten. """ self.running = True self.poly.connect() counter = 0 try: while self.running: time.sleep(self.shortpoll) ...
KeyboardInterrupt
dataset/ETHPy150Open UniversalDevicesInc/Polyglot/polyglot/nodeserver_api.py/NodeServer.run
5,278
def _parse_cmd(self, cmd): """ Parses a received command. :param cmd: String command received from Polyglot """ if len(cmd) >= 2: # parse command try: cmd = json.loads(cmd) except __HOLE__: self.send_error('Rece...
ValueError
dataset/ETHPy150Open UniversalDevicesInc/Polyglot/polyglot/nodeserver_api.py/PolyglotConnector._parse_cmd
5,279
def __init__(self, definition) : if definition.get('has missing', False) : self.has_missing = True try : self.predicates += [predicates.ExistsPredicate(definition['field'])] except __HOLE__ : pass else : self.has_missing = ...
AttributeError
dataset/ETHPy150Open datamade/dedupe/dedupe/variables/base.py/Variable.__init__
5,280
def __init__(self, definition) : super(CustomType, self).__init__(definition) try : self.comparator = definition["comparator"] except __HOLE__ : raise KeyError("For 'Custom' field types you must define " "a 'comparator' function in the field " ...
KeyError
dataset/ETHPy150Open datamade/dedupe/dedupe/variables/base.py/CustomType.__init__
5,281
def get_callable(lookup_view, can_fail=False): """ Convert a string version of a function name to the callable object. If the lookup_view is not an import path, it is assumed to be a URL pattern label and the original string is returned. If can_fail is True, lookup_view might be a URL pattern labe...
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/get_callable
5,282
def get_mod_func(callback): # Converts 'django.views.news.stories.story_detail' to # ['django.views.news.stories', 'story_detail'] try: dot = callback.rindex('.') except __HOLE__: return callback, '' return callback[:dot], callback[dot+1:]
ValueError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/get_mod_func
5,283
def _get_callback(self): if self._callback is not None: return self._callback try: self._callback = get_callable(self._callback_str) except ImportError, e: mod_name, _ = get_mod_func(self._callback_str) raise ViewDoesNotExist, "Could not import %s....
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/RegexURLPattern._get_callback
5,284
def _get_urlconf_module(self): try: return self._urlconf_module except __HOLE__: self._urlconf_module = __import__(self.urlconf_name, {}, {}, ['']) return self._urlconf_module
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/RegexURLResolver._get_urlconf_module
5,285
def _resolve_special(self, view_type): callback = getattr(self.urlconf_module, 'handler%s' % view_type) mod_name, func_name = get_mod_func(callback) try: return getattr(__import__(mod_name, {}, {}, ['']), func_name), {} except (ImportError, __HOLE__), e: raise Vie...
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/RegexURLResolver._resolve_special
5,286
def reverse(self, lookup_view, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") try: lookup_view = get_callable(lookup_view, True) except (ImportError, __HOLE__), e: raise NoReverseMatch("Error import...
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/core/urlresolvers.py/RegexURLResolver.reverse
5,287
def __call__(self, env, start_response): """Accepts a standard WSGI application call, authenticating the request and installing callback hooks for authorization and ACL header validation. For an authenticated request, REMOTE_USER will be set to a comma separated list of the user's groups...
ValueError
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.__call__
5,288
def authorize(self, req): """Returns None if the request is authorized to continue or a standard WSGI response callable if not. """ try: version, account, container, obj = split_path(req.path, 1, 4, True) except __HOLE__: return HTTPNotFound(request=req) ...
ValueError
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.authorize
5,289
def handle_request(self, req): """Entry point for auth requests (ones that match the self.auth_prefix). Should return a WSGI-style callable (such as swob.Response). :param req: swob.Request object """ req.start_time = time() handler = None try: versio...
ValueError
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.handle_request
5,290
def handle_set_services(self, req): """Handles the POST v2/<account>/.services call for setting services information. Can only be called by a reseller .admin. In the :func:`handle_get_account` (GET v2/<account>) call, a section of the returned JSON dict is `services`. This section looks...
ValueError
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.handle_set_services
5,291
def handle_get_token(self, req): """Handles the various `request for token and service end point(s)` calls. There are various formats to support the various auth servers in the past. Examples:: GET <auth-prefix>/v1/<act>/auth X-Auth-User: <act>:<usr> or X-Storage-U...
ValueError
dataset/ETHPy150Open openstack/swauth/swauth/middleware.py/Swauth.handle_get_token
5,292
def establish_variables(self, x=None, y=None, hue=None, data=None, orient=None, order=None, hue_order=None, units=None): """Convert input specification into a common representation.""" # Option 1: # We are plotting a wide-form dataset ...
ValueError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_CategoricalPlotter.establish_variables
5,293
def _group_longform(self, vals, grouper, order): """Group a long-form variable by another with correct order.""" # Ensure that the groupby will work if not isinstance(vals, pd.Series): vals = pd.Series(vals) # Group the val data grouped_vals = vals.groupby(grouper) ...
KeyError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_CategoricalPlotter._group_longform
5,294
def infer_orient(self, x, y, orient=None): """Determine how the plot should be oriented based on the data.""" orient = str(orient) def is_categorical(s): try: # Correct way, but doesnt exist in older Pandas return pd.core.common.is_categorical_dtype(s...
AttributeError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_CategoricalPlotter.infer_orient
5,295
def annotate_axes(self, ax): """Add descriptive labels to an Axes object.""" if self.orient == "v": xlabel, ylabel = self.group_label, self.value_label else: xlabel, ylabel = self.value_label, self.group_label if xlabel is not None: ax.set_xlabel(xlab...
TypeError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_CategoricalPlotter.annotate_axes
5,296
def fit_kde(self, x, bw): """Estimate a KDE for a vector of data with flexible bandwidth.""" # Allow for the use of old scipy where `bw` is fixed try: kde = stats.gaussian_kde(x, bw) except __HOLE__: kde = stats.gaussian_kde(x) if bw != "scott": # sci...
TypeError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_ViolinPlotter.fit_kde
5,297
def _lv_box_ends(self, vals, k_depth='proportion', outlier_prop=None): """Get the number of data points and calculate `depth` of letter-value plot.""" vals = np.asarray(vals) vals = vals[np.isfinite(vals)] n = len(vals) # If p is not set, calculate it so that 8 points are...
ValueError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/_LVPlotter._lv_box_ends
5,298
def factorplot(x=None, y=None, hue=None, data=None, row=None, col=None, col_wrap=None, estimator=np.mean, ci=95, n_boot=1000, units=None, order=None, hue_order=None, row_order=None, col_order=None, kind="point", size=4, aspect=1, orient=None, color=None, palet...
KeyError
dataset/ETHPy150Open mwaskom/seaborn/seaborn/categorical.py/factorplot
5,299
def emit(self, record): """ Emit a record. Output the record to the file, catering for rollover as described in doRollover(). """ try: if self.shouldRollover(record): self.doRollover() logging.FileHandler.emit(self, record) ...
KeyboardInterrupt
dataset/ETHPy150Open babble/babble/include/jython/Lib/logging/handlers.py/BaseRotatingHandler.emit