Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
6,800
def assertIsDecorated(self, function, decorator_name): try: decorator_list = function.__decorators__ except __HOLE__: decorator_list = [] self.assertIn( decorator_name, decorator_list, msg="'{}' method should be decorated with 'module_...
AttributeError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/test/test_interpreter.py/RoutersploitInterpreterTest.assertIsDecorated
6,801
def __init__(self, shard_spec): """ :param string shard_spec: A string of the form M/N where M, N are ints and 0 <= M < N. """ def ensure_int(s): try: return int(s) except __HOLE__: raise self.InvalidShardSpec(shard_spec) if shard_spec is None: raise self.InvalidSh...
ValueError
dataset/ETHPy150Open pantsbuild/pants/src/python/pants/base/hash_utils.py/Sharder.__init__
6,802
def test_run_with_no_which(self): try: which_backup = shutil.which except __HOLE__: # pragma: no cover return del shutil.which try: self._test(*GetExcecutableTests.empty) self.assertFalse(hasattr(shutil, 'which')) self._test(*Ge...
AttributeError
dataset/ETHPy150Open epsy/clize/clize/tests/test_runner.py/GetExcecutableTests.test_run_with_no_which
6,803
def assert_systemexit(self, __code, __func, *args, **kwargs): try: __func(*args, **kwargs) except __HOLE__ as e: self.assertEqual(e.code, __code) else: self.fail('SystemExit not raised')
SystemExit
dataset/ETHPy150Open epsy/clize/clize/tests/test_runner.py/RunnerTests.assert_systemexit
6,804
def _script_to_name(script): try: return unicode_data.human_readable_script_name(script) except __HOLE__: return script
KeyError
dataset/ETHPy150Open googlei18n/nototools/nototools/mti_cmap_data.py/_script_to_name
6,805
def _parse_cgroup_file(self, stat_file): """Parses a cgroup pseudo file for key/values.""" self.log.debug("Opening cgroup file: %s" % stat_file) try: with open(stat_file, 'r') as fp: return dict(map(lambda x: x.split(), fp.read().splitlines())) except __HOLE__...
IOError
dataset/ETHPy150Open serverdensity/sd-agent/checks.d/docker.py/Docker._parse_cgroup_file
6,806
def _conditional_import_module(self, module_name): """Import a module and return a reference to it or None on failure.""" try: exec('import '+module_name) except __HOLE__, error: if self._warn_on_extension_import: warnings.warn('Did a C extension fail to c...
ImportError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_hashlib.py/HashLibTestCase._conditional_import_module
6,807
def test_unknown_hash(self): try: hashlib.new('spam spam spam spam spam') except __HOLE__: pass else: self.assertTrue(0 == "hashlib didn't reject bogus hash name")
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_hashlib.py/HashLibTestCase.test_unknown_hash
6,808
def test_get_builtin_constructor(self): get_builtin_constructor = hashlib.__dict__[ '__get_builtin_constructor'] self.assertRaises(ValueError, get_builtin_constructor, 'test') try: import _md5 except __HOLE__: pass # This forces an ImportEr...
ImportError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_hashlib.py/HashLibTestCase.test_get_builtin_constructor
6,809
def from_envvars(conf, prefix=None, envvars=None, as_json=True): """Load environment variables as Flask configuration settings. Values are parsed as JSON. If parsing fails with a ValueError, values are instead used as verbatim strings. :param app: App, whose configuration should be loaded from ENVVARs...
ValueError
dataset/ETHPy150Open mbr/flask-appconfig/flask_appconfig/env.py/from_envvars
6,810
def on_timer(self): """Callback function triggered by SidTimer every 'log_interval' seconds""" # current_index is the position in the buffer calculated from current UTC time current_index = self.timer.data_index utc_now = self.timer.utc_now # clear the View to prepare for new dat...
IndexError
dataset/ETHPy150Open ericgibert/supersid/supersid/supersid_scanner.py/SuperSID_scanner.on_timer
6,811
def run(self, wx_app = None): """Start the application as infinite loop accordingly to need""" self.__class__.running = True if self.config['viewer'] == 'wx': wx_app.MainLoop() elif self.config['viewer'] == 'text': try: while(self.__class__.running...
KeyboardInterrupt
dataset/ETHPy150Open ericgibert/supersid/supersid/supersid_scanner.py/SuperSID_scanner.run
6,812
def __call__(self, date, ctx): # get the node values from the context values = [ctx.get_value(node) for node in self.nodes] # get the writer from the context, or create it if it's not been # created already. ctx_id = ctx.get_id() try: writer = self.writers[c...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/builders/basic.py/CSVWriter.__call__
6,813
def get_dataframe(self, ctx, dtype=None, sparse_fill_value=None): ctx_id = ctx if isinstance(ctx, int) else ctx.get_id() # if the builder's been finalized and there's a dataframe cached # return that without trying to convert it to a sparse dataframe # or changing the dtypes (dt...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/builders/basic.py/DataFrameBuilder.get_dataframe
6,814
def get_columns(self, node, ctx): """ returns the sub-set of columns in the dataframe returned by get_dataframe that relate to a particular node """ ctx_id = ctx if isinstance(ctx, int) else ctx.get_id() try: return self._cached_columns[(ctx_id, node)] ...
KeyError
dataset/ETHPy150Open manahl/mdf/mdf/builders/basic.py/DataFrameBuilder.get_columns
6,815
def pytest_runtest_logreport(self, report): try: scenario = report.scenario except __HOLE__: # skip reporting for non-bdd tests return if not scenario["steps"] or report.when != "call": # skip if there isn't a result or scenario has no steps ...
AttributeError
dataset/ETHPy150Open pytest-dev/pytest-bdd/pytest_bdd/cucumber_json.py/LogBDDCucumberJSON.pytest_runtest_logreport
6,816
def _get_revision(self, revision): """ Get's an ID revision given as str. This will always return a fill 40 char revision number :param revision: str or int or None """ if self._empty: raise EmptyRepositoryError("There are no changesets yet") if rev...
ValueError
dataset/ETHPy150Open codeinn/vcs/vcs/backends/hg/repository.py/MercurialRepository._get_revision
6,817
def get_or_assign_number(self): """ Set a unique number to identify this Order object. The first 4 digits represent the current year. The last five digits represent a zero-padded incremental counter. """ if self.number is None: epoch = datetime.now().date() ...
ValueError
dataset/ETHPy150Open awesto/django-shop/shop/models/defaults/order.py/Order.get_or_assign_number
6,818
def GetOutboundGatewaySettings(self): """Get Outbound Gateway Settings Args: None Returns: A dict {smartHost, smtpMode}""" uri = self._serviceUrl('email/gateway') try: return self._GetProperties(uri) except gdata.service.RequestError as e: raise AppsForYourDomainExcept...
TypeError
dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/gdata/apps/adminsettings/service.py/AdminSettingsService.GetOutboundGatewaySettings
6,819
def callback(request): try: client = get_evernote_client() client.get_access_token( request.session['oauth_token'], request.session['oauth_token_secret'], request.GET.get('oauth_verifier', '') ) except __HOLE__: return redirect('/') note_s...
KeyError
dataset/ETHPy150Open evernote/evernote-sdk-python/sample/django/oauth/views.py/callback
6,820
def _dynamic_mul(self, dimensions, other, keys): """ Implements dynamic version of overlaying operation overlaying DynamicMaps and HoloMaps where the key dimensions of one is a strict superset of the other. """ # If either is a HoloMap compute Dimension values if ...
KeyError
dataset/ETHPy150Open ioam/holoviews/holoviews/core/spaces.py/HoloMap._dynamic_mul
6,821
def __getitem__(self, key): """ Return an element for any key chosen key (in'bounded mode') or for a previously generated key that is still in the cache (for one of the 'open' modes) """ tuple_key = util.wrap_tuple(key) # Validation for bounded mode if se...
KeyError
dataset/ETHPy150Open ioam/holoviews/holoviews/core/spaces.py/DynamicMap.__getitem__
6,822
def get_current_status(self): p = Popen("%s freeze | grep ^%s==" % (self.pip_binary_path, self.resource.package_name), stdout=PIPE, stderr=STDOUT, shell=True) out = p.communicate()[0] res = p.wait() if res != 0: self.current_version = None else: try: ...
IndexError
dataset/ETHPy150Open samuel/kokki/kokki/cookbooks/pip/libraries/providers.py/PipPackageProvider.get_current_status
6,823
def assert_graph_equal(self, g1, g2): try: return self.assertSetEqual(set(g1), set(g2)) except __HOLE__: # python2.6 does not have assertSetEqual assert set(g1) == set(g2)
AttributeError
dataset/ETHPy150Open RDFLib/rdflib/test/test_auditable.py/BaseTestAuditableStore.assert_graph_equal
6,824
def _render_sources(dataset, tables): """Render the source part of a query. Parameters ---------- dataset : str The data set to fetch log data from. tables : Union[dict, list] The tables to fetch log data from Returns ------- str A string that represents the "fr...
KeyError
dataset/ETHPy150Open tylertreat/BigQuery-Python/bigquery/query_builder.py/_render_sources
6,825
def parse_response(self, result, command_name, **options): try: return self.response_callbacks[command_name.upper()]( result, **options) except __HOLE__: return result
KeyError
dataset/ETHPy150Open coleifer/walrus/walrus/tusks/rlite.py/WalrusLite.parse_response
6,826
def cost(self): """Return the size (in bytes) that the bytecode for this takes up""" assert self.cost_map != None try: try: return self.__cost except __HOLE__: self.__cost = sum([self.cost_map[t] for t in self.value()]) re...
AttributeError
dataset/ETHPy150Open googlei18n/compreffor/compreffor/pyCompressor.py/CandidateSubr.cost
6,827
@staticmethod def process_subrs(glyph_set_keys, encodings, fdlen, fdselect, substrings, rev_keymap, subr_limit, nest_limit, verbose=False): post_time = time.time() def mark_reachable(cand_subr, fdidx): try: if fdidx not in cand_subr._fdidx: cand_subr....
AttributeError
dataset/ETHPy150Open googlei18n/compreffor/compreffor/pyCompressor.py/Compreffor.process_subrs
6,828
def _remove_array(self, key): """Private function that removes the cached array. Do not call this unless you know what you are doing.""" try: del self._cache[key] except __HOLE__: pass ###################################################################### # Set...
KeyError
dataset/ETHPy150Open enthought/mayavi/tvtk/array_handler.py/ArrayCache._remove_array
6,829
def get_vtk_array_type(numeric_array_type): """Returns a VTK typecode given a numpy array.""" # This is a Mapping from numpy array types to VTK array types. _arr_vtk = {numpy.dtype(numpy.character):vtkConstants.VTK_UNSIGNED_CHAR, numpy.dtype(numpy.uint8):vtkConstants.VTK_UNSIGNED_CHAR, ...
KeyError
dataset/ETHPy150Open enthought/mayavi/tvtk/array_handler.py/get_vtk_array_type
6,830
def array2vtkCellArray(num_array, vtk_array=None): """Given a nested Python list or a numpy array, this method creates a vtkCellArray instance and returns it. A variety of input arguments are supported as described in the Parameter documentation. If numpy arrays are given, this method is highly ef...
TypeError
dataset/ETHPy150Open enthought/mayavi/tvtk/array_handler.py/array2vtkCellArray
6,831
def convert_array(arr, vtk_typ=None): """Convert the given array to the optional type specified by `vtk_typ`. Parameters ---------- - arr : numpy array/list. - vtk_typ : `string` or `None` represents the type the array is to be converted to. """ if vtk_typ: conv = {'vtkC...
TypeError
dataset/ETHPy150Open enthought/mayavi/tvtk/array_handler.py/convert_array
6,832
@property def coordinates(self): try: from haystack.utils.geo import Point except __HOLE__: return None else: return Point(self.longitude, self.latitude, srid=4326)
ImportError
dataset/ETHPy150Open inonit/drf-haystack/tests/mockapp/models.py/MockLocation.coordinates
6,833
def deactivate(self): """Remove this response from the dependency graph and remove its pseudocomp from the scoping object. """ if self._pseudo is not None: scope = self.scope try: getattr(scope, self._pseudo.name) except __HOLE__: ...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/hasresponses.py/Response.deactivate
6,834
def evaluate(self, scope=None): """Use the value in the u vector if it exists instead of pulling the value from scope. """ if self.pcomp_name: scope = self._get_updated_scope(scope) try: system = getattr(scope, self.pcomp_name)._system ...
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/hasresponses.py/Response.evaluate
6,835
def add_response(self, expr, name=None, scope=None): """Adds a response to the driver. expr: string String containing the response expression. name: string (optional) Name to be used to refer to the response in place of the expression string. scope:...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/hasresponses.py/HasResponses.add_response
6,836
def _get_scope(self, scope=None): if scope is None: try: return self.parent.get_expr_scope() except __HOLE__: pass return scope
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/hasresponses.py/HasResponses._get_scope
6,837
def _as_dataset_variable(name, var): """Prepare a variable for adding it to a Dataset """ try: var = as_variable(var, key=name) except __HOLE__: raise TypeError('variables must be given by arrays or a tuple of ' 'the form (dims, data[, attrs, encoding])') if n...
TypeError
dataset/ETHPy150Open pydata/xarray/xarray/core/merge.py/_as_dataset_variable
6,838
def run(self, deployer, state_persister): """ Run the system ``mount`` tool to mount this change's volume's block device. The volume must be attached to this node. """ # Create the directory where a device will be mounted. # The directory's parent's permissions will be s...
OSError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/blockdevice.py/MountBlockDevice.run
6,839
def detach_volume(self, blockdevice_id): """ Clear the cached device path, if it was cached. """ try: del self._device_paths[blockdevice_id] except __HOLE__: pass return self._api.detach_volume(blockdevice_id)
KeyError
dataset/ETHPy150Open ClusterHQ/flocker/flocker/node/agents/blockdevice.py/ProcessLifetimeCache.detach_volume
6,840
def _canvas_route(self, *args, **kwargs): """ Decorator for canvas route """ def outer(view_fn): @self.route(*args, **kwargs) def inner(*args, **kwargs): fn_args = getargspec(view_fn) try: idx = fn_args.args.index(_ARG_KEY) except ValueErr...
ValueError
dataset/ETHPy150Open demianbrecht/flask-canvas/flask_canvas.py/_canvas_route
6,841
def date_trunc_sql(self, lookup_type, field_name): fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields....
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/mysql/base.py/DatabaseOperations.date_trunc_sql
6,842
def db_sync(engine, abs_path, version=None, init_version=0): """Upgrade or downgrade a database. Function runs the upgrade() or downgrade() functions in change scripts. :param engine: SQLAlchemy engine instance for a given database :param abs_path: Absolute path to migrate repository. :p...
ValueError
dataset/ETHPy150Open openstack/rack/rack/openstack/common/db/sqlalchemy/migration.py/db_sync
6,843
def startElementNS(self, tag, qname, attrs): if tag in self.triggers: self.parse = True if self.doc._parsing != "styles.xml" and tag == (OFFICENS, 'font-face-decls'): self.parse = False if self.parse == False: return self.level = self.level + 1 ...
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/packages/odf/load.py/LoadParser.startElementNS
6,844
def get_password_validators(validator_config): validators = [] for validator in validator_config: try: klass = import_string(validator['NAME']) except __HOLE__: msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting." ...
ImportError
dataset/ETHPy150Open orcasgit/django-password-validation/password_validation/validation.py/get_password_validators
6,845
def validate_password(password, user=None, password_validators=None): """ Validate whether the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with all error messages. """ errors = [] if password_validat...
ValidationError
dataset/ETHPy150Open orcasgit/django-password-validation/password_validation/validation.py/validate_password
6,846
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH): try: common_passwords_lines = gzip.open(password_list_path).read().decode('utf-8').splitlines() except __HOLE__: common_passwords_lines = open(password_list_path).readlines() self.passwords = {p.strip() fo...
IOError
dataset/ETHPy150Open orcasgit/django-password-validation/password_validation/validation.py/CommonPasswordValidator.__init__
6,847
def lookup(self, service, timeout=1): if self.client.state != KazooState.CONNECTED: return service service_name = service.name result = self.client.get_children_async( path='/%s/%s' % (SERVICE_NAMESPACE, service_name, ), watch=functools.partial(self.on_service...
KeyError
dataset/ETHPy150Open deliveryhero/lymph/lymph/discovery/zookeeper.py/ZookeeperServiceRegistry.lookup
6,848
def __init__(self, params, offset=0): agents.Agent.__init__(self, params, offset) try: self.maxprice = self.args[0] except (__HOLE__, IndexError): raise MissingParameter, 'maxprice' try: self.maxbuy = self.args[1] except IndexError: ...
AttributeError
dataset/ETHPy150Open jcbagneris/fms/fms/contrib/coleman/agents/probeadjustbstrader.py/ProbeAdjustBSTrader.__init__
6,849
def main (): options = docopt.docopt(usage, help=False) major = int(sys.version[0]) minor = int(sys.version[2]) if major != 2 or minor < 5: sys.exit('This program can not work (is not tested) with your python version (< 2.5 or >= 3.0)') if options["--version"]: print 'ExaBGP : %s' % version print 'Python ...
OSError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/application/bgp.py/main
6,850
def run (env, comment, configurations, pid=0): logger = Logger() if comment: logger.configuration(comment) if not env.profile.enable: ok = Reactor(configurations).run() __exit(env.debug.memory,0 if ok else 1) try: import cProfile as profile except __HOLE__: import profile if not env.profile.file or ...
ImportError
dataset/ETHPy150Open Exa-Networks/exabgp/lib/exabgp/application/bgp.py/run
6,851
def ndintegrate(data, unit_conv, limits, unit='ppm', noise_limits=None): """ Integrate one nD data array within limits given in units. Data points must be equally spaced. Can only integrate one region per function call. The integration error due to baseline noise is calculated as: .. math:: ...
TypeError
dataset/ETHPy150Open jjhelmus/nmrglue/nmrglue/analysis/integration.py/ndintegrate
6,852
def setSWJPins(self, output, pin, wait=0): cmd = [] cmd.append(COMMAND_ID['DAP_SWJ_PINS']) try: p = PINS[pin] except __HOLE__: logging.error('cannot find %s pin', pin) return cmd.append(output & 0xff) cmd.append(p) cmd.a...
KeyError
dataset/ETHPy150Open mbedmicro/pyOCD/pyOCD/pyDAPAccess/cmsis_dap_core.py/CMSIS_DAP_Protocol.setSWJPins
6,853
@method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): self.topic = self.get_topic(**kwargs) if request.GET.get('first-unread'): if request.user.is_authenticated(): read_dates = [] try: read_dates.append(TopicRea...
IndexError
dataset/ETHPy150Open hovel/pybbm/pybb/views.py/TopicView.dispatch
6,854
def form_valid(self, form): success = True save_attachments = False save_poll_answers = False self.object, topic = form.save(commit=False) if perms.may_attach_files(self.request.user): aformset = self.get_attachment_formset_class()( self.request.POST,...
ValidationError
dataset/ETHPy150Open hovel/pybbm/pybb/views.py/PostEditMixin.form_valid
6,855
@method_decorator(csrf_protect) def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated(): self.user = request.user else: if defaults.PYBB_ENABLE_ANONYMOUS_POST: self.user, new = User.objects.get_or_create(**{username_field: defaults.PYB...
TypeError
dataset/ETHPy150Open hovel/pybbm/pybb/views.py/AddPostView.dispatch
6,856
def get(self, name): if not may(READ): raise Forbidden() try: item = current_app.storage.openwrite(name) except (OSError, IOError) as e: if e.errno == errno.ENOENT: raise NotFound() raise with item as item: comp...
UnicodeDecodeError
dataset/ETHPy150Open bepasty/bepasty-server/bepasty/views/display.py/DisplayView.get
6,857
def data_available(dataset_name=None): """Check if the data set is available on the local machine already.""" try: from itertools import izip_longest except __HOLE__: from itertools import zip_longest as izip_longest dr = data_resources[dataset_name] zip_urls = (dr['files'], ) if...
ImportError
dataset/ETHPy150Open SheffieldML/GPy/GPy/util/datasets.py/data_available
6,858
def hapmap3(data_set='hapmap3'): """ The HapMap phase three SNP dataset - 1184 samples out of 11 populations. SNP_matrix (A) encoding [see Paschou et all. 2007 (PCA-Correlated SNPs...)]: Let (B1,B2) be the alphabetically sorted bases, which occur in the j-th SNP, then / 1, iff SNPij==(B1,B1...
ImportError
dataset/ETHPy150Open SheffieldML/GPy/GPy/util/datasets.py/hapmap3
6,859
def get_template(self, uri): """Return a :class:`.Template` object corresponding to the given ``uri``. .. note:: The ``relativeto`` argument is not supported here at the moment. """ try: if self.filesystem_checks: return self._check(uri, self._colle...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lookup.py/TemplateLookup.get_template
6,860
def filename_to_uri(self, filename): """Convert the given ``filename`` to a URI relative to this :class:`.TemplateCollection`.""" try: return self._uri_cache[filename] except __HOLE__: value = self._relativeize(filename) self._uri_cache[filename] =...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lookup.py/TemplateLookup.filename_to_uri
6,861
def _load(self, filename, uri): self._mutex.acquire() try: try: # try returning from collection one # more time in case concurrent thread already loaded return self._collection[uri] except __HOLE__: pass ...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lookup.py/TemplateLookup._load
6,862
def _check(self, uri, template): if template.filename is None: return template try: template_stat = os.stat(template.filename) if template.module._modified_time < \ template_stat[stat.ST_MTIME]: self._collection.pop(uri, None) ...
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Mako-0.8.1/mako/lookup.py/TemplateLookup._check
6,863
def __repr__(self): try: return "<%s - %s>" % (self._object_type.encode('utf-8'), self.title.encode('utf-8')) except __HOLE__: # the title is None return "< Track >"
AttributeError
dataset/ETHPy150Open echonest/pyechonest/pyechonest/track.py/Track.__repr__
6,864
def dns_sweep(self,file_with_ips,file_prefix): logging.info("Finding misconfigured DNS servers that might allow zone transfers among live ips ..") self.shell.shell_exec("nmap -PN -n -sS -p 53 -iL "+file_with_ips+" -oA "+file_prefix) # Step 2 - Extract IPs dns_servers=file_prefix+".dns_server.ip...
IOError
dataset/ETHPy150Open owtf/owtf/framework/plugin/scanner.py/Scanner.dns_sweep
6,865
def mkdir(self): "write a directory for the node" if getattr(self, 'cache_isdir', None): return self.parent.mkdir() if self.name: try: os.mkdir(self.abspath()) except __HOLE__: e = extract_exception() i...
OSError
dataset/ETHPy150Open cournape/Bento/bento/core/node.py/Node.mkdir
6,866
def find_node(self, lst): "read the file system, make the nodes as needed" if is_string(lst): lst = [x for x in split_path(lst) if x and x != '.'] cur = self for x in lst: if x == '..': cur = cur.parent continue try: ...
AttributeError
dataset/ETHPy150Open cournape/Bento/bento/core/node.py/Node.find_node
6,867
def find_dir(self, lst): """ search a folder in the filesystem create the corresponding mappings source <-> build directories """ if isinstance(lst, str): lst = [x for x in split_path(lst) if x and x != '.'] node = self.find_node(lst) try: ...
OSError
dataset/ETHPy150Open cournape/Bento/bento/core/node.py/Node.find_dir
6,868
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='HitCounts Rock!', DEBU...
AttributeError
dataset/ETHPy150Open thornomad/django-hitcount/tests/conftest.py/pytest_configure
6,869
def run_setup_marathon_job(context): update_context_marathon_config(context) with contextlib.nested( mock.patch.object(SystemPaastaConfig, 'get_zk_hosts', autospec=True, return_value=context.zk_hosts), mock.patch('paasta_tools.setup_marathon_job.parse_args', autospec=True), mock.patch.ob...
SystemExit
dataset/ETHPy150Open Yelp/paasta/paasta_itests/steps/setup_marathon_job_steps.py/run_setup_marathon_job
6,870
def get(self): ''' worker ''' nsdata = {'nsname': self.get_argument('name'), 'profile_number': int(self.get_argument('nsid')), 'ns_platform': self.get_argument('type')} try: PGLOT.nodeservers.start_server(**nsdata) self.send_json() ...
ValueError
dataset/ETHPy150Open UniversalDevicesInc/Polyglot/polyglot/element_manager/api.py/ServersAddHandler.get
6,871
def digattr(obj, attr, default=None): '''Perform template-style dotted lookup''' steps = attr.split('.') for step in steps: try: # dict lookup obj = obj[step] except (TypeError, AttributeError, KeyError): try: # attribute lookup obj = getattr(obj...
IndexError
dataset/ETHPy150Open funkybob/django-nap/nap/utils/__init__.py/digattr
6,872
def _sorted_from_obj(self, data): # data is a list of the type generated by parse_qsl if isinstance(data, list): items = data else: # complex objects: try: # django.http.QueryDict, items = [(i[0], j) for i in data.lists() for j ...
AttributeError
dataset/ETHPy150Open circuits/circuits/circuits/web/parsers/querystring.py/QueryStringParser._sorted_from_obj
6,873
def process(self, pair): key = pair[0] value = pair[1] # faster than invoking a regex try: key.index("[") self.parse(key, value) return except __HOLE__: pass try: key.index(".") self.parse(key, valu...
ValueError
dataset/ETHPy150Open circuits/circuits/circuits/web/parsers/querystring.py/QueryStringParser.process
6,874
def parse(self, key, value): ref = self.result tokens = self.tokens(key) for token in tokens: token_type, key = token if token_type == QueryStringToken.ARRAY: if key not in ref: ref[key] = [] ref = ref[key] ...
KeyError
dataset/ETHPy150Open circuits/circuits/circuits/web/parsers/querystring.py/QueryStringParser.parse
6,875
def tokens(self, key): buf = "" for char in key: if char == "[": yield QueryStringToken.ARRAY, buf buf = "" elif char == ".": yield QueryStringToken.OBJECT, buf buf = "" elif char == "]": ...
ValueError
dataset/ETHPy150Open circuits/circuits/circuits/web/parsers/querystring.py/QueryStringParser.tokens
6,876
@register.simple_tag def user_avatar(user, secure=False, size=256, rating='pg', default=''): try: profile = user.get_profile() if profile.avatar: return profile.avatar.url except SiteProfileNotAvailable: pass except __HOLE__: pass except AttributeError: ...
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/django-badger/badger/templatetags/badger_tags.py/user_avatar
6,877
def scale_image(img_upload, img_max_size): """Crop and scale an image file.""" try: img = Image.open(img_upload) except __HOLE__: return None src_width, src_height = img.size src_ratio = float(src_width) / float(src_height) dst_width, dst_height = img_max_size dst_ratio = fl...
IOError
dataset/ETHPy150Open lmorchard/badg.us/badgus/profiles/models.py/scale_image
6,878
def is_vouched_mozillian(self): """Check whether this profile is associated with a vouched mozillians.org profile""" MOZILLIANS_API_BASE_URL = constance.config.MOZILLIANS_API_BASE_URL MOZILLIANS_API_APPNAME = constance.config.MOZILLIANS_API_APPNAME MOZILLIANS_API_KEY = constance...
ValueError
dataset/ETHPy150Open lmorchard/badg.us/badgus/profiles/models.py/UserProfile.is_vouched_mozillian
6,879
def estimate_u_multiple_tries(sumLogPi=None, nDoc=0, gamma=1.0, alpha0=1.0, initu=None, initU=None, approx_grad=False, fList=[1e7, 1e8, 1e10], **kwargs): ''' Estimate 2K-vector "u" via gradient descent, gracefully using multiple restarts with progres...
ValueError
dataset/ETHPy150Open daeilkim/refinery/refinery/bnpy/bnpy-dev/bnpy/allocmodel/admix/OptimizerForHDPFullVarModel.py/estimate_u_multiple_tries
6,880
def estimate_u(sumLogPi=None, nDoc=0, gamma=1.0, alpha0=1.0, initu=None, approx_grad=False, factr=1.0e7, **kwargs): ''' Run gradient optimization to estimate best v for specified problem Returns -------- vhat : K-vector of values, 0 < v < 1 fofvhat: objective function value at vhat Inf...
AssertionError
dataset/ETHPy150Open daeilkim/refinery/refinery/bnpy/bnpy-dev/bnpy/allocmodel/admix/OptimizerForHDPFullVarModel.py/estimate_u
6,881
def get_default_if(): """ Returns the default interface """ f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): interf = words[0] break except __HOLE__: pass ...
ValueError
dataset/ETHPy150Open rlisagor/pynetlinux/pynetlinux/route.py/get_default_if
6,882
def get_default_gw(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
ValueError
dataset/ETHPy150Open rlisagor/pynetlinux/pynetlinux/route.py/get_default_gw
6,883
def Observer(request): try: observer_name = Config().observer_name except __HOLE__: observer_name = '' diag = Diag.objects.filter(name=observer_name).first() if not diag: return HttpResponse(json.dumps({"health": ":-X", "time": time.time(), "comp": 0})) t = time.time() ...
AttributeError
dataset/ETHPy150Open open-cloud/xos/xos/core/views/observer.py/Observer
6,884
def __init__(self, content, attrs=None, filter_type=None, filename=None, **kwargs): # It looks like there is a bug in django-compressor because it expects # us to accept attrs. super(DjangoScssFilter, self).__init__(content, filter_type, filename, **kwargs) try: # this is a l...
KeyError
dataset/ETHPy150Open fusionbox/django-pyscss/django_pyscss/compressor.py/DjangoScssFilter.__init__
6,885
def _is_valid_email(self, email): """ Given an email address, make sure that it is well-formed. :param str email: The email address to validate. :rtype: bool :returns: True if the email address is valid, False if not. """ try: validate_email(email) ...
ValidationError
dataset/ETHPy150Open duointeractive/sea-cucumber/seacucumber/management/commands/ses_address.py/Command._is_valid_email
6,886
def add_color_info(info): color_map = { 'red': (0xcc, 0x33, 0x33), 'green': (0x33, 0x99, 0x33), 'blue': (0x33, 0x66, 0x99), 'yellow': (0xcc, 0xcc, 0x33), } color_name = info.get('default_image_color', 'blue') try: info['_color'] = color_map[color_name] except ...
KeyError
dataset/ETHPy150Open conda/constructor/constructor/imaging.py/add_color_info
6,887
def IsSubclass(candidate, parent_class): """Calls issubclass without raising an exception. Args: candidate: A candidate to check if a subclass. parent_class: A class or tuple of classes representing a potential parent. Returns: A boolean indicating whether or not candidate is a subclass of parent_cl...
TypeError
dataset/ETHPy150Open GoogleCloudPlatform/endpoints-proto-datastore/endpoints_proto_datastore/utils.py/IsSubclass
6,888
def DatetimeValueFromString(value): """Converts a serialized datetime string to the native type. Args: value: The string value to be deserialized. Returns: A datetime.datetime/date/time object that was deserialized from the string. Raises: TypeError: if the value can not be deserialized to one of...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/endpoints-proto-datastore/endpoints_proto_datastore/utils.py/DatetimeValueFromString
6,889
def old_changelist_view(self, request, extra_context=None): "The 'change list' admin view for this model." from django.contrib.admin.views.main import ERROR_FLAG from django.core.exceptions import PermissionDenied from django.utils.encoding import force_text from django.utils.tra...
ValueError
dataset/ETHPy150Open callowayproject/django-categories/categories/editor/tree_editor.py/TreeEditor.old_changelist_view
6,890
def arch(): """ Return the system's architecture according to dpkg or rpm. """ try: p = subprocess.Popen(['dpkg', '--print-architecture'], close_fds=True, stdout=subprocess.PIPE) except __HOLE__ as e: p = subprocess.Popen(['rpm', '--eval', '%_arch'], ...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/util.py/arch
6,891
def lsb_release_codename(): """ Return the OS release's codename. """ if hasattr(lsb_release_codename, '_cache'): return lsb_release_codename._cache try: p = subprocess.Popen(['lsb_release', '-c'], stdout=subprocess.PIPE) except __HOLE__: lsb_release_codename._cache = Non...
OSError
dataset/ETHPy150Open devstructure/blueprint/blueprint/util.py/lsb_release_codename
6,892
def parse_service(pathname): """ Parse a potential service init script or config file into the manager and service name or raise `ValueError`. Use the Upstart "start on" stanzas and SysV init's LSB headers to restrict services to only those that start at boot and run all the time. """ dirna...
IOError
dataset/ETHPy150Open devstructure/blueprint/blueprint/util.py/parse_service
6,893
def unicodeme(s): if isinstance(s, unicode): return s for encoding in ('utf_8', 'latin_1'): try: return unicode(s, encoding) except __HOLE__: pass # TODO Issue a warning? return s
UnicodeDecodeError
dataset/ETHPy150Open devstructure/blueprint/blueprint/util.py/unicodeme
6,894
def add_request_data(self, issue, request_data): """Add parsed request data to the node :param issue: Issue as XML document :param request_data: HTTP request data """ request = HTTPRequestParser(request_data) request.parse_data() reque...
IndexError
dataset/ETHPy150Open dorneanu/appvulnms/src/core/parser/AppVulnXMLParser.py/AppVulnXMLParser.add_request_data
6,895
def add_response_data(self, issue, response_data, binary_data=False): """Add parsed response data to the node :param issue: Issue as XML document :param response_data: HTTP response data :param binary_data: Flag indicating whether responde_data is binary """ ...
IndexError
dataset/ETHPy150Open dorneanu/appvulnms/src/core/parser/AppVulnXMLParser.py/AppVulnXMLParser.add_response_data
6,896
@classmethod def ensure_value_type(cls, value_type, parameter=None): """Raises a :exc:`TypeError` if the given ``value_type`` is not an instance of nor a subclass of the class. .. sourcecode:: pycon >>> Integer.ensure_value_type(Bulk ... ) # doctest: +NORMALIZE_WHITE...
TypeError
dataset/ETHPy150Open dahlia/sider/sider/types.py/Value.ensure_value_type
6,897
def delete_file(self, name): try: self.fs.delete_file(name+"_test.pst") except __HOLE__: pass
OSError
dataset/ETHPy150Open dokipen/whoosh/tests/test_postings.py/TestReadWrite.delete_file
6,898
def _load_yaml_mapping(filename): try: f = open(filename) try: yaml_versions = yaml_load(f) finally: f.close() except __HOLE__: yaml_versions = { } return yaml_versions #################################################################################...
IOError
dataset/ETHPy150Open turbulenz/turbulenz_local/turbulenz_local/helpers.py/_load_yaml_mapping
6,899
def validate(self, value): try: return int(value) except (ValueError, __HOLE__): raise ValidationError(_('Not an integer'))
TypeError
dataset/ETHPy150Open fiam/wapi/validators.py/IntegerValidator.validate