Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,700 | def try_convert_to_date(self, word):
"""
Tries to convert word to date(datetime) using search_date_formats
Return None if word fits no one format
"""
for frm in self.search_date_formats:
try:
return datetime.datetime.strptime(word, frm).date()
... | ValueError | dataset/ETHPy150Open AndrewIngram/django-extra-views/extra_views/contrib/mixins.py/SearchableListMixin.try_convert_to_date |
2,701 | def post(self):
body = self.request.body_file.read()
stream = None
timezone_offset = self._get_timezone_offset()
# Decode the request
try:
request = remoting.decode(body, strict=self.strict,
logger=self.logger, timezone_offset=timezone_offset)
... | KeyboardInterrupt | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/PyAMF-0.6.1/pyamf/remoting/gateway/google.py/WebAppGateway.post |
2,702 | def main():
usage = "usage: follow.py <search>"
opts = utils.parse(sys.argv[1:], {}, ".splunkrc", usage=usage)
if len(opts.args) != 1:
utils.error("Search expression required", 2)
search = opts.args[0]
service = client.connect(**opts.kwargs)
job = service.jobs.create(
search, ... | KeyboardInterrupt | dataset/ETHPy150Open splunk/splunk-sdk-python/examples/follow.py/main |
2,703 | def _get_video_id(self, video_url):
match = re.findall("watch.*[\?|&]v=([\dA-Za-z_\-]+)", video_url)
try:
nid_as_youtube_url = match[0]
except __HOLE__:
nid_as_youtube_url = None
logging.error(u"couldn't get video_id for {video_url}".format(
vi... | IndexError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/youtube.py/Youtube._get_video_id |
2,704 | def _extract_biblio(self, page, id=None):
if not "snippet" in page:
raise ProviderContentMalformedError
json_response = provider._load_json(page)
this_video_json = json_response["items"][0]
dict_of_keylists = {
'title': ['snippet', 'title'],
'channe... | KeyError | dataset/ETHPy150Open Impactstory/total-impact-core/totalimpact/providers/youtube.py/Youtube._extract_biblio |
2,705 | def is_number(s, cast=float):
"""
Check if a string is a number. Use cast=int to check if s is an integer.
"""
try:
cast(s) # for int, long and float
except __HOLE__:
return False
return True | ValueError | dataset/ETHPy150Open tanghaibao/jcvi/formats/base.py/is_number |
2,706 | def start(self, *pages):
""" Takes a list of Page instances, creates html files, and starts
the server. """
# Make sure at least one page has been given:
if not(pages):
print "*Can't start server - no pages provided."
return
# Make sure pages/ directory exists:
if not(os.path.e... | KeyboardInterrupt | dataset/ETHPy150Open graycatlabs/PyBBIO/bbio/libraries/BBIOServer/bbio_server.py/BBIOServer.start |
2,707 | def kv_create(request, kv_class, obj_pk):
"""
POST to:
/core/keyvalue/api/<kv_class>/create/
with parameters like:
{
'key': 'key_string'
'value': 'value_string'
'obj_pk': 1
}
Status Codes:
* 201 - Object created
* 400 - Issues during creation
""... | ValidationError | dataset/ETHPy150Open mozilla/inventory/core/keyvalue/api.py/kv_create |
2,708 | def kv_update(request, kv_class, kv_pk):
"""
POST to:
/core/keyvalue/api/<kv_class>/<kv_pk>/update/
with parameters like:
{
'key': 'key_string'
'value': 'value_string'
'obj_pk': 1
}
Status Codes:
* 200 - Object updated
* 400 - Issues during update
... | ValidationError | dataset/ETHPy150Open mozilla/inventory/core/keyvalue/api.py/kv_update |
2,709 | def read( fname ):
try:
return open( os.path.join( os.path.dirname( __file__ ), fname ) ).read()
except __HOLE__:
return '' | IOError | dataset/ETHPy150Open ilblackdragon/django-blogs/setup.py/read |
2,710 | def _run(self):
if not self._running:
return
next_call = None
try:
next_call = self.callback()
except (KeyboardInterrupt, __HOLE__):
raise
except:
logging.error("Error in periodic callback", exc_info=True)
if self._runnin... | SystemExit | dataset/ETHPy150Open mrjoes/tornadio/tornadio/periodic.py/Callback._run |
2,711 | def reduce(func,iterable,initializer=None):
args = iter(iterable)
if initializer is not None:
res = initializer
else:
res = next(args)
while True:
try:
res = func(res,next(args))
except __HOLE__:
return res | StopIteration | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/_functools.py/reduce |
2,712 | def __getattr__(self, key):
"""Python only calls this when key is missing!"""
try:
return self.__getitem__(key)
except __HOLE__:
raise AttributeError(key) | KeyError | dataset/ETHPy150Open plotly/plotly.py/plotly/graph_objs/graph_objs.py/PlotlyDict.__getattr__ |
2,713 | def force_clean(self, **kwargs):
"""Recursively remove empty/None values."""
keys = list(self.keys())
for key in keys:
try:
self[key].force_clean()
except __HOLE__:
pass
if isinstance(self[key], (dict, list)):
if... | AttributeError | dataset/ETHPy150Open plotly/plotly.py/plotly/graph_objs/graph_objs.py/PlotlyDict.force_clean |
2,714 | def _patch_figure_class(figure_class):
def __init__(self, *args, **kwargs):
super(figure_class, self).__init__(*args, **kwargs)
if 'data' not in self:
self.data = GraphObjectFactory.create('data', _parent=self,
_parent_key='data')
fi... | AttributeError | dataset/ETHPy150Open plotly/plotly.py/plotly/graph_objs/graph_objs.py/_patch_figure_class |
2,715 | def openpty():
"""openpty() -> (master_fd, slave_fd)
Open a pty master/slave pair, using os.openpty() if possible."""
try:
return os.openpty()
except (__HOLE__, OSError):
pass
master_fd, slave_name = _open_terminal()
slave_fd = slave_open(slave_name)
return master_fd, slave_... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/openpty |
2,716 | def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, __HOLE__):
pass
else:
slave_name =... | OSError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/master_open |
2,717 | def _open_terminal():
"""Open pty master and return (master_fd, tty_name).
SGI and generic BSD version, for when openpty() fails."""
try:
import sgi
except ImportError:
pass
else:
try:
tty_name, master_fd = sgi._getpty(os.O_RDWR, 0666, 0)
except __HOLE__, ... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/_open_terminal |
2,718 | def slave_open(tty_name):
"""slave_open(tty_name) -> slave_fd
Open the pty slave and acquire the controlling terminal, returning
opened filedescriptor.
Deprecated, use openpty() instead."""
result = os.open(tty_name, os.O_RDWR)
try:
from fcntl import ioctl, I_PUSH
except __HOLE__:
... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/slave_open |
2,719 | def fork():
"""fork() -> (pid, master_fd)
Fork and make the child a session leader with a controlling terminal."""
try:
pid, fd = os.forkpty()
except (__HOLE__, OSError):
pass
else:
if pid == CHILD:
try:
os.setsid()
except OSError:
... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/fork |
2,720 | def spawn(argv, master_read=_read, stdin_read=_read):
"""Create a spawned process."""
if type(argv) == type(''):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)
... | OSError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/pty.py/spawn |
2,721 | @contextlib.contextmanager
def tempdir(**kwargs):
argdict = kwargs.copy()
if 'dir' not in argdict:
argdict['dir'] = CONF.tempdir
tmpdir = tempfile.mkdtemp(**argdict)
try:
yield tmpdir
finally:
try:
shutil.rmtree(tmpdir)
except __HOLE__ as e:
LO... | OSError | dataset/ETHPy150Open openstack/ec2-api/ec2api/utils.py/tempdir |
2,722 | def check_ceph_df():
'Program entry point.'
try:
res = subprocess.check_output(["ceph", "df", "--format=json"],
stderr=subprocess.STDOUT)
exit_code, message = interpret_output_df(res)
sys.stdout.write("%s\n" % message)
sys.exit(exit_code)
... | OSError | dataset/ETHPy150Open openstack/monitoring-for-openstack/oschecks/ceph.py/check_ceph_df |
2,723 | def check_ceph_health():
'Program entry point.'
try:
res = subprocess.check_output(["ceph", "health"],
stderr=subprocess.STDOUT)
exit_code, message = interpret_output_health(res)
sys.stdout.write(message)
sys.exit(exit_code)
except subpr... | OSError | dataset/ETHPy150Open openstack/monitoring-for-openstack/oschecks/ceph.py/check_ceph_health |
2,724 | def poll():
""" Callback function that polls for new tasks based on a schedule. """
deployment_id = helper.get_deployment_id()
# If the deployment is not registered, skip.
if not deployment_id:
return
# If we can't reach the backup and recovery services, skip.
nodes = helper.get_node_info()
http_clie... | ValueError | dataset/ETHPy150Open AppScale/appscale/Hermes/hermes.py/poll |
2,725 | def ArrayOf(klass):
"""Function to return a class that can encode and decode a list of
some other type."""
global _array_of_map
global _array_of_classes, _sequence_of_classes
# if this has already been built, return the cached one
if klass in _array_of_map:
return _array_of_map[klass]
... | TypeError | dataset/ETHPy150Open JoelBender/bacpypes/py27/bacpypes/constructeddata.py/ArrayOf |
2,726 | def decode_base58(bc, length):
n = 0
for char in bc:
n = n * 58 + DIGITS58.index(char)
try:
return n.to_bytes(length, 'big')
except __HOLE__:
return _long_to_bytes(n, length, 'big') | AttributeError | dataset/ETHPy150Open blockcypher/blockcypher-python/blockcypher/utils.py/decode_base58 |
2,727 | def instance(self, uri, cls=None, default=None, **kwargs):
instance = self._instances.get(uri, None)
if instance is None:
if cls is None:
try:
cls = self._resources[uri[:uri.rfind('/')]]
except __HOLE__:
cls = Reference... | KeyError | dataset/ETHPy150Open biosustain/potion-client/potion_client/__init__.py/Client.instance |
2,728 | def create_test_zipline(**config):
"""
:param config: A configuration object that is a dict with:
- sid - an integer, which will be used as the asset ID.
- order_count - the number of orders the test algo will place,
defaults to 100
- order_amount - the number o... | KeyError | dataset/ETHPy150Open quantopian/zipline/zipline/utils/simfactory.py/create_test_zipline |
2,729 | def __init__(self, graph=None, encoding="utf-8",prettyprint=True):
try:
import xml.etree.ElementTree
except __HOLE__:
raise ImportError('GraphML writer requires '
'xml.elementtree.ElementTree')
self.prettyprint=prettyprint
self.enco... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/graphml.py/GraphMLWriter.__init__ |
2,730 | def get_key(self, name, attr_type, scope, default):
keys_key = (name, attr_type, scope)
try:
return self.keys[keys_key]
except __HOLE__:
new_id = "d%i" % len(list(self.keys))
self.keys[keys_key] = new_id
key_kwargs = {"id":new_id,
... | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/graphml.py/GraphMLWriter.get_key |
2,731 | def __init__(self, node_type=str):
try:
import xml.etree.ElementTree
except __HOLE__:
raise ImportError('GraphML reader requires '
'xml.elementtree.ElementTree')
self.node_type=node_type
self.multigraph=False # assume multigraph and... | ImportError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/graphml.py/GraphMLReader.__init__ |
2,732 | def decode_data_elements(self, graphml_keys, obj_xml):
"""Use the key information to decode the data XML if present."""
data = {}
for data_element in obj_xml.findall("{%s}data" % self.NS_GRAPHML):
key = data_element.get("key")
try:
data_name=graphml_keys[k... | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/graphml.py/GraphMLReader.decode_data_elements |
2,733 | def __init__(self,
count,
max_count = None,
prepend = None,
width = 'auto',
speed_calc_cycles = 10,
interval = 1,
verbose = 0,
sigi... | TypeError | dataset/ETHPy150Open cimatosa/jobmanager/jobmanager/progress.py/Progress.__init__ |
2,734 | def _DisplayHost(self, computer, self_report):
"""Displays the report for a single host.
Args:
computer: models.Computer object to display.
self_report: if True, display as self report.
"""
uuid = computer.uuid
popup = self.request.get('format', None) == 'popup'
if popup:
li... | AttributeError | dataset/ETHPy150Open google/simian/src/simian/mac/admin/host.py/Host._DisplayHost |
2,735 | def write_csv_header(self):
if self.is_dict:
try:
self.writer.writeheader()
except __HOLE__:
# For Python<2.7
self.writer.writerow(dict(zip(
self.writer.fieldnames,
... | AttributeError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/openstack_dashboard/usage/base.py/CsvDataMixin.write_csv_header |
2,736 | def serve_file(request, response, path, type=None, disposition=None,
name=None):
"""Set status, headers, and body in order to serve the given file.
The Content-Type header will be set to the type arg, if provided.
If not provided, the Content-Type will be guessed by the file extension
of... | OSError | dataset/ETHPy150Open circuits/circuits/circuits/web/tools.py/serve_file |
2,737 | def check_auth(request, response, realm, users, encrypt=None):
"""Check Authentication
If an Authorization header contains credentials, return True, else False.
:param realm: The authentication realm.
:type realm: str
:param users: A dict of the form: {username: password} or a callable
... | TypeError | dataset/ETHPy150Open circuits/circuits/circuits/web/tools.py/check_auth |
2,738 | def run_python_module(modulename, args):
"""Run a python module, as though with ``python -m name args...``.
`modulename` is the name of the module, possibly a dot-separated name.
`args` is the argument array to present as sys.argv, including the first
element naming the module being executed.
"""
... | ImportError | dataset/ETHPy150Open nedbat/byterun/byterun/execfile.py/run_python_module |
2,739 | def run_python_file(filename, args, package=None):
"""Run a python file as if it were the main program on the command line.
`filename` is the path to the file to execute, it need not be a .py file.
`args` is the argument array to present as sys.argv, including the first
element naming the file being ex... | IOError | dataset/ETHPy150Open nedbat/byterun/byterun/execfile.py/run_python_file |
2,740 | def view_task(request, cog_atlas_id=None):
'''view_task returns a view to see a group of images associated with a particular cognitive atlas task.
:param cog_atlas_id: statmaps.models.CognitiveAtlasTask the id for the task defined in the Cognitive Atlas
'''
from cogat_functions import get_task_graph
... | ObjectDoesNotExist | dataset/ETHPy150Open NeuroVault/NeuroVault/neurovault/apps/statmaps/views.py/view_task |
2,741 | def serve_nidm(request, collection_cid, nidmdir, sep, path):
collection = get_collection(collection_cid, request, mode='file')
basepath = os.path.join(settings.PRIVATE_MEDIA_ROOT, 'images')
fpath = path if sep is '/' else ''.join([nidmdir, sep, path])
try:
nidmr = collection.basecollectionitem_s... | ObjectDoesNotExist | dataset/ETHPy150Open NeuroVault/NeuroVault/neurovault/apps/statmaps/views.py/serve_nidm |
2,742 | @csrf_exempt
def atlas_query_region(request):
# this query is significantly faster (from 2-4 seconds to <1 second) if the synonyms don't need to be queried
# i was previously in contact with NIF and it seems like it wouldn't be too hard to download all the synonym data
search = request.GET.get('region','')
... | ValueError | dataset/ETHPy150Open NeuroVault/NeuroVault/neurovault/apps/statmaps/views.py/atlas_query_region |
2,743 | @csrf_exempt
def atlas_query_voxel(request):
X = request.GET.get('x','')
Y = request.GET.get('y','')
Z = request.GET.get('z','')
collection = name = request.GET.get('collection','')
atlas = request.GET.get('atlas','').replace('\'', '')
try:
collection_object = Collection.objects.filter(n... | IndexError | dataset/ETHPy150Open NeuroVault/NeuroVault/neurovault/apps/statmaps/views.py/atlas_query_voxel |
2,744 | @staticmethod
def set_actor(user, sender, instance, **kwargs):
"""
Signal receiver with an extra, required 'user' kwarg. This method becomes a real (valid) signal receiver when
it is curried with the actor.
"""
try:
app_label, model_name = settings.AUTH_USER_MODEL... | ValueError | dataset/ETHPy150Open jjkester/django-auditlog/src/auditlog/middleware.py/AuditlogMiddleware.set_actor |
2,745 | def test_field_types(self):
# Very likely need to look into adding support for these field types
skip_fields = [
getattr(models.fields.related, 'ForeignObject', None),
getattr(models.fields, 'GenericIPAddressField', None),
getattr(models.fields.proxy, 'OrderWrt', Non... | AttributeError | dataset/ETHPy150Open praekelt/django-export/export/tests/__init__.py/FieldsTestCase.test_field_types |
2,746 | def shlex_split(x):
"""Helper function to split lines into segments.
"""
# shlex.split raises an exception if there is a syntax error in sh syntax
# for example if no closing " is found. This function keeps dropping the
# last character of the line until shlex.split does not raise
# an exception... | ValueError | dataset/ETHPy150Open ipython/ipython-py3k/IPython/core/completerlib.py/shlex_split |
2,747 | def prepare_post(self, data, amount):
invoice = "%s" % data.id
failct = data.paymentfailures.count()
if failct > 0:
invoice = "%s_%i" % (invoice, failct)
try:
cc = data.credit_card
balance = trunc_decimal(data.balance, 2)
self.packet['Ven... | AttributeError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/payment/modules/sagepay/processor.py/PaymentProcessor.prepare_post |
2,748 | def capture_payment(self, testing=False, order=None, amount=None):
"""Execute the post to Sage Pay VSP DIRECT"""
if not order:
order = self.order
if order.paid_in_full:
self.log_extra('%s is paid in full, no capture attempted.', order)
self.record_payment()
... | KeyError | dataset/ETHPy150Open dokterbob/satchmo/satchmo/apps/payment/modules/sagepay/processor.py/PaymentProcessor.capture_payment |
2,749 | def delete_doc(self, doc_id):
""" Deletes a document by doc ID.
Args:
doc_id: A list of document IDs.
Raises:
search_exceptions.InternalError on internal errors.
"""
solr_request = {"delete": {"id": doc_id}}
solr_url = "http://{0}:{1}/solr/update?commit=true".format(self._search_loc... | ValueError | dataset/ETHPy150Open AppScale/appscale/SearchService/solr_interface.py/Solr.delete_doc |
2,750 | def get_index(self, app_id, namespace, name):
""" Gets an index from SOLR.
Performs a JSON request to the SOLR schema API to get the list of defined
fields. Extracts the fields that match the naming convention
appid_[namespace]_index_name.
Args:
app_id: A str, the application identifier.
... | ValueError | dataset/ETHPy150Open AppScale/appscale/SearchService/solr_interface.py/Solr.get_index |
2,751 | def update_schema(self, updates):
""" Updates the schema of a document.
Args:
updates: A list of updates to apply.
Raises:
search_exceptions.InternalError on internal errors from SOLR.
"""
field_list = []
for update in updates:
field_list.append({'name': update['name'], 'type'... | ValueError | dataset/ETHPy150Open AppScale/appscale/SearchService/solr_interface.py/Solr.update_schema |
2,752 | def commit_update(self, hash_map):
""" Commits field/value changes to SOLR.
Args:
hash_map: A dictionary to send to SOLR.
Raises:
search_exceptions.InternalError: On failure.
"""
docs = []
docs.append(hash_map)
json_payload = simplejson.dumps(docs)
solr_url = "http://{0}:{1... | ValueError | dataset/ETHPy150Open AppScale/appscale/SearchService/solr_interface.py/Solr.commit_update |
2,753 | def __execute_query(self, solr_query):
""" Executes query string on SOLR.
Args:
solr_query: A str, the query to run.
Returns:
The results from the query executing.
Raises:
search_exceptions.InternalError on internal SOLR error.
"""
solr_url = "http://{0}:{1}/solr/select/?wt=j... | ValueError | dataset/ETHPy150Open AppScale/appscale/SearchService/solr_interface.py/Solr.__execute_query |
2,754 | def to_representation(self, obj):
if obj is None:
return \
super(SubmissionStatsInstanceSerializer, self).to_representation(obj)
request = self.context.get('request')
field = request.query_params.get('group')
name = request.query_params.get('name', field)
... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/serializers/stats_serializer.py/SubmissionStatsInstanceSerializer.to_representation |
2,755 | def to_representation(self, obj):
if obj is None:
return super(StatsInstanceSerializer, self).to_representation(obj)
request = self.context.get('request')
method = request.query_params.get('method', None)
field = request.query_params.get('field', None)
if field and ... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/libs/serializers/stats_serializer.py/StatsInstanceSerializer.to_representation |
2,756 | @webapp.route('/log')
def view_log():
filename = request.args['filename']
seek_tail = request.args.get('seek_tail', '1') != '0'
session_key = session.get('client_id')
try:
content = current_service.read_log(filename, session_key=session_key, seek_tail=seek_tail)
except __HOLE__:
err... | KeyError | dataset/ETHPy150Open Jahaja/psdash/psdash/web.py/view_log |
2,757 | @webapp.route('/log/search')
def search_log():
filename = request.args['filename']
query_text = request.args['text']
session_key = session.get('client_id')
try:
data = current_service.search_log(filename, query_text, session_key=session_key)
return jsonify(data)
except __HOLE__:
... | KeyError | dataset/ETHPy150Open Jahaja/psdash/psdash/web.py/search_log |
2,758 | def __init__(self, backend, cipher, mode, operation):
self._backend = backend
self._cipher = cipher
self._mode = mode
self._operation = operation
# There is a bug in CommonCrypto where block ciphers do not raise
# kCCAlignmentError when finalizing if you supply non-block ... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cryptography-1.3.1/src/cryptography/hazmat/backends/commoncrypto/ciphers.py/_CipherContext.__init__ |
2,759 | def __init__(self, backend, cipher, mode, operation):
self._backend = backend
self._cipher = cipher
self._mode = mode
self._operation = operation
self._tag = None
registry = self._backend._cipher_registry
try:
cipher_enum, mode_enum = registry[type(ci... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/cryptography-1.3.1/src/cryptography/hazmat/backends/commoncrypto/ciphers.py/_GCMCipherContext.__init__ |
2,760 | def dump_ifd(self, ifd, ifd_name, tag_dict=EXIF_TAGS, relative=0, stop_tag=DEFAULT_STOP_TAG):
"""
Return a list of entries in the given IFD.
"""
# make sure we can process the entries
try:
entries = self.s2n(ifd, 2)
except TypeError:
logger.warning... | IndexError | dataset/ETHPy150Open ianare/exif-py/exifread/classes.py/ExifHeader.dump_ifd |
2,761 | def _canon_decode_tag(self, value, mn_tags):
"""
Decode Canon MakerNote tag based on offset within tag.
See http://www.burren.cx/david/canon.html by David Burren
"""
for i in range(1, len(value)):
tag = mn_tags.get(i, ('Unknown', ))
name = tag[0]
... | TypeError | dataset/ETHPy150Open ianare/exif-py/exifread/classes.py/ExifHeader._canon_decode_tag |
2,762 | def _set_pages(self, pages):
""" The pages setter. """
# Remove pages from the old list that appear in the new list. The old
# list will now contain pages that are no longer in the wizard.
old_pages = self.pages
new_pages = []
for page in pages:
try:
... | ValueError | dataset/ETHPy150Open enthought/pyface/pyface/ui/qt4/wizard/wizard.py/Wizard._set_pages |
2,763 | def get_streaming_event():
try:
now = datetime.datetime.now()
streaming_event = Event.objects.filter(public=True,
start_date__lte=now).order_by('-start_date')[0]
try:
next_event = streaming_event.get_next()
except Event.DoesN... | IndexError | dataset/ETHPy150Open kiberpipa/Intranet/pipa/video/utils.py/get_streaming_event |
2,764 | def get_next_streaming_event():
now = datetime.datetime.now()
q = Event.objects.filter(public=True,
require_video=True,
start_date__gte=now)
try:
return q.order_by('-start_date')[0]
except __HOLE__:
return | IndexError | dataset/ETHPy150Open kiberpipa/Intranet/pipa/video/utils.py/get_next_streaming_event |
2,765 | def AtomicWrite(filename, contents, mode=0666, gid=None):
"""Create a file 'filename' with 'contents' atomically.
As in Write, 'mode' is modified by the umask. This creates and moves
a temporary file, and errors doing the above will be propagated normally,
though it will try to clean up the temporary file in ... | OSError | dataset/ETHPy150Open google/google-apputils/google/apputils/file_util.py/AtomicWrite |
2,766 | @contextlib.contextmanager
def TemporaryDirectory(suffix='', prefix='tmp', base_path=None):
"""A context manager to create a temporary directory and clean up on exit.
The parameters are the same ones expected by tempfile.mkdtemp.
The directory will be securely and atomically created.
Everything under it will b... | OSError | dataset/ETHPy150Open google/google-apputils/google/apputils/file_util.py/TemporaryDirectory |
2,767 | def MkDirs(directory, force_mode=None):
"""Makes a directory including its parent directories.
This function is equivalent to os.makedirs() but it avoids a race
condition that os.makedirs() has. The race is between os.mkdir() and
os.path.exists() which fail with errors when run in parallel.
Args:
direc... | OSError | dataset/ETHPy150Open google/google-apputils/google/apputils/file_util.py/MkDirs |
2,768 | def RmDirs(dir_name):
"""Removes dir_name and every subsequently empty directory above it.
Unlike os.removedirs and shutil.rmtree, this function doesn't raise an error
if the directory does not exist.
Args:
dir_name: Directory to be removed.
"""
try:
shutil.rmtree(dir_name)
except OSError, err:
... | OSError | dataset/ETHPy150Open google/google-apputils/google/apputils/file_util.py/RmDirs |
2,769 | def end(self, c):
tdata = c.tableData
data = tdata.get_data()
# Add missing columns so that each row has the same count of columns
# This prevents errors in Reportlab table
try:
maxcols = max([len(row) for row in data] or [0])
except __HOLE__:
lo... | ValueError | dataset/ETHPy150Open xhtml2pdf/xhtml2pdf/xhtml2pdf/tables.py/pisaTagTABLE.end |
2,770 | def insertBefore(self, newChild, refChild):
""" Inserts the node newChild before the existing child node refChild.
If refChild is null, insert newChild at the end of the list of children.
"""
if newChild.nodeType not in self._child_node_types:
raise IllegalChild, "%s cann... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/packages/odf/element.py/Node.insertBefore |
2,771 | def removeChild(self, oldChild):
""" Removes the child node indicated by oldChild from the list of children, and returns it.
"""
#FIXME: update ownerDocument.element_dict or find other solution
try:
self.childNodes.remove(oldChild)
except __HOLE__:
raise x... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/tablib-0.10.0/tablib/packages/odf/element.py/Node.removeChild |
2,772 | def on_dccchat(self, c, e):
if len(e.arguments) != 2:
return
args = e.arguments[1].split()
if len(args) == 4:
try:
address = ip_numstr_to_quad(args[2])
port = int(args[3])
except __HOLE__:
return
self... | ValueError | dataset/ETHPy150Open zulip/zulip/bots/irc-mirror.py/IRCBot.on_dccchat |
2,773 | def update_wrapper(wrapper, wrapped, *a, **ka):
try:
functools.update_wrapper(wrapper, wrapped, *a, **ka)
except __HOLE__:
pass
# These helpers are used at module level and need to be defined first.
# And yes, I know PEP-8, but sometimes a lower-case classname makes more sense. | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/update_wrapper |
2,774 | def add(self, rule, method, target, name=None):
""" Add a new rule or replace the target for an existing rule. """
anons = 0 # Number of anonymous wildcards found
keys = [] # Names of keys
pattern = '' # Regular expression pattern with named groups
filters = [] # Lists of wil... | ValueError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/Router.add |
2,775 | def build(self, _name, *anons, **query):
""" Build an URL by filling the wildcards in a rule. """
builder = self.builder.get(_name)
if not builder:
raise RouteBuildError("No route with that name.", _name)
try:
for i, value in enumerate(anons):
quer... | KeyError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/Router.build |
2,776 | def _handle(self, environ):
path = environ['bottle.raw_path'] = environ['PATH_INFO']
if py3k:
try:
environ['PATH_INFO'] = path.encode('latin1').decode('utf8')
except UnicodeError:
return HTTPError(400, 'Invalid path string. Expected UTF-8')
... | SystemExit | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/Bottle._handle |
2,777 | def _cast(self, out, peek=None):
""" Try to convert the parameter into something WSGI compatible and set
correct HTTP headers when possible.
Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like,
iterable of strings and iterable of unicodes
"""
# Empty o... | SystemExit | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/Bottle._cast |
2,778 | def wsgi(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
out = self._cast(self._handle(environ))
# rfc2616 section 4.3
if response._status_code in (100, 101, 204, 304)\
or environ['REQUEST_METHOD'] == 'HEAD':
if hasa... | KeyboardInterrupt | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/Bottle.wsgi |
2,779 | @staticmethod
def _iter_chunked(read, bufsize):
err = HTTPError(400, 'Error while parsing chunked transfer body.')
rn, sem, bs = tob('\r\n'), tob(';'), tob('')
while True:
header = read(1)
while header[-2:] != rn:
c = read(1)
header += ... | ValueError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/BaseRequest._iter_chunked |
2,780 | @DictProperty('environ', 'bottle.request.body', read_only=True)
def _body(self):
try:
read_func = self.environ['wsgi.input'].read
except __HOLE__:
self.environ['wsgi.input'] = BytesIO()
return self.environ['wsgi.input']
body_iter = self._iter_chunked if se... | KeyError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/BaseRequest._body |
2,781 | def __getattr__(self, name):
""" Search in self.environ for additional user defined attributes. """
try:
var = self.environ['bottle.request.ext.%s' % name]
return var.__get__(self) if hasattr(var, '__get__') else var
except __HOLE__:
raise AttributeError('Attr... | KeyError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/BaseRequest.__getattr__ |
2,782 | def _local_property():
ls = threading.local()
def fget(_):
try:
return ls.var
except __HOLE__:
raise RuntimeError("Request context not initialized.")
def fset(_, value):
ls.var = value
def fdel(_):
del ls.var
return property(fget, fset, fde... | AttributeError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/_local_property |
2,783 | def apply(self, callback, _):
dumps = self.json_dumps
if not dumps: return callback
def wrapper(*a, **ka):
try:
rv = callback(*a, **ka)
except __HOLE__:
rv = _e()
if isinstance(rv, dict):
#Attempt to serialize,... | HTTPError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/JSONPlugin.apply |
2,784 | def getunicode(self, name, default=None, encoding=None):
""" Return the value as a unicode string, or the default. """
try:
return self._fix(self[name], encoding)
except (UnicodeError, __HOLE__):
return default | KeyError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/FormsDict.getunicode |
2,785 | def parse_date(ims):
""" Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """
try:
ts = email.utils.parsedate_tz(ims)
return time.mktime(ts[:8] + (0, )) - (ts[9] or 0) - time.timezone
except (__HOLE__, ValueError, IndexError, OverflowError):
return None | TypeError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/parse_date |
2,786 | def parse_auth(header):
""" Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None"""
try:
method, data = header.split(None, 1)
if method.lower() == 'basic':
user, pwd = touni(base64.b64decode(tob(data))).split(':', 1)
return user, pw... | ValueError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/parse_auth |
2,787 | def parse_range_header(header, maxlen=0):
""" Yield (start, end) ranges parsed from a HTTP Range header. Skip
unsatisfiable ranges. The end index is non-inclusive."""
if not header or header[:6] != 'bytes=': return
ranges = [r.split('-', 1) for r in header[6:].split(',') if '-' in r]
for start, ... | ValueError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/parse_range_header |
2,788 | def run(self, app): # pragma: no cover
from wsgiref.simple_server import make_server
from wsgiref.simple_server import WSGIRequestHandler, WSGIServer
import socket
class FixedHandler(WSGIRequestHandler):
def address_string(self): # Prevent reverse DNS lookups please.
... | KeyboardInterrupt | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/WSGIRefServer.run |
2,789 | def run(self, handler):
from eventlet import wsgi, listen, patcher
if not patcher.is_monkey_patched(os):
msg = "Bottle requires eventlet.monkey_patch() (before import)"
raise RuntimeError(msg)
socket_args = {}
for arg in ('backlog', 'family'):
try:
... | KeyError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/EventletServer.run |
2,790 | def run(self, handler):
import asyncio
from aiohttp.wsgi import WSGIServerHttpProtocol
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
protocol_factory = lambda: WSGIServerHttpProtocol(
handler,
readpayload=True,
debug=(... | KeyboardInterrupt | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/AiohttpServer.run |
2,791 | def run(self, handler):
for sa in self.adapters:
try:
return sa(self.host, self.port, **self.options).run(handler)
except __HOLE__:
pass | ImportError | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/AutoServer.run |
2,792 | def run(app=None,
server='wsgiref',
host='127.0.0.1',
port=8080,
interval=1,
reloader=False,
quiet=False,
plugins=None,
debug=None, **kargs):
""" Start a server instance. This method blocks until the server terminates.
:param app: WSGI applica... | SystemExit | dataset/ETHPy150Open Arelle/Arelle/arelle/webserver/bottle.py/run |
2,793 | def execute_for(self, targets):
session_setup = self.setup_repl_session(targets)
self.context.release_lock()
with stty_utils.preserve_stty_settings():
with self.context.new_workunit(name='repl', labels=[WorkUnitLabel.RUN]):
print('') # Start REPL output on a new line.
try:
r... | KeyboardInterrupt | dataset/ETHPy150Open pantsbuild/pants/src/python/pants/task/repl_task_mixin.py/ReplTaskMixin.execute_for |
2,794 | def get_last_log(self, file_name=None, finished=False):
"""
Execute query for the given command most recently started CalAccessCommandLog,
unless finished=True, in which case query for the most recently finished.
Commands that require a file / model as a positional argument should
... | IndexError | dataset/ETHPy150Open california-civic-data-coalition/django-calaccess-raw-data/calaccess_raw/management/commands/__init__.py/CalAccessCommand.get_last_log |
2,795 | def get_caller_log(self):
"""
If the command was called by another command, return the caller's
RawDataCommandLog object. Else, return None.
"""
caller = None
if not self._called_from_command_line:
# TODO: see if there's another way to identify caller
... | IndexError | dataset/ETHPy150Open california-civic-data-coalition/django-calaccess-raw-data/calaccess_raw/management/commands/__init__.py/CalAccessCommand.get_caller_log |
2,796 | def main():
args = parser.parse_args()
if args.verbose > 1:
logging.basicConfig(level=logging.DEBUG)
elif args.verbose > 0:
logging.basicConfig(level=logging.INFO)
server = DAPLinkServer(args.address,
socket=args.socket,
inter... | KeyboardInterrupt | dataset/ETHPy150Open geky/pyDAPLink/pyDAPLink/tools/pydaplink_server.py/main |
2,797 | def __init__(self, symtable=None, writer=None, with_plugins=True):
self.writer = writer or StdWriter()
self.writer._larch = self
if symtable is None:
symtable = SymbolTable(larch=self)
self.symtable = symtable
self._interrupt = None
self.error = []
... | AttributeError | dataset/ETHPy150Open xraypy/xraylarch/lib/interpreter.py/Interpreter.__init__ |
2,798 | def run(self, node, expr=None, func=None,
fname=None, lineno=None, with_raise=False):
"""executes parsed Ast representation for an expression"""
# Note: keep the 'node is None' test: internal code here may run
# run(None) and expect a None in return.
# print(" Run", node, ... | TypeError | dataset/ETHPy150Open xraypy/xraylarch/lib/interpreter.py/Interpreter.run |
2,799 | def eval(self, expr, fname=None, lineno=0):
"""evaluates a single statement"""
self.fname = fname
self.lineno = lineno
self.error = []
try:
node = self.parse(expr, fname=fname, lineno=lineno)
except __HOLE__:
errmsg = sys.exc_info()[1]
... | RuntimeError | dataset/ETHPy150Open xraypy/xraylarch/lib/interpreter.py/Interpreter.eval |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.