Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,200 | def identify(self):
"""Update client metadata on the server and negotiate features.
:returns: nsqd response data if there was feature negotiation,
otherwise `None`
"""
self.send(nsq.identify({
# nsqd <0.2.28
'short_id': self.client_id,
'lo... | ValueError | dataset/ETHPy150Open wtolson/gnsq/gnsq/nsqd.py/Nsqd.identify |
2,201 | def auth(self):
"""Send authorization secret to nsqd."""
self.send(nsq.auth(self.auth_secret))
frame, data = self.read_response()
if frame == nsq.FRAME_TYPE_ERROR:
raise data
try:
response = json.loads(data.decode('utf-8'))
except __HOLE__:
... | ValueError | dataset/ETHPy150Open wtolson/gnsq/gnsq/nsqd.py/Nsqd.auth |
2,202 | def runfastcgi(argset=[], **kwargs):
options = FASTCGI_OPTIONS.copy()
options.update(kwargs)
for x in argset:
if "=" in x:
k, v = x.split('=', 1)
else:
k, v = x, True
options[k.lower()] = v
if "help" in options:
return fastcgi_help()
try:
... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-0.96/django/core/servers/fastcgi.py/runfastcgi |
2,203 | def _handle_password(self, password):
""" Handles getting the password"""
if password is None:
password = keyring.get_password('yagmail', self.user)
if password is None:
password = keyring.get_password('yagmail', self.user)
if password is None:
... | NameError | dataset/ETHPy150Open kootenpv/yagmail/yagmail/yagmail.py/SMTP._handle_password |
2,204 | def process_view(self, request, view_func, view_args, view_kwargs):
try:
path = view_kwargs['path']
except __HOLE__:
request.node = None
else:
request.node = SimpleLazyObject(lambda: get_node(path)) | KeyError | dataset/ETHPy150Open ithinksw/philo/philo/middleware.py/RequestNodeMiddleware.process_view |
2,205 | def hashed_name(self, name, content=None):
parsed_name = urlsplit(unquote(name))
clean_name = parsed_name.path.strip()
opened = False
if content is None:
if not self.exists(clean_name):
raise ValueError("The file '%s' could not be found with %r." %
... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/staticfiles/storage.py/CachedFilesMixin.hashed_name |
2,206 | def _get_request_object(request, attrs=None, klass=None, key=None):
"""Resolves the appropriate object for use from the request.
This applies only to DataView or DataContext objects.
"""
# Attempt to derive the `attrs` from the request
if attrs is None:
if request.method == 'POST':
... | ValueError | dataset/ETHPy150Open chop-dbhi/serrano/serrano/resources/base.py/_get_request_object |
2,207 | def get_request_query(request, attrs=None):
"""
Resolves the appropriate DataQuery object for use from the request.
"""
# Attempt to derive the `attrs` from the request
if attrs is None:
if request.method == 'POST':
attrs = request.data.get('query')
elif request.method ==... | ValueError | dataset/ETHPy150Open chop-dbhi/serrano/serrano/resources/base.py/get_request_query |
2,208 | def create_app(applet_id, applet_name, src_dir, publish=False, set_default=False, billTo=None, try_versions=None, try_update=True, confirm=True):
"""
Creates a new app object from the specified applet.
"""
app_spec = _get_app_spec(src_dir)
logger.info("Will create app with spec: %s" % (app_spec,))
... | KeyboardInterrupt | dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/app_builder.py/create_app |
2,209 | def consume_incoming(self, *args, **kwargs):
consumed = 0
for m in self.spider_log_consumer.get_messages(timeout=1.0, count=self.consumer_batch_size):
try:
msg = self._decoder.decode(m)
except (KeyError, TypeError), e:
logger.error("Decoding error:... | KeyError | dataset/ETHPy150Open scrapinghub/frontera/frontera/worker/db.py/DBWorker.consume_incoming |
2,210 | def consume_scoring(self, *args, **kwargs):
consumed = 0
seen = set()
batch = []
for m in self.scoring_log_consumer.get_messages(count=self.consumer_batch_size):
try:
msg = self._decoder.decode(m)
except (__HOLE__, TypeError), e:
lo... | KeyError | dataset/ETHPy150Open scrapinghub/frontera/frontera/worker/db.py/DBWorker.consume_scoring |
2,211 | def has_module(module_name):
try:
import imp
imp.find_module(module_name)
del imp
return True
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open tony/tmuxp/bootstrap_env.py/has_module |
2,212 | def pca(x, subtract_mean=False, normalize=False, sort_components=True, reducedim=None, algorithm=pca_eig):
""" Calculate principal component analysis (PCA)
Parameters
----------
x : array-like, shape = [n_trials, n_channels, n_samples] or [n_channels, n_samples]
EEG data set
subtract_me... | IndexError | dataset/ETHPy150Open scot-dev/scot/scot/pca.py/pca |
2,213 | def draw_networkx_nodes(G, pos,
nodelist=None,
node_size=300,
node_color='r',
node_shape='o',
alpha=1.0,
cmap=None,
vmin=None,
v... | ImportError | dataset/ETHPy150Open calliope-project/calliope/calliope/lib/nx_pylab.py/draw_networkx_nodes |
2,214 | def draw_networkx_edges(G, pos, node_patches=None,
edgelist=None,
width=None,
edge_color=None,
style='solid',
alpha=None,
edge_cmap=None,
edge_vmin=None... | RuntimeError | dataset/ETHPy150Open calliope-project/calliope/calliope/lib/nx_pylab.py/draw_networkx_edges |
2,215 | def main():
init_app(set_backends=True, routes=False)
# drop all styles
CitationStyle.remove()
total = 0
for style_file in get_style_files(settings.CITATION_STYLES_PATH):
with open(style_file, 'r') as f:
try:
root = etree.parse(f).getroot()
except e... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/scripts/parse_citation_styles.py/main |
2,216 | def validate(self, attrs):
'''
1. Disallow starts-with, which complicates validation, and
is unnecessary for file uploading
2. Require that required_conditions are present
3. Make sure conditions are in required_conditions or
optional_conditions
4. Invoke su... | ValidationError | dataset/ETHPy150Open bodylabs/drf-to-s3/drf_to_s3/serializers.py/DefaultPolicySerializer.validate |
2,217 | def testError(self):
failed = False
try:
bam_innerdist(testbam3, testbam4)
except __HOLE__:
failed = True
self.assertTrue(failed) | ValueError | dataset/ETHPy150Open ngsutils/ngsutils/ngsutils/bam/t/test_innerdist.py/InnerDistTest.testError |
2,218 | def add_db(source_socket, destination_socket, source_db, destination_db):
src = redis_conn(source_socket, source_db)
dest = redis_conn(destination_socket, destination_db)
keys = src.keys()
for key in keys:
key_type = src.type(key)
if key_type == "string":
value = src.get(key)... | ValueError | dataset/ETHPy150Open practo/r5d4/scripts/add_keys.py/add_db |
2,219 | def check():
try:
check_call(['initctl', '--version'], stdout=PIPE)
return True
except __HOLE__ as err:
if err.errno == 2:
return False
raise | OSError | dataset/ETHPy150Open Anaconda-Platform/chalmers/chalmers/service/upstart_service.py/check |
2,220 | def _run_command(function, args, kwargs, exit_msg):
success = False
try:
log.debug("Running %s command...", getattr(function, '__name__', 'a'))
success = function(*args, **kwargs)
except __HOLE__:
log.debug("Command canceled")
exit_msg = ""
except RuntimeError as exc:
... | KeyboardInterrupt | dataset/ETHPy150Open jacebrowning/gitman/gitman/cli.py/_run_command |
2,221 | def machine_setup(target, use_chroot):
"""Prepare the machine and get SSH parameters from ``vagrant ssh``.
"""
try:
out = subprocess.check_output(['vagrant', 'ssh-config'],
cwd=target.path,
stderr=subprocess.PIPE)
except... | OSError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip-vagrant/reprounzip/unpackers/vagrant/__init__.py/machine_setup |
2,222 | def vagrant_setup_create(args):
"""Sets up the experiment to be run in a Vagrant-built virtual machine.
This can either build a chroot or not.
If building a chroot, we do just like without Vagrant: we copy all the
files and only get what's missing from the host. But we do install
automatically the... | KeyError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip-vagrant/reprounzip/unpackers/vagrant/__init__.py/vagrant_setup_create |
2,223 | def upload_file(self, local_path, input_path):
if self.use_chroot:
remote_path = join_root(PosixPath('/experimentroot'),
input_path)
else:
remote_path = input_path
temp = make_unique_name(b'reprozip_input_')
ltemp = self.target... | OSError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip-vagrant/reprounzip/unpackers/vagrant/__init__.py/SSHUploader.upload_file |
2,224 | def download(self, remote_path, local_path):
if self.use_chroot:
remote_path = join_root(PosixPath('/experimentroot'), remote_path)
temp = make_unique_name(b'reprozip_output_')
rtemp = PosixPath('/vagrant') / temp
ltemp = self.target / temp
# Copy file to shared fol... | OSError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip-vagrant/reprounzip/unpackers/vagrant/__init__.py/SSHDownloader.download |
2,225 | def check_vagrant_version():
try:
out = subprocess.check_output(['vagrant', '--version'])
except (subprocess.CalledProcessError, __HOLE__):
logging.error("Couldn't run vagrant")
sys.exit(1)
out = out.decode('ascii').strip().lower().split()
if out[0] == 'vagrant':
if Loose... | OSError | dataset/ETHPy150Open ViDA-NYU/reprozip/reprounzip-vagrant/reprounzip/unpackers/vagrant/__init__.py/check_vagrant_version |
2,226 | @classmethod
def _size_selector(cls, possible_sizes):
"""Select the maximum size, utility function for adding borders.
The number two is used so that the edges of a column have spaces
around them (instead of being right next to a column separator).
:param possible_sizes: possible s... | ValueError | dataset/ETHPy150Open openstack/taskflow/taskflow/types/table.py/PleasantTable._size_selector |
2,227 | def __exit__(self, exc_type, exc_val, exc_tb):
"""
If an exception occurred, we leave the file for inspection.
"""
sys.path.remove(self.tempdir)
if exc_type is None:
# No exception occurred
os.remove(self.tempdir + 'test_imports_future_stdlib.py')
... | OSError | dataset/ETHPy150Open PythonCharmers/python-future/tests/test_future/test_requests.py/write_module.__exit__ |
2,228 | def test_remove_hooks_then_requests(self):
code = """
from future import standard_library
standard_library.install_hooks()
import builtins
import http.client
import html.parser
"""
with write_module(code, self.tempdir):
... | ImportError | dataset/ETHPy150Open PythonCharmers/python-future/tests/test_future/test_requests.py/TestRequests.test_remove_hooks_then_requests |
2,229 | def test_requests_cm(self):
"""
Tests whether requests can be used importing standard_library modules
previously with the hooks context manager
"""
code = """
from future import standard_library
with standard_library.hooks():
import builtin... | ImportError | dataset/ETHPy150Open PythonCharmers/python-future/tests/test_future/test_requests.py/TestRequests.test_requests_cm |
2,230 | def get_os_by_image_meta(self, os_release):
LOG.debug('--- Getting operating system data by image metadata ---')
if os_release:
LOG.debug('Looks like {0} is going to be provisioned'.
format(os_release))
try:
OS = getattr(objects, os_release['... | AttributeError | dataset/ETHPy150Open openstack/bareon/bareon/drivers/data/nailgun.py/Nailgun.get_os_by_image_meta |
2,231 | def bind_links(self, links, sources=None, position=None):
"""
Associate a link to a model, a view inside this menu
"""
try:
for source in sources:
self._map_links_to_source(
links=links, position=position, source=source
)
... | TypeError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/navigation/classes.py/Menu.bind_links |
2,232 | def resolve(self, context, source=None):
try:
request = Variable('request').resolve(context)
except VariableDoesNotExist:
# There is no request variable, most probable a 500 in a test view
# Don't return any resolved links then.
logger.warning('No request ... | TypeError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/navigation/classes.py/Menu.resolve |
2,233 | def unbind_links(self, links, sources=None):
"""
Allow unbinding links from sources, used to allow 3rd party apps to
change the link binding of core apps
"""
try:
for source in sources:
self._map_links_to_source(
links=links, sourc... | TypeError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/navigation/classes.py/Menu.unbind_links |
2,234 | def resolve(self, context, resolved_object=None):
request = Variable('request').resolve(context)
current_path = request.META['PATH_INFO']
current_view = resolve(current_path).view_name
# ACL is tested agains the resolved_object or just {{ object }} if not
if not resolved_object:... | KeyError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/navigation/classes.py/Link.resolve |
2,235 | @classmethod
def get_for_source(cls, source):
try:
return cls._registry[source]
except KeyError:
try:
return cls._registry[source.model]
except AttributeError:
try:
return cls._registry[source.__class__]
... | KeyError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/navigation/classes.py/SourceColumn.get_for_source |
2,236 | def check_is_int(s):
try:
int(s)
except __HOLE__:
return False
return True | ValueError | dataset/ETHPy150Open cloudify-cosmo/cloudify-manager/rest-service/manager_rest/deployment_update/utils.py/check_is_int |
2,237 | def _ifconfig_getnode():
"""Get the hardware address on Unix by running ifconfig."""
import os
for dir in ['', '/sbin/', '/usr/sbin']:
try:
pipe = os.popen(os.path.join(dir, 'ifconfig'))
except __HOLE__:
continue
for line in pipe:
words = line.lowe... | IOError | dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/third_party/uuid/uuid.py/_ifconfig_getnode |
2,238 | def _ipconfig_getnode():
"""Get the hardware address on Windows by running ipconfig.exe."""
import os, re
dirs = ['', r'c:\windows\system32', r'c:\winnt\system32']
try:
import ctypes
buffer = ctypes.create_string_buffer(300)
ctypes.windll.kernel32.GetSystemDirectoryA(buffer, 300)... | IOError | dataset/ETHPy150Open scalyr/scalyr-agent-2/scalyr_agent/third_party/uuid/uuid.py/_ipconfig_getnode |
2,239 | def pivot_table(data, values=None, index=None, columns=None, aggfunc='mean',
fill_value=None, margins=False, dropna=True,
margins_name='All'):
"""
Create a spreadsheet-style pivot table as a DataFrame. The levels in the
pivot table will be stored in MultiIndex objects (hierar... | AttributeError | dataset/ETHPy150Open pydata/pandas/pandas/tools/pivot.py/pivot_table |
2,240 | def _add_margins(table, data, values, rows, cols, aggfunc,
margins_name='All'):
if not isinstance(margins_name, compat.string_types):
raise ValueError('margins_name argument must be a string')
exception_msg = 'Conflicting name "{0}" in margins'.format(margins_name)
for level in tab... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/tools/pivot.py/_add_margins |
2,241 | def _compute_grand_margin(data, values, aggfunc,
margins_name='All'):
if values:
grand_margin = {}
for k, v in data[values].iteritems():
try:
if isinstance(aggfunc, compat.string_types):
grand_margin[k] = getattr(v, aggfunc)(... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/tools/pivot.py/_compute_grand_margin |
2,242 | def _generate_marginal_results(table, data, values, rows, cols, aggfunc,
grand_margin,
margins_name='All'):
if len(cols) > 0:
# need to "interleave" the margins
table_pieces = []
margin_keys = []
def _all_key(key):
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/tools/pivot.py/_generate_marginal_results |
2,243 | def _normalize(table, normalize, margins):
if not isinstance(normalize, bool) and not isinstance(normalize,
compat.string_types):
axis_subs = {0: 'index', 1: 'columns'}
try:
normalize = axis_subs[normalize]
except __HOLE_... | KeyError | dataset/ETHPy150Open pydata/pandas/pandas/tools/pivot.py/_normalize |
2,244 | @classmethod
def _validate_timeout(cls, value, name):
""" Check that a timeout attribute is valid.
:param value: The timeout value to validate
:param name: The name of the timeout attribute to validate. This is
used to specify in error messages.
:return: The validated an... | ValueError | dataset/ETHPy150Open BergWerkGIS/QGIS-CKAN-Browser/CKAN-Browser/request/packages/urllib3/util/timeout.py/Timeout._validate_timeout |
2,245 | def get_trigger_db_given_type_and_params(type=None, parameters=None):
try:
parameters = parameters or {}
trigger_dbs = Trigger.query(type=type,
parameters=parameters)
trigger_db = trigger_dbs[0] if len(trigger_dbs) > 0 else None
if not parameters... | ValueError | dataset/ETHPy150Open StackStorm/st2/st2common/st2common/services/triggers.py/get_trigger_db_given_type_and_params |
2,246 | def get_trigger_type_db(ref):
"""
Returns the trigger type object from db given a string ref.
:param ref: Reference to the trigger type db object.
:type ref: ``str``
:rtype trigger_type: ``object``
"""
try:
return TriggerType.get_by_ref(ref)
except __HOLE__ as e:
LOG.de... | ValueError | dataset/ETHPy150Open StackStorm/st2/st2common/st2common/services/triggers.py/get_trigger_type_db |
2,247 | def dispatch_events(self, dt=None):
if not self._open:
return
event = IOHIDEventStruct()
r = self._queue.contents.contents.getNextEvent(self._queue,
ctypes.byref(event), 0, 0)
if r != 0:
# Undocumented behaviour? returns 3758097127L when no event... | KeyError | dataset/ETHPy150Open ardekantur/pyglet/experimental/input/osx.py/Device.dispatch_events |
2,248 | def _pop_new_chunk(self):
if self.chunks_exhausted:
return b""
try:
chunk = self.content[self.index]
except __HOLE__:
chunk = b''
self.chunks_exhausted = True
else:
self.index += 1
chunk = self._encode_chunk(chunk)
... | IndexError | dataset/ETHPy150Open shazow/urllib3/test/test_response.py/MockChunkedEncodingResponse._pop_new_chunk |
2,249 | def pop_current_chunk(self, amt=-1, till_crlf=False):
if amt > 0 and till_crlf:
raise ValueError("Can't specify amt and till_crlf.")
if len(self.cur_chunk) <= 0:
self.cur_chunk = self._pop_new_chunk()
if till_crlf:
try:
i = self.cur_chunk.index... | IndexError | dataset/ETHPy150Open shazow/urllib3/test/test_response.py/MockChunkedEncodingResponse.pop_current_chunk |
2,250 | def __getattr__(self, name):
if hasattr(self.underlying, name):
return getattr(self.underlying, name)
try:
return self.defaults[name]
except __HOLE__, error:
raise AttributeError("'%s' object has no attribute '%s'" % (self.underlying.__class__.__name__, name))... | KeyError | dataset/ETHPy150Open yaniv-aknin/django-ajaxerrors/ajaxerrors/utils.py/DefaultedAttributes.__getattr__ |
2,251 | def get_callable(callable):
if isinstance(callable, basestring):
module, attr = callable.rsplit('.', 1)
try:
mod = import_module(module)
except __HOLE__, e:
raise ImproperlyConfigured('Error importing ajaxerrors callable %s: "%s"' % (callable, e))
try:
... | ImportError | dataset/ETHPy150Open yaniv-aknin/django-ajaxerrors/ajaxerrors/utils.py/get_callable |
2,252 | def _isvalidnode(pynode): #(7)
try:
bool(pynode)
return True
except __HOLE__:
return False | KeyError | dataset/ETHPy150Open rgalanakis/practicalmayapython/src/chapter7/callbacks.py/_isvalidnode |
2,253 | def make_url(report_class, domain, string_params, args):
try:
return html.escape(
report_class.get_url(
domain=domain
) + string_params % args
)
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/custom/ilsgateway/tanzania/reports/utils.py/make_url |
2,254 | def check_xform_es_index(interval=10):
try:
doc_id, doc_rev = get_last_change_for_doc_class(XFormInstance)
except __HOLE__:
return None
time.sleep(interval)
return _check_es_rev(XFORM_INDEX, doc_id, [doc_rev]) | StopIteration | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqadmin/escheck.py/check_xform_es_index |
2,255 | def check_case_es_index(interval=10):
try:
doc_id, doc_rev = get_last_change_for_doc_class(CommCareCase)
except __HOLE__:
return None
time.sleep(interval)
return _check_es_rev(CASE_INDEX, doc_id, [doc_rev]) | StopIteration | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/hqadmin/escheck.py/check_case_es_index |
2,256 | def func(self, lib, opts, args):
"""Command handler for the metasync function.
"""
pretend = opts.pretend
query = ui.decargs(args)
sources = []
for source in opts.sources:
sources.extend(source.split(','))
sources = sources or self.config['source'].a... | KeyError | dataset/ETHPy150Open beetbox/beets/beetsplug/metasync/__init__.py/MetaSyncPlugin.func |
2,257 | def __delitem__(self, key):
try:
del self.d[key]
except (__HOLE__, TypeError):
pass | KeyError | dataset/ETHPy150Open petrvanblokland/Xierpa3/xierpa3/toolbox/formdict.py/FormDict.__delitem__ |
2,258 | def __getitem__(self, key):
try:
v = self.d[key]
# v is always a sequence
if v and len(v) == 1:
return v[0]
return v
except (__HOLE__, TypeError):
# @@@ for this behavior, we should use d.get() instead.
return None | KeyError | dataset/ETHPy150Open petrvanblokland/Xierpa3/xierpa3/toolbox/formdict.py/FormDict.__getitem__ |
2,259 | def LogError(self, message, trace=None):
try:
self.db_error.Add(message, trace) # Log error in the DB.
except __HOLE__:
cprint("ERROR: DB is not setup yet: cannot log errors to file!") | AttributeError | dataset/ETHPy150Open owtf/owtf/framework/error_handler.py/ErrorHandler.LogError |
2,260 | def _python_eggs(self, priors):
egg_infos = []
groups = [self.instances]
if priors:
for _group, prior_instances in self.prior_groups:
groups.append(list(prior_instances.values()))
for instances in groups:
for i in instances:
try:
... | AttributeError | dataset/ETHPy150Open openstack/anvil/anvil/packaging/base.py/DependencyHandler._python_eggs |
2,261 | def _scan_pip_requires(self, requires_files):
own_eggs = self._python_eggs(False)
def replace_forced_requirements(fn, forced_by_key):
old_lines = sh.load_file(fn).splitlines()
new_lines = []
alterations = []
for line in old_lines:
try:
... | KeyError | dataset/ETHPy150Open openstack/anvil/anvil/packaging/base.py/DependencyHandler._scan_pip_requires |
2,262 | @staticmethod
def _requirements_satisfied(pips_list, download_dir):
downloaded_req = [pip_helper.get_archive_details(filename)["req"]
for filename in sh.listdir(download_dir, files_only=True)]
downloaded_req = dict((req.key, req.specs[0][1]) for req in downloaded_req)
... | KeyError | dataset/ETHPy150Open openstack/anvil/anvil/packaging/base.py/DependencyHandler._requirements_satisfied |
2,263 | def _colorize(self, pyval, state):
pyval_type = type(pyval)
state.score += 1
if pyval is None or pyval is True or pyval is False:
self._output(unicode(pyval), self.CONST_TAG, state)
elif pyval_type in (int, float, long, types.ComplexType):
self._output(un... | KeyboardInterrupt | dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/markup/pyval_repr.py/PyvalColorizer._colorize |
2,264 | def _sort(self, items):
if not self.sort: return items
try: return sorted(items)
except __HOLE__: raise
except: return items | KeyboardInterrupt | dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/markup/pyval_repr.py/PyvalColorizer._sort |
2,265 | def items_for_result(cl, result, form):
"""
Generates the actual list of data.
"""
def link_in_col(is_first, field_name, cl):
if cl.list_display_links is None:
return False
if is_first and not cl.list_display_links:
return True
return field_name in cl.lis... | ObjectDoesNotExist | dataset/ETHPy150Open django/django/django/contrib/admin/templatetags/admin_list.py/items_for_result |
2,266 | @register.tag
def gizmo(parser, token):
"""
Similar to the include tag, gizmo loads special templates called gizmos that come with the django-tethys_gizmo
app. Gizmos provide tools for developing user interface elements with minimal code. Examples include date pickers,
maps, and interactive plots.
... | ValueError | dataset/ETHPy150Open tethysplatform/tethys/tethys_gizmos/templatetags/tethys_gizmos.py/gizmo |
2,267 | def render(self, context):
# Get the gizmos rendered from the context
gizmos_rendered = context['gizmos_rendered']
# Compile list of unique gizmo dependencies
dependencies = []
# Add gizmo dependencies
for rendered_gizmo in gizmos_rendered:
try:
... | AttributeError | dataset/ETHPy150Open tethysplatform/tethys/tethys_gizmos/templatetags/tethys_gizmos.py/TethysGizmoDependenciesNode.render |
2,268 | def test_pyunitAddError(self):
# pyunit passes an exc_info tuple directly to addError
try:
raise RuntimeError('foo')
except __HOLE__ as e:
excValue = e
self.result.addError(self, sys.exc_info())
failure = self.result.errors[0][1]
self.assertEqu... | RuntimeError | dataset/ETHPy150Open twisted/twisted/twisted/trial/test/test_reporter.py/TestResultTests.test_pyunitAddError |
2,269 | def setUp(self):
try:
raise RuntimeError('foo')
except __HOLE__:
self.f = Failure()
self.f.frames = [
['foo', 'foo/bar.py', 5, [('x', 5)], [('y', 'orange')]],
['qux', 'foo/bar.py', 10, [('a', 'two')], [('b', 'MCMXCIX')]]
]
self.... | RuntimeError | dataset/ETHPy150Open twisted/twisted/twisted/trial/test/test_reporter.py/FormatFailuresTests.setUp |
2,270 | def test_summaryColoredFailure(self):
"""
The summary in case of failure should have a good count of errors
and be colored properly.
"""
try:
raise RuntimeError('foo')
except __HOLE__:
self.result.addError(self, sys.exc_info())
self.result.... | RuntimeError | dataset/ETHPy150Open twisted/twisted/twisted/trial/test/test_reporter.py/TreeReporterTests.test_summaryColoredFailure |
2,271 | def test_groupResults(self):
"""
If two different tests have the same error, L{Reporter._groupResults}
includes them together in one of the tuples in the list it returns.
"""
try:
raise RuntimeError('foo')
except RuntimeError:
self.result.addError(... | RuntimeError | dataset/ETHPy150Open twisted/twisted/twisted/trial/test/test_reporter.py/TreeReporterTests.test_groupResults |
2,272 | def removeMethod(self, klass, methodName):
"""
Remove 'methodName' from 'klass'.
If 'klass' does not have a method named 'methodName', then
'removeMethod' succeeds silently.
If 'klass' does have a method named 'methodName', then it is removed
using delattr. Also, method... | AttributeError | dataset/ETHPy150Open twisted/twisted/twisted/trial/test/test_reporter.py/SubunitReporterTests.removeMethod |
2,273 | def find_unique_points(explored_parameters):
"""Takes a list of explored parameters and finds unique parameter combinations.
If parameter ranges are hashable operates in O(N), otherwise O(N**2).
:param explored_parameters:
List of **explored** parameters
:return:
List of tuples, fir... | TypeError | dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/utils/explore.py/find_unique_points |
2,274 | def execute(self, argv):
'''Executes user provided command. Eg. bii run:cpp'''
errors = False
try:
if isinstance(argv, basestring): # To make tests easier to write
argv = shlex.split(argv)
self.executor.execute(argv) # Executor only raises not expected E... | KeyboardInterrupt | dataset/ETHPy150Open biicode/client/shell/bii.py/Bii.execute |
2,275 | def run_main(args, user_io=None, current_folder=None, user_folder=None, biiapi_client=None):
try:
user_folder = user_folder or os.path.expanduser("~")
biicode_folder = os.path.join(user_folder, '.biicode')
current_folder = current_folder or os.getcwd()
user_io = user_io or create_use... | OSError | dataset/ETHPy150Open biicode/client/shell/bii.py/run_main |
2,276 | def format_output_data(self, data):
for k, v in six.iteritems(data):
if isinstance(v, six.text_type):
try:
# Deserialize if possible into dict, lists, tuples...
v = ast.literal_eval(v)
except SyntaxError:
# N... | ValueError | dataset/ETHPy150Open openstack/python-blazarclient/climateclient/command.py/ClimateCommand.format_output_data |
2,277 | def year(request, year, queryset=None,
template_name="jellyroll/calendar/year.html", template_loader=loader,
extra_context=None, context_processors=None, mimetype=None):
"""
Jellyroll'd items for a particular year.
Works a bit like a generic view in that you can pass a bunch of optional
keyword... | IndexError | dataset/ETHPy150Open jacobian-archive/jellyroll/src/jellyroll/views/calendar.py/year |
2,278 | def month(request, year, month, queryset=None,
template_name="jellyroll/calendar/month.html", template_loader=loader,
extra_context=None, context_processors=None, mimetype=None):
"""
Jellyroll'd items for a particular month.
Works a bit like a generic view in that you can pass a bunch of optional
... | IndexError | dataset/ETHPy150Open jacobian-archive/jellyroll/src/jellyroll/views/calendar.py/month |
2,279 | def day(request, year, month, day, queryset=None, recent_first=False,
template_name="jellyroll/calendar/day.html", template_loader=loader,
extra_context=None, context_processors=None, mimetype=None):
"""
Jellyroll'd items for a particular day.
Works a bit like a generic view in that you can pass a ... | IndexError | dataset/ETHPy150Open jacobian-archive/jellyroll/src/jellyroll/views/calendar.py/day |
2,280 | def __init__(self, parentnode, name,
atom=None, shape=None,
title="", filters=None,
chunkshape=None, byteorder=None,
_log=True):
self.atom = atom
"""An `Atom` instance representing the shape, type of the atomic
objects to be sa... | TypeError | dataset/ETHPy150Open PyTables/PyTables/tables/carray.py/CArray.__init__ |
2,281 | 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 AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/util.py/unquote |
2,282 | def find_resource(manager, name_or_id, **find_args):
"""Look for resource in a given manager.
Used as a helper for the _find_* methods.
Example:
.. code-block:: python
def _find_hypervisor(cs, hypervisor):
#Get a hypervisor by name or ID.
return cliutils.find_resource(... | ValueError | dataset/ETHPy150Open openstack/python-cloudkittyclient/cloudkittyclient/openstack/common/apiclient/utils.py/find_resource |
2,283 | def _load_from_file(self, path):
states = []
try:
if os.path.exists(path):
with open(path, 'rb') as fd:
states = pickle.load(fd)
except (PickleError, PicklingError), err:
raise SynapseException(err)
except (__HOLE__, EOFError):
... | IOError | dataset/ETHPy150Open comodit/synapse-agent/synapse/states_manager.py/StatesManager._load_from_file |
2,284 | def persist(self):
try:
with open(self.path, 'wb') as fd:
os.chmod(self.path, stat.S_IREAD | stat.S_IWRITE)
pickle.dump(self.states, fd)
except __HOLE__ as err:
self.logger.error(err) | IOError | dataset/ETHPy150Open comodit/synapse-agent/synapse/states_manager.py/StatesManager.persist |
2,285 | def _get_index(self, res_id):
try:
return map(itemgetter('resource_id'), self.states).index(res_id)
except __HOLE__:
return -1 | ValueError | dataset/ETHPy150Open comodit/synapse-agent/synapse/states_manager.py/StatesManager._get_index |
2,286 | def _register_pygments_rst_directive():
from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name, TextLexer
from pygments.formatters import HtmlFormatter
DEFAULT = HtmlFormatter()
... | ValueError | dataset/ETHPy150Open jamesturk/django-markupfield/markupfield/markup.py/_register_pygments_rst_directive |
2,287 | def exit(self):
"""
Sometimes client is disconnected and command exits after. So cmdstack is gone
"""
try:
self.protocol.cmdstack.pop()
self.protocol.cmdstack[-1].resume()
except __HOLE__:
# cmdstack could be gone already (wget + disconnect)
... | AttributeError | dataset/ETHPy150Open cowrie/cowrie/cowrie/core/honeypot.py/HoneyPotCommand.exit |
2,288 | def __getdistro_setenv(servername):
"""
"""
server = [s for s in env.bootmachine_servers
if s.name == servername][0]
env.servername = server.name
env.host = server.public_ip
env.host_string = "{0}:{1}".format(server.public_ip, server.port)
env.hosts = [server.public_ip]
env... | ImportError | dataset/ETHPy150Open rizumu/bootmachine/bootmachine/contrib/configurators/salt.py/__getdistro_setenv |
2,289 | def _from_json(self, datastring):
try:
return utils.loads(datastring)
except __HOLE__:
msg = _("cannot understand JSON")
raise exception.MalformedRequestBody(reason=msg) | ValueError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/JSONDeserializer._from_json |
2,290 | def get_body_deserializer(self, content_type):
try:
return self.body_deserializers[content_type]
except (__HOLE__, TypeError):
raise exception.InvalidContentType(content_type=content_type) | KeyError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/RequestDeserializer.get_body_deserializer |
2,291 | def get_action_args(self, request_environment):
"""Parse dictionary created by routes library."""
try:
args = request_environment['wsgiorg.routing_args'][1].copy()
except Exception:
return {}
try:
del args['controller']
except __HOLE__:
... | KeyError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/RequestDeserializer.get_action_args |
2,292 | def get_body_serializer(self, content_type):
try:
return self.body_serializers[content_type]
except (KeyError, __HOLE__):
raise exception.InvalidContentType(content_type=content_type) | TypeError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/ResponseSerializer.get_body_serializer |
2,293 | @webob.dec.wsgify(RequestClass=Request)
def __call__(self, request):
"""WSGI method that controls (de)serialization and method dispatch."""
LOG.info("%(method)s %(url)s" % {"method": request.method,
"url": request.url})
try:
action, arg... | AttributeError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/Resource.__call__ |
2,294 | def dispatch(self, request, action, action_args):
"""Find action-spefic method on controller and call it."""
controller_method = getattr(self.controller, action)
try:
return controller_method(req=request, **action_args)
except __HOLE__ as exc:
LOG.exception(exc)
... | TypeError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/api/openstack/wsgi.py/Resource.dispatch |
2,295 | def get_nova_client(auth_token=None, bypass_url=None, previous_tries=0):
if previous_tries > 3:
return None
# first try to use auth details from auth_ref so we
# don't need to auth with keystone every time
auth_ref = get_auth_ref()
auth_details = get_auth_details()
... | AttributeError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/get_nova_client |
2,296 | def keystone_auth(auth_details):
try:
if auth_details['OS_AUTH_URL'].endswith('v3'):
k_client = k3_client
else:
k_client = k2_client
tenant_name = auth_details['OS_TENANT_NAME']
keystone = k_client.Client(username=auth_details['OS_U... | IOError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/keystone_auth |
2,297 | def is_token_expired(token, auth_details):
for fmt in ('%Y-%m-%dT%H:%M:%SZ', '%Y-%m-%dT%H:%M:%S.%fZ'):
try:
if auth_details['OS_AUTH_URL'].endswith('v3'):
expires_at = token.get('expires_at')
else:
expires_at = token['token'].get('expires')
... | ValueError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/is_token_expired |
2,298 | def get_auth_from_file():
try:
with open(TOKEN_FILE) as token_file:
auth_ref = json.load(token_file)
return auth_ref
except __HOLE__ as e:
if e.errno == errno.ENOENT:
return None
status_err(e) | IOError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/get_auth_from_file |
2,299 | def get_auth_details(openrc_file=OPENRC):
auth_details = AUTH_DETAILS
pattern = re.compile(
'^(?:export\s)?(?P<key>\w+)(?:\s+)?=(?:\s+)?(?P<value>.*)$'
)
try:
with open(openrc_file) as openrc:
for line in openrc:
match = pattern.match(line)
if... | IOError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/maas_common.py/get_auth_details |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.