Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,500 | def _extract_biblio(self, page, id=None):
dict_of_keylists = {
'title' : ['title'],
'genre' : ['defined_type'],
#'authors_literal' : ['authors'],
'published_date' : ['published_date']
}
item = self._extract_figshare_record(page, id)
biblio_... | TypeError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/figshare.py/Figshare._extract_biblio |
5,501 | def member_items(self,
account_name,
provider_url_template=None,
cache_enabled=True):
if not self.provides_members:
raise NotImplementedError()
self.logger.debug(u"%s getting member_items for %s" % (self.provider_name, account_name))
if not pr... | TypeError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/figshare.py/Figshare.member_items |
5,502 | def __getstate__(self):
d = dict(vars(self))
for k in '_credCache', '_cacheTimestamp':
try:
del d[k]
except __HOLE__:
pass
return d | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/cred/checkers.py/FilePasswordDB.__getstate__ |
5,503 | def requestAvatarId(self, c):
try:
u, p = self.getUser(c.username)
except __HOLE__:
return defer.fail(error.UnauthorizedLogin())
else:
up = credentials.IUsernamePassword(c, None)
if self.hash:
if up is not None:
... | KeyError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/cred/checkers.py/FilePasswordDB.requestAvatarId |
5,504 | def requestAvatarId(self, credentials):
try:
from twisted.cred import pamauth
except __HOLE__: # PyPAM is missing
return defer.fail(error.UnauthorizedLogin())
else:
d = pamauth.pamAuthenticate(self.service, credentials.username,
... | ImportError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/cred/checkers.py/PluggableAuthenticationModulesChecker.requestAvatarId |
5,505 | def run_subprocess(cmd, data=None):
"""
Execute the command C{cmd} in a subprocess.
@param cmd: The command to execute, specified as a list
of string.
@param data: A string containing data to send to the
subprocess.
@return: A tuple C{(out, err)}.
@raise OSError: If there is... | ImportError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/epydoc/util.py/run_subprocess |
5,506 | def survey_template_represent(template_id, row=None):
"""
Display the template name rather than the id
"""
if row:
return row.name
elif not template_id:
return current.messages["NONE"]
table = current.s3db.survey_template
query = (table.id == template_id)
record = c... | AttributeError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/survey_template_represent |
5,507 | @staticmethod
def question_list_onaccept(form):
"""
If a grid question is added to the the list then all of the
grid children will need to be added as well
"""
qstntable = current.s3db.survey_question
try:
form_vars = form.vars
questio... | AttributeError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/S3SurveyQuestionModel.question_list_onaccept |
5,508 | def getLocationList(series_id):
"""
Get a list of the LatLons for each Response in a Series
"""
response_locations = []
rappend = response_locations.append
code_list = ["STD-L4", "STD-L3", "STD-L2", "STD-L1", "STD-L0"]
table = current.s3db.survey_complete
rows = current.db(table.se... | ValueError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/getLocationList |
5,509 | @staticmethod
def translate_onaccept(form):
"""
If the translation spreadsheet has been uploaded then
it needs to be processed.
The translation strings need to be extracted from
the spreadsheet and inserted into the language file.
"""
if "fil... | IOError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/S3SurveyTranslateModel.translate_onaccept |
5,510 | def apply_method(self, r, **attr):
"""
Entry point for REST API
@param r: the S3Request
@param attr: controller arguments
"""
if r.representation != "xls":
r.error(415, current.ERROR.BAD_FORMAT)
template_id = r.id
template = r.re... | IOError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/survey_TranslateDownload.apply_method |
5,511 | def apply_method(self, r, **attr):
"""
Entry point for REST API
@param r: the S3Request
@param attr: controller arguments
"""
if r.representation != "xls":
r.error(415, current.error.BAD_FORMAT)
series_id = self.record_id
if seri... | ImportError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/survey_ExportResponses.apply_method |
5,512 | def formattedAnswer(self, data):
"""
This will take a string and do it's best to return a Date object
It will try the following in order
* Convert using the ISO format:
* look for a month in words a 4 digit year and a day (1 or 2 digits)
* a year and m... | ValueError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/S3QuestionTypeDateWidget.formattedAnswer |
5,513 | def castRawAnswer(self, complete_id, answer):
""" @todo: docstring """
try:
return float(answer)
except __HOLE__:
return None
# ------------------------------------------------------------------------- | ValueError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/S3NumericAnalysis.castRawAnswer |
5,514 | def json2py(jsonstr):
"""
Utility function to convert a string in json to a python structure
"""
from xml.sax.saxutils import unescape
if not isinstance(jsonstr, str):
return jsonstr
try:
jsonstr = unescape(jsonstr, {"u'": '"'})
jsonstr = unescape(jsonstr, {"'": '"'... | ValueError | dataset/ETHPy150Open sahana/eden/modules/s3db/survey.py/json2py |
5,515 | def eatDirective(self):
directive = self.matchDirective()
try:
self.calls[directive] += 1
except __HOLE__:
self.calls[directive] = 1
super(Analyzer, self).eatDirective() | KeyError | dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/DirectiveAnalyzer.py/Analyzer.eatDirective |
5,516 | def main_dir(opts):
results = _analyze_templates(_find_templates(opts.dir, opts.suffix))
totals = {}
for series in results:
if not series:
continue
for k, v in series.iteritems():
try:
totals[k] += v
except __HOLE__:
totals[... | KeyError | dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/DirectiveAnalyzer.py/main_dir |
5,517 | def tearDown(self):
try:
self.cnx.close()
self.removefile()
except __HOLE__:
pass
except sqlite.InterfaceError:
pass | AttributeError | dataset/ETHPy150Open sassoftware/conary/conary/pysqlite3/test/transaction_tests.py/TransactionTests.tearDown |
5,518 | def tearDown(self):
try:
self.cnx.close()
self.removefile()
except __HOLE__:
pass
except sqlite.InterfaceError:
pass | AttributeError | dataset/ETHPy150Open sassoftware/conary/conary/pysqlite3/test/transaction_tests.py/AutocommitTests.tearDown |
5,519 | def run():
a = docopt.docopt(__doc__)
vi_mode = bool(a['--vi'])
config_dir = os.path.expanduser(a['--config-dir'] or '~/.ptpython/')
# Create config directory.
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
# If IPython is not available, show message and exit here with error s... | ImportError | dataset/ETHPy150Open jonathanslenders/ptpython/ptpython/entry_points/run_ptipython.py/run |
5,520 | def run(self, point):
"""Execute all registered Hooks (callbacks) for the given point."""
exc = None
hooks = self[point]
hooks.sort()
for hook in hooks:
# Some hooks are guaranteed to run even if others at
# the same hookpoint fail. We will still log the f... | KeyboardInterrupt | dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/_cprequest.py/HookMap.run |
5,521 | def process_query_string(self):
"""Parse the query string into Python structures. (Core)"""
try:
p = httputil.parse_query_string(
self.query_string, encoding=self.query_string_encoding)
except __HOLE__:
raise cherrypy.HTTPError(
404, "The g... | UnicodeDecodeError | dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/_cprequest.py/Request.process_query_string |
5,522 | def finalize(self):
"""Transform headers (and cookies) into self.header_list. (Core)"""
try:
code, reason, _ = httputil.valid_status(self.status)
except __HOLE__:
raise cherrypy.HTTPError(500, sys.exc_info()[1].args[0])
headers = self.headers
self.status... | ValueError | dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/_cprequest.py/Response.finalize |
5,523 | def main():
ip = ipapi.get()
try:
ip.ex("import math,cmath")
ip.ex("import numpy")
ip.ex("import numpy as np")
ip.ex("from numpy import *")
except __HOLE__:
print("Unable to start NumPy profile, is numpy installed?") | ImportError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/deathrow/ipy_profile_numpy.py/main |
5,524 | def islink(path):
"""Test whether a path is a symbolic link"""
try:
st = os.lstat(path)
except (os.error, __HOLE__):
return False
return stat.S_ISLNK(st.st_mode)
# Does a path exist?
# This is false for dangling symbolic links. | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/posixpath.py/islink |
5,525 | def parse_relative_time(dtstr):
# example 600 seconds is: '000000001000000R'
try:
year = int(dtstr[:2])
month = int(dtstr[2:4])
day = int(dtstr[4:6])
hour = int(dtstr[6:8])
minute = int(dtstr[8:10])
second = int(dtstr[10:12])
dsecond = int(dtstr[12:13])
... | IndexError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/smpp/pdu/smpp_time.py/parse_relative_time |
5,526 | def location(self):
"(float, float) Return Where.Point.pos.text as a (lat,lon) tuple"
try:
return tuple([float(z) for z in self.Point.pos.text.split(' ')])
except __HOLE__:
return tuple() | AttributeError | dataset/ETHPy150Open bradfitz/addressbooker/gdata/geo/__init__.py/Where.location |
5,527 | def set_location(self, latlon):
"""(bool) Set Where.Point.pos.text from a (lat,lon) tuple.
Arguments:
lat (float): The latitude in degrees, from -90.0 to 90.0
lon (float): The longitude in degrees, from -180.0 to 180.0
Returns True on success.
"""
assert(isinstance(latlon[0], flo... | AttributeError | dataset/ETHPy150Open bradfitz/addressbooker/gdata/geo/__init__.py/Where.set_location |
5,528 | def add_image(self, image):
"""
Add a PersistentImage-type object to this PersistenImageManager
This should only be called with an image that has not yet been added to the store.
To retrieve a previously persisted image use image_with_id() or image_query()
@param image TODO
... | IOError | dataset/ETHPy150Open redhat-imaging/imagefactory/imgfac/MongoPersistentImageManager.py/MongoPersistentImageManager.add_image |
5,529 | def import_dotted_path(path):
"""
Takes a dotted path to a member name in a module, and returns
the member after importing it.
"""
try:
module_path, member_name = path.rsplit(".", 1)
module = import_module(module_path)
return getattr(module, member_name)
except (ValueErro... | AttributeError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/utils/importing.py/import_dotted_path |
5,530 | def _update_reader_output(self):
r = self.reader
r.update()
if r.error_code != 0:
try:
self.reader.i_blanking = True
except __HOLE__:
pass
else:
r.update()
# Try reading file.
if r.error_code !=... | AttributeError | dataset/ETHPy150Open enthought/mayavi/mayavi/sources/plot3d_reader.py/PLOT3DReader._update_reader_output |
5,531 | def mapper_final(self):
# hook for test_local.LocalRunnerSetupTestCase.test_python_archive()
try:
import foo
foo # quiet pyflakes warning
except __HOLE__:
pass
for dirpath, _, filenames in os.walk('.'):
for filename in filenames:
... | ImportError | dataset/ETHPy150Open Yelp/mrjob/tests/mr_os_walk_job.py/MROSWalkJob.mapper_final |
5,532 | def pibrella_exit():
try:
pibrella.exit()
except AttributeError:
print("Pibrella not initialized!")
except __HOLE__:
print("Pibrella not initialized!") | NameError | dataset/ETHPy150Open pimoroni/pibrella/pibrella.py/pibrella_exit |
5,533 | def dequeue(self):
if self.blocking:
try:
return self.conn.brpop(
self.queue_key,
timeout=self.read_timeout)[1]
except (ConnectionError, __HOLE__, IndexError):
# Unfortunately, there is no way to differentiate a sock... | TypeError | dataset/ETHPy150Open coleifer/huey/huey/storage.py/RedisStorage.dequeue |
5,534 | def get(self, queue_name, task_id):
"""
Pops a specific task off the queue by identifier.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:param task_id: The identifier of the task.
:type task_id:... | ValueError | dataset/ETHPy150Open toastdriven/alligator/alligator/backends/locmem_backend.py/Client.get |
5,535 | def _generate_filename_to_mtime(self):
"""Records the state of a directory.
Returns:
A dictionary of subdirectories and files under
directory associated with their timestamps.
the keys are absolute paths and values are epoch timestamps.
Raises:
ShutdownError: if the quit event has ... | IOError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/mtime_file_watcher.py/MtimeFileWatcher._generate_filename_to_mtime |
5,536 | def render(self, context):
try:
user = context['user']
count = user.received_messages.filter(read_at__isnull=True, recipient_deleted_at__isnull=True).count()
except (__HOLE__, AttributeError):
count = ''
if self.varname is not None:
context[self.va... | KeyError | dataset/ETHPy150Open amarandon/smeuhsocial/apps/messages/templatetags/inbox.py/InboxOutput.render |
5,537 | def parse(self, p):
p.startLengthCheck(3)
if self.certificateType == CertificateType.x509:
chainLength = p.get(3)
index = 0
certificate_list = []
while index != chainLength:
certBytes = p.getVarBytes(3)
x509 = X509()
... | ImportError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/gdata/tlslite/messages.py/Certificate.parse |
5,538 | def changes(request, slug, template_name='wakawaka/changes.html', extra_context=None):
"""
Displays the changes between two revisions.
"""
if extra_context is None:
extra_context = {}
rev_a_id = request.GET.get('a', None)
rev_b_id = request.GET.get('b', None)
# Some stinky fin... | ObjectDoesNotExist | dataset/ETHPy150Open bartTC/django-wakawaka/wakawaka/views.py/changes |
5,539 | def test_override(self):
modname = os.path.__name__
tests = [
("import os.path" , "('os.path', None, -1, 'os')"),
("import os.path as path2", "('os.path', None, -1, 'os')"),
("from os.path import *" ,
"('os.path', ('*',), -1, '%s')" % modname),
... | ImportError | dataset/ETHPy150Open ofermend/medicare-demo/socialite/jython/Lib/test/test_import_jy.py/OverrideBuiltinsImportTestCase.test_override |
5,540 | def test_invalid_argument_type(self):
values = (0, 0, 0, 'string not int')
try:
self.bound.bind(values)
except TypeError as e:
self.assertIn('v0', str(e))
self.assertIn('Int32Type', str(e))
self.assertIn('str', str(e))
else:
sel... | TypeError | dataset/ETHPy150Open datastax/python-driver/tests/unit/test_parameter_binding.py/BoundStatementTestV1.test_invalid_argument_type |
5,541 | @register.tag(name='get_latest_annotations')
def do_get_latest_annotations(parser, token):
""" Use like so: {% get_latest_annotations as annotations [count=1]%}
"""
as_var = None
count = 1
try:
contents = token.split_contents()
if len(contents) >= 2 and contents[1] == "as":
... | IndexError | dataset/ETHPy150Open stefanw/django-annotatetext/annotatetext/templatetags/annotatetags.py/do_get_latest_annotations |
5,542 | @register.tag(name='get_annotations_for')
def do_get_annotations_for(parser, token):
"""Use like so: {% get_annotations_for object_list as var_name %}
Note: objects in object_list must be of one ContentType!
var_name is a dict that contains the id of every object in object_list as key.
The value is anot... | IndexError | dataset/ETHPy150Open stefanw/django-annotatetext/annotatetext/templatetags/annotatetags.py/do_get_annotations_for |
5,543 | def get_dirs_and_files(self):
try:
dirs, files = self.storage.listdir(self.path)
except __HOLE__:
return [], []
if self.path:
files = [os.path.join(self.path, filename) for filename in files]
return dirs, [BoundFile(self.storage, filename) for filename... | NotImplementedError | dataset/ETHPy150Open zbyte64/django-hyperadmin/hyperadmin/resources/storages/resources.py/StorageQuery.get_dirs_and_files |
5,544 | def item_stats(host, port):
"""Check the stats for items and connection status."""
stats = None
try:
mc = memcache.Client(['%s:%s' % (host, port)])
stats = mc.get_stats()[0][1]
except __HOLE__:
raise
finally:
return stats | IndexError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/memcached_status.py/item_stats |
5,545 | def main(args):
bind_ip = str(args.ip)
port = args.port
is_up = True
try:
stats = item_stats(bind_ip, port)
current_version = stats['version']
except (__HOLE__, IndexError):
is_up = False
else:
is_up = True
if current_version not in VERSIONS:
... | TypeError | dataset/ETHPy150Open rcbops/rpc-openstack/maas/plugins/memcached_status.py/main |
5,546 | def generate_thumb(storage, video_path, thumb_size=None, format='jpg', frames=100):
histogram = []
http_status = 200
name = video_path
path = storage.path(video_path)
if not storage.exists(video_path):
return "", '404'
framemask = "%s%s%s%s" % (TMP_DIR,
... | OSError | dataset/ETHPy150Open francescortiz/image/image/videothumbs.py/generate_thumb |
5,547 | @register.filter(name="getattr")
def get_attr(obj, val):
try:
return getattr(obj, val)
except AttributeError:
try:
return obj[val]
except (__HOLE__, TypeError):
return None | KeyError | dataset/ETHPy150Open mgaitan/waliki/waliki/templatetags/waliki_tags.py/get_attr |
5,548 | def _check_system_limits():
global _system_limits_checked, _system_limited
if _system_limits_checked:
if _system_limited:
raise NotImplementedError(_system_limited)
_system_limits_checked = True
try:
import os
nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
except (__H... | AttributeError | dataset/ETHPy150Open SickRage/SickRage/lib/concurrent/futures/process.py/_check_system_limits |
5,549 | def short_name(model):
"""Return a simplified name for this model. A bit brittle."""
# for a single model, this will work
name = model.__class__.__name__
try:
if hasattr(model, 'steps'):
# pipeline
name = '-'.join( [ pair[0] for pair in model.steps ] )
elif hasatt... | AttributeError | dataset/ETHPy150Open jrmontag/mnist-sklearn/utils.py/short_name |
5,550 | def test_f(HH, Istim, freq, stim_t0, duration=1, tmax=1000):
"""Istim is amplitude of square pulse input to neuron, having
given duration in ms and frequency in Hz. Starts at stim_t0.
"""
baseline_Iapp = HH.pars['Iapp']
stim_period = 1000./freq
HH.set(tdata=[0, tmax])
n = int(floor(tmax/stim... | IndexError | dataset/ETHPy150Open robclewley/compneuro/Entrain_teacher_copy.py/test_f |
5,551 | def _pass_to_shared(self, name, item):
try:
item.traj = self.v_traj
item.name = name
item.parent = self
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open SmokinCaterpillar/pypet/pypet/shareddata.py/SharedResult._pass_to_shared |
5,552 | @classmethod
def setupClass(cls):
global np
global npt
try:
import numpy as np
import numpy.testing as npt
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/assortativity/tests/test_mixing.py/TestDegreeMixingMatrix.setupClass |
5,553 | @classmethod
def setupClass(cls):
global np
global npt
try:
import numpy as np
import numpy.testing as npt
except __HOLE__:
raise SkipTest('NumPy not available.') | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/algorithms/assortativity/tests/test_mixing.py/TestAttributeMixingMatrix.setupClass |
5,554 | def main():
"""
Run ftfy as a command-line utility.
"""
import argparse
parser = argparse.ArgumentParser(
description="ftfy (fixes text for you), version %s" % __version__
)
parser.add_argument('filename', default='-', nargs='?',
help='The file whose Unicode ... | UnicodeDecodeError | dataset/ETHPy150Open LuminosoInsight/python-ftfy/ftfy/cli.py/main |
5,555 | def take_action(self, parsed_args):
if not parsed_args.cmd:
action = HelpAction(None, None, default=self.app)
action(self.app.parser, self.app.parser, None, None)
return 1
try:
the_cmd = self.app.command_manager.find_command(
parsed_args.c... | ValueError | dataset/ETHPy150Open TurboGears/gearbox/gearbox/commands/help.py/HelpCommand.take_action |
5,556 | def reopen_connection(self):
self.close_connection()
root_delay = self.MIN_DELAY
while True:
try:
self.open_connection()
return
except Exception:
if self.verbose:
log.warning('Unable to connect to Logent... | KeyboardInterrupt | dataset/ETHPy150Open saltstack/salt/salt/engines/logentries.py/PlainTextSocketAppender.reopen_connection |
5,557 | def start(endpoint='data.logentries.com',
port=10000,
token=None,
tag='salt/engines/logentries'):
'''
Listen to salt events and forward them to Logentries
'''
if __opts__.get('id').endswith('_master'):
event_bus = salt.utils.event.get_master_event(
__opt... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/engines/logentries.py/start |
5,558 | def check_gil_released(self, func):
for n_threads in (4, 12, 32):
# Try harder each time. On an empty machine 4 threads seems
# sufficient, but in some contexts (e.g. Travis CI) we need more.
arr = self.run_in_threads(func, n_threads)
distinct = set(arr)
... | AssertionError | dataset/ETHPy150Open numba/numba/numba/tests/test_gil.py/TestGILRelease.check_gil_released |
5,559 | def get_meta_appversion_text(form_metadata):
try:
text = form_metadata['appVersion']
except __HOLE__:
return None
# just make sure this is a longish string and not something like '2.0'
if isinstance(text, (str, unicode)) and len(text) > 5:
return text
else:
return No... | KeyError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/receiverwrapper/util.py/get_meta_appversion_text |
5,560 | def stop_watching_memory():
"""Unregister memory profiling tools from IPython instance."""
global watching_memory
watching_memory = False
ip = get_ipython()
try:
ip.events.unregister("post_run_cell", watch_memory)
except ValueError:
pass
try:
ip.events.unregister("pre... | ValueError | dataset/ETHPy150Open ianozsvald/ipython_memory_usage/src/ipython_memory_usage/ipython_memory_usage_perf.py/stop_watching_memory |
5,561 | def main():
opts, args = getopt.getopt(sys.argv[1:], 'i:h')
name = None
for o, a in opts:
if o == '-i': name = a
else: usage()
pc = pcap.pcap(name)
pc.setfilter(' '.join(args))
decode = { pcap.DLT_LOOP:dpkt.loopback.Loopback,
pcap.DLT_NULL:dpkt.loopback.Lo... | KeyboardInterrupt | dataset/ETHPy150Open dugsong/pypcap/testsniff.py/main |
5,562 | @requires_venv
def do_enable():
"""
Uncomment any lines that start with #import in the .pth file
"""
try:
_lines = []
with open(vext_pth, mode='r') as f:
for line in f.readlines():
if line.startswith('#') and line[1:].lstrip().startswith('import '):
... | IOError | dataset/ETHPy150Open stuaxo/vext/vext/cmdline/__init__.py/do_enable |
5,563 | @requires_venv
def do_disable():
"""
Comment any lines that start with import in the .pth file
"""
from vext import vext_pth
try:
_lines = []
with open(vext_pth, mode='r') as f:
for line in f.readlines():
if not line.startswith('#') and line.startswith('i... | IOError | dataset/ETHPy150Open stuaxo/vext/vext/cmdline/__init__.py/do_disable |
5,564 | def getout(*args):
try:
return Popen(args, stdout=PIPE).communicate()[0]
except __HOLE__:
return '' | OSError | dataset/ETHPy150Open kivy/kivy/kivy/input/providers/probesysfs.py/getout |
5,565 | def rmtree_ignore_error(path):
""" Have to do this a lot, moving this into a function to save lines of code.
ignore_error=True should work, but doesn't.
"""
try:
shutil.rmtree(path)
except __HOLE__:
pass | OSError | dataset/ETHPy150Open kenfar/DataGristle/scripts/tests/test_gristle_dir_merger_cmd.py/rmtree_ignore_error |
5,566 | def _get_raw_post_data(self):
if not hasattr(self, '_raw_post_data'):
if self._read_started:
raise Exception("You cannot access raw_post_data after reading from request's data stream")
try:
content_length = int(self.META.get('CONTENT_LENGTH', 0))
... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/http/__init__.py/HttpRequest._get_raw_post_data |
5,567 | def __delitem__(self, header):
try:
del self._headers[header.lower()]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.3/django/http/__init__.py/HttpResponse.__delitem__ |
5,568 | def user_list(user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, return_password=False):
'''
Return a dict with information about users of a Postgres server.
Set return_password to True to get password hash in the result.
CLI Example:
.. code-block:: ba... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/postgres.py/user_list |
5,569 | def role_get(name, user=None, host=None, port=None, maintenance_db=None,
password=None, runas=None, return_password=False):
'''
Return a dict with information about users of a Postgres server.
Set return_password to True to get password hash in the result.
CLI Example:
.. code-block:... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/postgres.py/role_get |
5,570 | def schema_get(dbname, name,
db_user=None, db_password=None,
db_host=None, db_port=None):
'''
Return a dict with information about schemas in a database.
CLI Example:
.. code-block:: bash
salt '*' postgres.schema_get dbname name
dbname
Database name ... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/postgres.py/schema_get |
5,571 | def _get_object_owner(name,
object_type,
prepend='public',
maintenance_db=None,
user=None,
host=None,
port=None,
password=None,
runas=None):
'''
Return the owner of a postgres object
'''
if object_type == 'table':
query = (' '.join(... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/postgres.py/_get_object_owner |
5,572 | @staticmethod
def _resource_deserialize(s):
"""Returns dict deserialization of a given JSON string."""
try:
return json.loads(s)
except __HOLE__:
raise ResponseError('The API Response was not valid.') | ValueError | dataset/ETHPy150Open kennethreitz-archive/python-github3/github3/api.py/GithubCore._resource_deserialize |
5,573 | def main():
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--profile', help='The profile name to use '
'when starting the AWS Shell.')
args = parser.parse_args()
indexer = completion.CompletionIndex()
try:
index_str = indexer.load_index(utils.AWSCLI_VE... | KeyError | dataset/ETHPy150Open awslabs/aws-shell/awsshell/__init__.py/main |
5,574 | def _detect_gis_backend():
"""Determine whether or not a GIS backend is currently in use,
to allow for divergent behavior elsewhere.
"""
# If the connection is from `django.contrib.gis`, then we know that this
# is a GIS backend.
if '.gis.' in connections[DEFAULT_DB_ALIAS].__module__:
re... | ImportError | dataset/ETHPy150Open lukesneeringer/django-pgfields/django_pg/utils/gis.py/_detect_gis_backend |
5,575 | def import_by_path(dotted_path, error_prefix=''):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImproperlyConfigured if something goes wrong.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
... | ImportError | dataset/ETHPy150Open danirus/django-comments-xtd/django_comments_xtd/compat.py/import_by_path |
5,576 | def _parseJoints(self, node=None):
for name in self._names:
try:
self._joints.append(self._world.getXODERoot().namedChild(name).getODEObject())
except __HOLE__:
# the given object name is not found. output warning and quit.
warnings.warn("J... | KeyError | dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/actuators.py/SpecificJointActuator._parseJoints |
5,577 | def _parseJoints(self, node=None):
for name in self._names:
try:
self._joints.append(self._world.getXODERoot().namedChild(name).getODEObject())
except __HOLE__:
# the given object name is not found. output warning and quit.
warnings.warn("J... | KeyError | dataset/ETHPy150Open pybrain/pybrain/pybrain/rl/environments/ode/actuators.py/CopyJointActuator._parseJoints |
5,578 | def fit_predict(training_data, fitting_data, tau=1, samples_per_job=0, save_results=True, show=False):
from disco.worker.pipeline.worker import Worker, Stage
from disco.core import Job, result_iterator
from disco.core import Disco
"""
training_data - training samples
fitting_data - dataset to b... | ValueError | dataset/ETHPy150Open romanorac/discomll/discomll/regression/locally_weighted_linear_regression.py/fit_predict |
5,579 | def write8(self, reg, value):
"Writes an 8-bit value to the specified register/address"
try:
self.bus.write_byte_data(self.address, reg, value)
if self.debug:
print("I2C: Wrote 0x%02X to register 0x%02X" % (value, reg))
except __HOLE__ as err:
return self.errMsg() | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.write8 |
5,580 | def write16(self, reg, value):
"Writes a 16-bit value to the specified register/address pair"
try:
self.bus.write_word_data(self.address, reg, value)
if self.debug:
print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" %
(value, reg, reg+1))
except __HOLE__ as err:
ret... | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.write16 |
5,581 | def writeRaw8(self, value):
"Writes an 8-bit value on the bus"
try:
self.bus.write_byte(self.address, value)
if self.debug:
print("I2C: Wrote 0x%02X" % value)
except __HOLE__ as err:
return self.errMsg() | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.writeRaw8 |
5,582 | def writeList(self, reg, list):
"Writes an array of bytes using I2C format"
try:
if self.debug:
print("I2C: Writing list to register 0x%02X:" % reg)
print(list)
self.bus.write_i2c_block_data(self.address, reg, list)
except __HOLE__ as err:
return self.errMsg() | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.writeList |
5,583 | def readList(self, reg, length):
"Read a list of bytes from the I2C device"
try:
results = self.bus.read_i2c_block_data(self.address, reg, length)
if self.debug:
print ("I2C: Device 0x%02X returned the following from reg 0x%02X" %
(self.address, reg))
print(results)
re... | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.readList |
5,584 | def readU8(self, reg):
"Read an unsigned byte from the I2C device"
try:
result = self.bus.read_byte_data(self.address, reg)
if self.debug:
print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
(self.address, result & 0xFF, reg))
return result
except __HOLE__ as err:... | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.readU8 |
5,585 | def readS8(self, reg):
"Reads a signed byte from the I2C device"
try:
result = self.bus.read_byte_data(self.address, reg)
if result > 127: result -= 256
if self.debug:
print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" %
(self.address, result & 0xFF, reg))
return... | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.readS8 |
5,586 | def readU16(self, reg, little_endian=True):
"Reads an unsigned 16-bit value from the I2C device"
try:
result = self.bus.read_word_data(self.address,reg)
# Swap bytes if using big endian because read_word_data assumes little
# endian on ARM (little endian) systems.
if not little_endian:
... | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.readU16 |
5,587 | def readS16(self, reg, little_endian=True):
"Reads a signed 16-bit value from the I2C device"
try:
result = self.readU16(reg,little_endian)
if result > 32767: result -= 65536
return result
except __HOLE__ as err:
return self.errMsg() | IOError | dataset/ETHPy150Open DexterInd/GrovePi/Software/Python/grove_barometer_sensors/barometric_sensor_bmp180/Adafruit_I2C.py/Adafruit_I2C.readS16 |
5,588 | def geometry_string(s):
"""Get a X-style geometry definition and return a tuple.
600x400 -> (600,400)
"""
try:
x_string, y_string = s.split('x')
geometry = (int(x_string), int(y_string))
except __HOLE__:
msg = "%s is not a valid geometry specification" %s
raise argpa... | ValueError | dataset/ETHPy150Open ASPP/pelita/tkviewer.py/geometry_string |
5,589 | @never_cache
def activate(request,
uidb64=None,
token=None,
template_name='users/activate.html',
post_activation_redirect=None,
current_app=None,
extra_context=None):
context = {
'title': _('Account activation '),
}
if p... | ValueError | dataset/ETHPy150Open mishbahr/django-users2/users/views.py/activate |
5,590 | def get_cluster_info():
# The fallback constraints used for testing will come from the current
# effective constraints.
eff_constraints = dict(constraints.EFFECTIVE_CONSTRAINTS)
# We'll update those constraints based on what the /info API provides, if
# anything.
global cluster_info
global ... | KeyError | dataset/ETHPy150Open openstack/swift/test/functional/__init__.py/get_cluster_info |
5,591 | def setup_package():
global policy_specified
policy_specified = os.environ.get('SWIFT_TEST_POLICY')
in_process_env = os.environ.get('SWIFT_TEST_IN_PROCESS')
if in_process_env is not None:
use_in_process = utils.config_true_value(in_process_env)
else:
use_in_process = None
globa... | KeyError | dataset/ETHPy150Open openstack/swift/test/functional/__init__.py/setup_package |
5,592 | def load_constraint(name):
global cluster_info
try:
c = cluster_info['swift'][name]
except __HOLE__:
raise SkipTest("Missing constraint: %s" % name)
if not isinstance(c, int):
raise SkipTest("Bad value, %r, for constraint: %s" % (c, name))
return c | KeyError | dataset/ETHPy150Open openstack/swift/test/functional/__init__.py/load_constraint |
5,593 | @classmethod
def from_info(cls, info=None):
if not (info or cluster_info):
get_cluster_info()
info = info or cluster_info
try:
policy_info = info['swift']['policies']
except __HOLE__:
raise AssertionError('Did not find any policy info in %r' % info... | KeyError | dataset/ETHPy150Open openstack/swift/test/functional/__init__.py/FunctionalStoragePolicyCollection.from_info |
5,594 | def requires_policies(f):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if skip:
raise SkipTest
try:
self.policies = FunctionalStoragePolicyCollection.from_info()
except __HOLE__:
raise SkipTest("Unable to determine available policies")
... | AssertionError | dataset/ETHPy150Open openstack/swift/test/functional/__init__.py/requires_policies |
5,595 | def run(self, end_time, delay=False): # <1>
"""Schedule and display events until time is up"""
# schedule the first event for each cab
for _, proc in sorted(self.procs.items()): # <2>
first_event = next(proc) # <3>
self.events.put(first_event) # <4>
# main lo... | StopIteration | dataset/ETHPy150Open fluentpython/example-code/16-coroutine/taxi_sim_delay.py/Simulator.run |
5,596 | def blit_to_texture(self, target, level, x, y, z, internalformat=None):
'''Draw this image to to the currently bound texture at `target`.
This image's anchor point will be aligned to the given `x` and `y`
coordinates. If the currently bound texture is a 3D texture, the `z`
parameter gi... | ValueError | dataset/ETHPy150Open ardekantur/pyglet/pyglet/image/__init__.py/ImageData.blit_to_texture |
5,597 | def _convert(self, format, pitch):
'''Return data in the desired format; does not alter this instance's
current format or pitch.
'''
if format == self._current_format and pitch == self._current_pitch:
return self._current_data
self._ensure_string_data()
data ... | ValueError | dataset/ETHPy150Open ardekantur/pyglet/pyglet/image/__init__.py/ImageData._convert |
5,598 | def get_authorization(self, req, chal):
try:
realm = chal['realm']
nonce = chal['nonce']
qop = chal.get('qop')
algorithm = chal.get('algorithm', 'MD5')
# mod_digest doesn't send an opaque, even though it isn't
# supposed to be optional
... | KeyError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/samples-and-tests/i-am-a-developer/mechanize/_auth.py/AbstractDigestAuthHandler.get_authorization |
5,599 | def percentiles(self, percentiles):
"""Given a list of percentiles (floats between 0 and 1), return a
list of the values at those percentiles, interpolating if
necessary."""
try:
scores = [0.0]*len(percentiles)
if self.count > 0:
values = self.samples()
values.sort()
... | IndexError | dataset/ETHPy150Open Cue/scales/src/greplin/scales/samplestats.py/Sampler.percentiles |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.