Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
7,300 | def test_PortageInstaller():
if not is_gentoo():
print("Skipping not Gentoo")
return
from rosdep2.platforms.gentoo import PortageInstaller
@patch.object(PortageInstaller, 'get_packages_to_install')
def test(mock_method):
installer = PortageInstaller()
mock_method.retur... | AssertionError | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_gentoo.py/test_PortageInstaller |
7,301 | @classmethod
def deserialize(cls, fd, **kw):
try:
return cls._deserialize(fd, **kw)
except (struct.error, __HOLE__) as err:
raise cls.exception(err) | IOError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/packages/flashmedia/packet.py/Packet.deserialize |
7,302 | @classmethod
def deserialize_from(cls, buf, offset, **kw):
try:
return cls._deserialize_from(buf, offset, **kw)
except (struct.error, __HOLE__) as err:
raise cls.exception(err) | IOError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/packages/flashmedia/packet.py/Packet.deserialize_from |
7,303 | def ready(self):
self.responding = False
self.synchronised = False
self.get_cpu_average()
try:
self._proxy.getinfo()
self.responding = True
except (__HOLE__, socket.error, httplib.CannotSendRequest) as e:
# print "daemon offline"
... | ValueError | dataset/ETHPy150Open moocowmoo/dashvend/bin/dashvend/dashrpc.py/DashRPC.ready |
7,304 | @stockholm.sniffer()
def _stockholm_sniffer(fh):
# Smells a Stockholm file if the following conditions are met:
# - File isn't empty
# - File contains correct header
try:
line = next(fh)
except __HOLE__:
return False, {}
if _is_header(line):
return True, {}
return F... | StopIteration | dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/stockholm.py/_stockholm_sniffer |
7,305 | @stockholm.reader(TabularMSA)
def _stockholm_to_tabular_msa(fh, constructor=None):
# Checks that user has passed required constructor parameter
if constructor is None:
raise ValueError("Must provide `constructor` parameter indicating the "
"type of sequences in the alignment. `c... | StopIteration | dataset/ETHPy150Open biocore/scikit-bio/skbio/io/format/stockholm.py/_stockholm_to_tabular_msa |
7,306 | def import_module(module_name):
"""
Given a dotted Python path, imports & returns the module.
If not found, raises ``UnknownModuleError``.
Ex::
mod = import_module('random')
:param module_name: The dotted Python path
:type module_name: string
:returns: module
"""
try:
... | ImportError | dataset/ETHPy150Open toastdriven/alligator/alligator/utils.py/import_module |
7,307 | def import_attr(module_name, attr_name):
"""
Given a dotted Python path & an attribute name, imports the module &
returns the attribute.
If not found, raises ``UnknownCallableError``.
Ex::
choice = import_attr('random', 'choice')
:param module_name: The dotted Python path
:type m... | AttributeError | dataset/ETHPy150Open toastdriven/alligator/alligator/utils.py/import_attr |
7,308 | @require_POST
@csrf_exempt
def import_submission_for_form(request, username, id_string):
""" Retrieve and process submission from SMSSync Request """
sms_identity = request.POST.get('from_number', '').strip()
sms_text = request.POST.get('content', '').strip()
now_timestamp = datetime.datetime.now().str... | ValueError | dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/sms_support/providers/telerivet.py/import_submission_for_form |
7,309 | def valid_host_source(value):
try:
section = SECTIONS["hosts:" + value]
except __HOLE__:
raise ValueError("invalid host source: %r" % value)
section.required = True
return value | KeyError | dataset/ETHPy150Open reddit/push/push/config.py/HostsConfig.valid_host_source |
7,310 | @register.filter
def intcomma(value, use_l10n=True):
"""
Converts an integer to a string containing commas every three digits.
For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
"""
if settings.USE_L10N and use_l10n:
try:
if not isinstance(value, float):
... | TypeError | dataset/ETHPy150Open crate-archive/crate-site/crateweb/apps/jhumanize/helpers.py/intcomma |
7,311 | def is_numeric(x):
try:
int(x)
return True
except __HOLE__:
return False | ValueError | dataset/ETHPy150Open kootenpv/sky/sky/view/view.py/is_numeric |
7,312 | def _jump_to_in_window(self, filename, line_number=None, column_number=None, transient=False):
""" Opens a new window and jumps to declaration if possible
:param filename: string or int
:param line_number: int
:param column_number: int
:param transient: bool
... | AttributeError | dataset/ETHPy150Open srusskih/SublimeJEDI/sublime_jedi/go_to.py/BaseLookUpJediCommand._jump_to_in_window |
7,313 | def coerce_put_post(request):
"""
Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it.
Function fr... | AttributeError | dataset/ETHPy150Open benoitc/dj-revproxy/revproxy/util.py/coerce_put_post |
7,314 | def import_conn_manager(module):
parts = module.rsplit(":", 1)
if len(parts) == 1:
raise ImportError("can't import handler '%s'" % module)
module, obj = parts[0], parts[1]
try:
__import__(module)
except __HOLE__:
if module.endswith(".py") and os.path.exists(module):
... | ImportError | dataset/ETHPy150Open benoitc/dj-revproxy/revproxy/util.py/import_conn_manager |
7,315 | @classmethod
def _init_dependencies(cls):
global db
if db is not None:
return
try:
db = __import__('google.appengine.ext.db').appengine.ext.db
except __HOLE__:
raise InvalidCacheBackendError("Datastore cache backend requires the "
... | ImportError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/ext/google.py/GoogleNamespaceManager._init_dependencies |
7,316 | def do_open(self, flags, replace):
# If we already loaded the data, don't bother loading it again
if self.loaded:
self.flags = flags
return
item = self.cache.get_by_key_name(self.namespace)
if not item:
self._is_new = True
self.hash = {}
... | OSError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/ext/google.py/GoogleNamespaceManager.do_open |
7,317 | def authorize(self, username, password, hosting_url, *args, **kwargs):
"""Authorize the Review Board Gateway repository.
Review Board Gateway uses HTTP Basic Auth, so this will store the
provided password, encrypted, for use in later API requests.
Similar to GitLab's API, Review Board ... | HTTPError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/hostingsvcs/rbgateway.py/ReviewBoardGateway.authorize |
7,318 | def get_file(self, repository, path, revision, base_commit_id, *args,
**kwargs):
"""Get a file from ReviewBoardGateway.
This will perform an API request to fetch the contents of a file.
"""
url = self._get_file_url(repository, revision, base_commit_id, path)
tr... | HTTPError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/hostingsvcs/rbgateway.py/ReviewBoardGateway.get_file |
7,319 | def get_file_exists(self, repository, path, revision, base_commit_id,
*args, **kwargs):
"""Check whether a file exists in ReviewBoardGateway.
This will perform an API request to fetch the meta_data of a file.
"""
url = self._get_file_url(repository, revision, bas... | HTTPError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/hostingsvcs/rbgateway.py/ReviewBoardGateway.get_file_exists |
7,320 | def _api_get(self, url):
"""Make a GET request to the Review Board Gateway API.
Delegate to the client's http_get function but first add a
PRIVATE-TOKEN in the header for authentication.
"""
try:
data, headers = self.client.http_get(
url,
... | HTTPError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/hostingsvcs/rbgateway.py/ReviewBoardGateway._api_get |
7,321 | def _api_head(self, url):
"""Make a HEAD request to the Review Board Gateway API.
Delegate to the client's http_request function using the method
HEAD but first add a PRIVATE-TOKEN in the header for authentication.
"""
try:
data, headers = self.client.http_request(
... | HTTPError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/hostingsvcs/rbgateway.py/ReviewBoardGateway._api_head |
7,322 | def _cast_to_float(self, value):
try:
return float(value)
except (__HOLE__, ValueError):
raise TypeError("Non-numerical value: %r" % value) | TypeError | dataset/ETHPy150Open openstack/rally/rally/common/streaming_algorithms.py/StreamingAlgorithm._cast_to_float |
7,323 | @positional(1)
def get_package_for_module(module):
"""Get package name for a module.
Helper calculates the package name of a module.
Args:
module: Module to get name for. If module is a string, try to find
module in sys.modules.
Returns:
If module contains 'package' attribute, uses that as pac... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/protorpc/protorpc/util.py/get_package_for_module |
7,324 | def ModularIntegerFactory(_mod, _dom, _sym, parent):
"""Create custom class for specific integer modulus."""
try:
_mod = _dom.convert(_mod)
except CoercionFailed:
ok = False
else:
ok = True
if not ok or _mod < 1:
raise ValueError("modulus must be a positive integer, ... | KeyError | dataset/ETHPy150Open sympy/sympy/sympy/polys/domains/modularinteger.py/ModularIntegerFactory |
7,325 | def has_capability(self, *args):
caps = self.capabilities
try:
for arg in args:
caps = caps[arg]
# If only part of a capability path is specified, we don't want
# to evaluate to True just because it has contents. We want to
# only say we ... | KeyError | dataset/ETHPy150Open reviewboard/rbtools/rbtools/api/capabilities.py/Capabilities.has_capability |
7,326 | def _ensure_is_connected(self):
if not self._is_connected:
try:
port = int(self.settings_dict['PORT'])
except __HOLE__:
raise ImproperlyConfigured("PORT must be an integer")
self.db_name = self.settings_dict['NAME']
self._connecti... | ValueError | dataset/ETHPy150Open aparo/django-elasticsearch/django_elasticsearch/base.py/DatabaseWrapper._ensure_is_connected |
7,327 | def process_body_row(linedict, filingnum, header_id, is_amended, cd, filer_id):
form = linedict['form_parser']
## Mark memo-ized rows as being superceded by an amendment.
try:
if linedict['memo_code']=='X':
linedict['superceded_by_amendment'] = True
except __HOLE__:
pass... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/formdata/utils/filing_body_processor_fix_hack.py/process_body_row |
7,328 | def process_filing_body(filingnum, fp=None, logger=None):
#It's useful to pass the form parser in when running in bulk so we don't have to keep creating new ones.
if not fp:
fp = form_parser()
if not logger:
logger=fec_logger()
msg = "process_filing_body: Starting # %s" %... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/formdata/utils/filing_body_processor_fix_hack.py/process_filing_body |
7,329 | def test_notifymail(self):
utils.subscribe(self.user2_settings, self.TEST_KEY)
utils.subscribe(self.user1_settings, self.TEST_KEY)
utils.notify("This notification goes out by mail!", self.TEST_KEY)
call_command("notifymail", cron=True)
# No un-mailed notifications can be left!... | SystemExit | dataset/ETHPy150Open benjaoming/django-nyt/django_nyt/tests/test_management.py/CommandTest.test_notifymail |
7,330 | @classmethod
def detect_process(cls, headers):
"""Returns tuple of process, legacy or None, None if not process originating."""
try:
if 'Libprocess-From' in headers:
return PID.from_string(headers['Libprocess-From']), False
elif 'User-Agent' in headers and headers['User-Agent'].startswith... | ValueError | dataset/ETHPy150Open wickman/compactor/compactor/httpd.py/WireProtocolMessageHandler.detect_process |
7,331 | def convert_code_to_value(M_c, cidx, code):
"""
For a column with categorical data, this function takes the 'code':
the integer used to represent a specific value, and returns the corresponding
raw value (e.g. 'Joe' or 234.23409), which is always encoded as a string.
Note that the underlying store ... | KeyError | dataset/ETHPy150Open probcomp/crosscat/src/utils/data_utils.py/convert_code_to_value |
7,332 | def get_can_cast_to_float(column_data):
can_cast = True
try:
[float(datum) for datum in column_data]
except __HOLE__ as e:
can_cast = False
return can_cast | ValueError | dataset/ETHPy150Open probcomp/crosscat/src/utils/data_utils.py/get_can_cast_to_float |
7,333 | def add(self, l, st, ptr):
try:
ctr = st[id(self)]
except __HOLE__:
ctr = st[id(self)] = 0
if ctr >= self.a and (self.b is None or ctr <= self.b):
st2 = st.copy()
count = st2.pop(id(self)) # record loop exit statistics and reset counter
... | KeyError | dataset/ETHPy150Open blackberry/ALF/alf/fuzz/grammr2_crack.py/_rstate.add |
7,334 | def _update(self, **data):
# at the moment, the timestamps seem to be naive so they have no time zone and operate on UTC time.
# we can use this to our advantage to use strptime instead of a complicated parsing routine.
# example timestamp: 2015-08-21T12:03:45.782000+00:00
# sometimes th... | AttributeError | dataset/ETHPy150Open Rapptz/discord.py/discord/message.py/Message._update |
7,335 | def run_and_read(view, cmd):
out, err = subprocess.Popen(['cmd.exe', '/c', cmd],
stdout=PIPE,
stderr=PIPE,
shell=True,
startupinfo=get_startup_info()).communicate()
try:
return... | AttributeError | dataset/ETHPy150Open guillermooo/Vintageous/ex/plat/windows.py/run_and_read |
7,336 | def _scrub(self, path):
"""Remove all tags from a file.
"""
for cls in self._mutagen_classes():
# Try opening the file with this type, but just skip in the
# event of any error.
try:
f = cls(util.syspath(path))
except Exception:
... | IOError | dataset/ETHPy150Open beetbox/beets/beetsplug/scrub.py/ScrubPlugin._scrub |
7,337 | def _scrub_item(self, item, restore=True):
"""Remove tags from an Item's associated file and, if `restore`
is enabled, write the database's tags back to the file.
"""
# Get album art if we need to restore it.
if restore:
try:
mf = mediafile.MediaFile(u... | IOError | dataset/ETHPy150Open beetbox/beets/beetsplug/scrub.py/ScrubPlugin._scrub_item |
7,338 | @cronjobs.register
def send_weekly_ready_for_review_digest():
"""Sends out the weekly "Ready for review" digest email."""
# If this is stage, do nothing.
if settings.STAGE:
return
@email_utils.safe_translation
def _send_mail(locale, user, context):
subject = _('[Reviews Pending: %s... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/kitsune/kitsune/wiki/cron.py/send_weekly_ready_for_review_digest |
7,339 | def testNaming4(self):
exc_raised = False
try:
values = ftest(1, c=2)
except __HOLE__, t:
exc_raised = True
self.assertTrue(exc_raised, "TypeError 'c' unexpected arg not raised") | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ArgsTest.py/ArgsTest.testNaming4 |
7,340 | def testNaming5(self):
exc_raised = False
try:
values = ftest()
except __HOLE__, t:
exc_raised = True
self.assertTrue(exc_raised, "TypeError 'ftest() takes exactly 2 arguments (0 given)' not raised") | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ArgsTest.py/ArgsTest.testNaming5 |
7,341 | def testStarArgs(self):
args = (1,2)
res = aArgs(*args)
self.assertEquals(args, res)
args = "123"
try:
res = aArgs(*args)
called = True
exc = None
except TypeError, e:
called = False
exc = e
# weird one... | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ArgsTest.py/ArgsTest.testStarArgs |
7,342 | def testKwArgsRecurse(self):
kwa = kw_args(x=5, y=6)
if kwa:
self.assertEquals(kwa.get('x'), 5)
self.assertEquals(kwa.get('y'), 6)
kwa = kw_args2(x=5, y=6)
if kwa:
self.assertEquals(kwa.get('x'), 5)
self.assertEquals(kwa.get('y'), 6)
... | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ArgsTest.py/ArgsTest.testKwArgsRecurse |
7,343 | def testGetattr(self):
instance = ArgsTestClass()
foo = instance.foo
values = foo(1, 2, 3)
self.assertEquals(values[0], 1)
self.assertEquals(values[1], 2)
self.assertEquals(values[2], 3)
values = foo(*(1, 2, 3))
self.assertEquals(values[0], 1)
se... | TypeError | dataset/ETHPy150Open pyjs/pyjs/examples/libtest/ArgsTest.py/ArgsTest.testGetattr |
7,344 | @classmethod
def _create(cls, *args, **kwargs):
branched_from = kwargs.get('branched_from')
initiator = kwargs.get('initiator')
registration_schema = kwargs.get('registration_schema')
registration_metadata = kwargs.get('registration_metadata')
if not branched_from:
... | IndexError | dataset/ETHPy150Open CenterForOpenScience/osf.io/tests/factories.py/DraftRegistrationFactory._create |
7,345 | def ReadManifest(jar_file_name):
"""Read and parse the manifest out of the given jar.
Args:
jar_file_name: the name of the jar from which the manifest is to be read.
Returns:
A parsed Manifest object, or None if the jar has no manifest.
Raises:
IOError: if the jar does not exist or cannot be read... | KeyError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/jarfile.py/ReadManifest |
7,346 | def _ParseManifestSection(section, jar_file_name):
"""Parse a dict out of the given manifest section string.
Args:
section: a str or unicode that is the manifest section. It looks something
like this (without the >):
> Name: section-name
> Some-Attribute: some value
> Another-Attribute:... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/jarfile.py/_ParseManifestSection |
7,347 | def extractor(self, fname):
fname = os.path.abspath(fname)
outfile = os.path.splitext(fname)[0]
try:
fpout = open(outfile, "wb")
gz = gzip.GzipFile(fname, "rb")
while True:
data = gz.read(self.BLOCK_SIZE)
if data:
... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/plugins/gzipextract.py/GzipExtractPlugin.extractor |
7,348 | @staticmethod
def validate (obj):
import foam.events
ev = foam.events.Event
try:
getattr(ev, obj)
return True
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/foam/types/trigger_type.py/TriggerType.validate |
7,349 | def run():
"""Thin wrapper for main() that catches KeyboardInterrupts."""
try:
main()
except __HOLE__:
print("Stopped by user.") | KeyboardInterrupt | dataset/ETHPy150Open earwig/git-repo-updater/gitup/script.py/run |
7,350 | def snake_case_dict(_dict):
raw_dict = _dict.copy()
result = {}
try:
while 1:
key, value = raw_dict.popitem()
result[snake_case(key)] = value
except __HOLE__:
return result | KeyError | dataset/ETHPy150Open puentesarrin/asyncflux/asyncflux/util.py/snake_case_dict |
7,351 | def test_long_integers(self):
if 12L + 24L != 36L: self.fail('long op')
if 12L + (-24L) != -12L: self.fail('long op')
if (-12L) + 24L != 12L: self.fail('long op')
if (-12L) + (-24L) != -36L: self.fail('long op')
if not 12L < 24L: self.fail('long op')
if not -24L < -12L: s... | ValueError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_types.py/TypesTests.test_long_integers |
7,352 | @unittest.skipIf(is_jython, "No buffer on Jython")
def test_buffers(self):
self.assertRaises(ValueError, buffer, 'asdf', -1)
cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1
self.assertRaises(TypeError, buffer, None)
a = buffer('asdf... | TypeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_types.py/TypesTests.test_buffers |
7,353 | def __eq__(self, o):
try:
return self.id == o.id and self.cls == o.cls and self.attrs == o.attrs
except __HOLE__:
return False | AttributeError | dataset/ETHPy150Open skyostil/tracy/src/analyzer/Trace.py/Object.__eq__ |
7,354 | @celery_app.task(name='scripts.refresh_box_tokens')
def run_main(days=None, dry_run=True):
init_app(set_backends=True, routes=False)
try:
days = int(days)
except (ValueError, __HOLE__):
days = 60 - 7 # refresh tokens that expire this week
delta = relativedelta(days=days)
if not dry_... | TypeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/scripts/refresh_box_tokens.py/run_main |
7,355 | def verify_node_settings_document(document, provider):
try:
assert('_id' in document)
assert('{}_list_id'.format(provider) in document)
except __HOLE__:
return False
return True | AssertionError | dataset/ETHPy150Open CenterForOpenScience/osf.io/scripts/migration/migrate_citation_addons_list_id.py/verify_node_settings_document |
7,356 | def _executeQuery(self, command, args=None):
"""execute the provided command on the database.
args are specified as a dictionary. error checking on the
results is performed here and the returned value is a list of
lists with each list representing a row of the returned table.
"... | TypeError | dataset/ETHPy150Open CGATOxford/cgat/CGAT/CBioPortal.py/CBioPortal._executeQuery |
7,357 | def _RetrieveURL(self, url, payload, method, headers, request, response,
follow_redirects=True, deadline=_API_CALL_DEADLINE):
"""Retrieves a URL.
Args:
url: String containing the URL to access.
payload: Request payload to send, if any; None if no payload.
method: HTTP metho... | IOError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/api/urlfetch_stub.py/URLFetchServiceStub._RetrieveURL |
7,358 | def from_map(self, schema, inobjs, newdb):
"""Initalize the dictionary of types by converting the input map
:param schema: schema owning the types
:param inobjs: YAML map defining the schema objects
:param newdb: collection of dictionaries defining the database
"""
for k... | KeyError | dataset/ETHPy150Open perseas/Pyrseas/pyrseas/dbobject/dbtype.py/TypeDict.from_map |
7,359 | def __getitem__(self, name):
"Returns a BoundField with the given name."
try:
field = self.fields[name]
except __HOLE__:
raise KeyError('Key %r not found in Form' % name)
return BoundField(self, field, name) | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/forms/forms.py/BaseForm.__getitem__ |
7,360 | def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
value = field.widg... | ValidationError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/forms/forms.py/BaseForm._clean_fields |
7,361 | def _clean_form(self):
try:
self.cleaned_data = self.clean()
except __HOLE__, e:
self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages) | ValidationError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/forms/forms.py/BaseForm._clean_form |
7,362 | def mps2_set_board_image_file(self, disk, images_cfg_path, image0file_path, image_name='images.txt'):
""" This function will alter image cfg file
@details Main goal of this function is to change number of images to 1, comment all
existing image entries and append at the end of file new... | IOError | dataset/ETHPy150Open ARMmbed/htrun/mbed_host_tests/host_tests_plugins/module_copy_mps2.py/HostTestPluginCopyMethod_MPS2.mps2_set_board_image_file |
7,363 | @must_be_valid_project # injects project
@must_have_permission('write')
@must_not_be_registration
def project_add_tag(auth, node, **kwargs):
data = request.get_json()
tag = data['tag']
if tag:
try:
node.add_tag(tag=tag, auth=auth)
return {'status': 'success'}, http.CREATED
... | ValidationError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/project/views/tag.py/project_add_tag |
7,364 | def __init__(self, imagePath):
try:
self.image = Image.open(imagePath)
except __HOLE__:
print 'Could not open image. Are you sure you entered the correct path?\n'
sys.exit(-1)
self.image = self.image.resize((_HEIGHT, _WIDTH),Image.BILINEAR)
self.image = self.image.convert("L") # conver... | IOError | dataset/ETHPy150Open the-xkcd-community/the-red-spider-project/src/randomascii.py/AsciiGenerator.__init__ |
7,365 | def __str__(self):
asciiString = ''
for height in xrange(0, self.image.size[1]):
for width in xrange(0, self.image.size[0]):
lum = 255 - self.image.getpixel((width, height))
row = bisect(zonebounds, lum)
try:
possibles = greyscale[row]
except __HOLE__:
con... | IndexError | dataset/ETHPy150Open the-xkcd-community/the-red-spider-project/src/randomascii.py/AsciiGenerator.__str__ |
7,366 | def load_module(self, fullname):
if fullname in sys.modules:
return self
extname = fullname.split(self.prefix)[1]
module = self.find_module_for_extension(extname)
realname = module.__name__
try:
__import__(realname)
except __HOLE__:
rai... | ImportError | dataset/ETHPy150Open pecan/pecan/pecan/extensions.py/PecanExtensionImporter.load_module |
7,367 | @weblab_api.route_webclient('/locales.json')
def locales():
lang = request.args.get('lang')
if not lang:
# Default language is English
lang = 'en'
try:
babel.Locale.parse(lang)
except (babel.core.UnknownLocaleError, __HOLE__) as e:
# Avoid storing fake languages
... | ValueError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/weblab/core/webclient/view_i18n.py/locales |
7,368 | @staticmethod
def are_concurrent(*lines):
"""Is a sequence of linear entities concurrent?
Two or more linear entities are concurrent if they all
intersect at a single point.
Parameters
==========
lines : a sequence of linear entities.
Returns
=====... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/line.py/LinearEntity.are_concurrent |
7,369 | def is_parallel(l1, l2):
"""Are two linear entities parallel?
Parameters
==========
l1 : LinearEntity
l2 : LinearEntity
Returns
=======
True : if l1 and l2 are parallel,
False : otherwise.
See Also
========
coefficient... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/line.py/LinearEntity.is_parallel |
7,370 | def is_perpendicular(l1, l2):
"""Are two linear entities perpendicular?
Parameters
==========
l1 : LinearEntity
l2 : LinearEntity
Returns
=======
True : if l1 and l2 are perpendicular,
False : otherwise.
See Also
========
... | AttributeError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/line.py/LinearEntity.is_perpendicular |
7,371 | def __new__(cls, p1, pt=None, slope=None, **kwargs):
if isinstance(p1, LinearEntity):
p1, pt = p1.args
else:
p1 = Point(p1)
if pt is not None and slope is None:
try:
p2 = Point(pt)
except __HOLE__:
raise ValueError('... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/line.py/Line.__new__ |
7,372 | def __new__(cls, p1, pt=None, angle=None, **kwargs):
p1 = Point(p1)
if pt is not None and angle is None:
try:
p2 = Point(pt)
except __HOLE__:
from sympy.utilities.misc import filldedent
raise ValueError(filldedent('''
... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/geometry/line.py/Ray.__new__ |
7,373 | @description(valediction="OK!")
def _choose_new_hosts(self):
def get_connection_name(conn, number):
name = self._get_sa_connection_name(conn)
return '%s (#%d)' % (name, number)
def get_connections_names():
return (', '.join(get_connection_name(c, i) for i, c in e... | ValueError | dataset/ETHPy150Open Crystalnix/serverauditor-sshconfig/serverauditor_sshconfig/sa_import.py/ImportSSHConfigApplication._choose_new_hosts |
7,374 | def main():
app = ImportSSHConfigApplication(api=API(), ssh_config=SSHConfig(), cryptor=RNCryptor(), logger=PrettyLogger())
try:
app.run()
except (__HOLE__, EOFError):
sys.exit(1)
return | KeyboardInterrupt | dataset/ETHPy150Open Crystalnix/serverauditor-sshconfig/serverauditor_sshconfig/sa_import.py/main |
7,375 | @error_handler
def execute_query(request, design_id=None):
response = {'status': -1, 'message': ''}
if request.method != 'POST':
response['message'] = _('A POST request is required.')
app_name = get_app_name(request)
query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name]
design = safe_get_desi... | RuntimeError | dataset/ETHPy150Open cloudera/hue/apps/rdbms/src/rdbms/api.py/execute_query |
7,376 | @error_handler
def explain_query(request):
response = {'status': -1, 'message': ''}
if request.method != 'POST':
response['message'] = _('A POST request is required.')
app_name = get_app_name(request)
query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name]
try:
form = get_query_form(reques... | RuntimeError | dataset/ETHPy150Open cloudera/hue/apps/rdbms/src/rdbms/api.py/explain_query |
7,377 | @error_handler
def save_query(request, design_id=None):
response = {'status': -1, 'message': ''}
if request.method != 'POST':
response['message'] = _('A POST request is required.')
app_name = get_app_name(request)
query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name]
design = safe_get_design(re... | RuntimeError | dataset/ETHPy150Open cloudera/hue/apps/rdbms/src/rdbms/api.py/save_query |
7,378 | def application_json(self):
'''Handler for application/json media-type'''
self.decode_body()
try:
pybody = json.loads(self.body)
except __HOLE__:
pybody = self.body
return pybody | ValueError | dataset/ETHPy150Open jpaugh/agithub/agithub/base.py/ResponseBody.application_json |
7,379 | @classmethod
def OpenFileSystem(cls, path_spec, resolver_context=None):
"""Opens a file system object defined by path specification.
Args:
path_spec: the path specification (instance of PathSpec).
resolver_context: the optional resolver context (instance of
resolver.Contex... | ValueError | dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/resolver/resolver.py/Resolver.OpenFileSystem |
7,380 | def _osUrandom(self, nbytes):
"""
Wrapper around C{os.urandom} that cleanly manage its absence.
"""
try:
return os.urandom(nbytes)
except (AttributeError, __HOLE__), e:
raise SourceNotAvailable(e) | NotImplementedError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/python/randbytes.py/RandomFactory._osUrandom |
7,381 | def _match(self, pattern, string):
"""Same as :func:`re.match`, except the regex is compiled and cached,
then reused on subsequent matches with the same pattern."""
try:
compiled = self._compiled[pattern]
except __HOLE__:
compiled = self._compiled[pattern] = re.co... | KeyError | dataset/ETHPy150Open celery/kombu/kombu/transport/virtual/exchange.py/TopicExchange._match |
7,382 | def get_controller(equipment, logfile=None):
try:
del os.environ["TERM"]
except __HOLE__:
pass
ssh = sshlib.get_ssh(equipment["hostname"], equipment["user"],
equipment["password"], prompt=equipment["prompt"],
logfile=logfile)
ctor = ShellController(ssh)
ctor.h... | KeyError | dataset/ETHPy150Open kdart/pycopia/QA/pycopia/QA/ssh_controller.py/get_controller |
7,383 | def get_next_sibling(self):
if hasattr(self, '_parent'):
if self._parent:
siblings = list(self._parent.get_children())
else:
siblings = [self]
try:
return siblings[siblings.index(self) + 1]
except __HOLE__:
... | IndexError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/models/base.py/Node.get_next_sibling |
7,384 | @staticmethod
def fetch_content_instances(nodes):
"""
Given a list of nodes, efficiently get all of their content instances.
The structure returned looks like this::
{
content_type_id: {
content_id: content_instance,
conte... | AttributeError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/models/base.py/Node.fetch_content_instances |
7,385 | @property
def node(self):
"""
Settable property used by Node.prefetch_tree to optimize tree
rendering
"""
if hasattr(self, '_node'):
return self._node
try:
return self._nodes.all()[0]
except __HOLE__:
raise Node.DoesNotExist | IndexError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/models/base.py/Content.node |
7,386 | @classmethod
def get_templates_hierarchy(cls, **kwargs):
templates = kwargs.get('hierarchy', (
'widgy/{app_label}/{model_name}/{template_name}{extension}',
'widgy/{app_label}/{template_name}{extension}',
'widgy/{template_name}{extension}',
))
kwargs.setdef... | AttributeError | dataset/ETHPy150Open fusionbox/django-widgy/widgy/models/base.py/Content.get_templates_hierarchy |
7,387 | def xxinv(mul):
""" Y * X * X.I -> Y """
factor, matrices = mul.as_coeff_matrices()
for i, (X, Y) in enumerate(zip(matrices[:-1], matrices[1:])):
try:
if X.is_square and Y.is_square and X == Y.inverse():
I = Identity(X.rows)
return newmul(factor, *(matrice... | ValueError | dataset/ETHPy150Open sympy/sympy/sympy/matrices/expressions/matmul.py/xxinv |
7,388 | def _readable(self, watcher, events):
"""Called by the pyev watcher (self.read_watcher) whenever the socket
is readable.
This means either the socket has been closed or there is a new
client connection waiting.
"""
protocol = self.factory.build(self.loop)
try... | IOError | dataset/ETHPy150Open bfrog/whizzer/whizzer/server.py/SocketServer._readable |
7,389 | def _groupby_function(name, alias, npfunc, numeric_only=True,
_convert=False):
_local_template = "Compute %(f)s of group values"
@Substitution(name='groupby', f=name)
@Appender(_doc_template)
@Appender(_local_template)
def f(self):
self._set_selection_from_grouper()
... | AssertionError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/_groupby_function |
7,390 | def _get_indices(self, names):
"""
safe get multiple indices, translate keys for
datelike to underlying repr
"""
def get_converter(s):
# possibly convert to the actual key types
# in the indices, could be a Timestamp or a np.datetime64
if isin... | KeyError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/_GroupBy._get_indices |
7,391 | def _cython_transform(self, how, numeric_only=True):
output = {}
for name, obj in self._iterate_slices():
is_numeric = is_numeric_dtype(obj.dtype)
if numeric_only and not is_numeric:
continue
try:
result, names = self.grouper.transform... | AssertionError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/_GroupBy._cython_transform |
7,392 | def _cython_agg_general(self, how, numeric_only=True):
output = {}
for name, obj in self._iterate_slices():
is_numeric = is_numeric_dtype(obj.dtype)
if numeric_only and not is_numeric:
continue
try:
result, names = self.grouper.aggrega... | AssertionError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/_GroupBy._cython_agg_general |
7,393 | def _python_agg_general(self, func, *args, **kwargs):
func = self._is_builtin_func(func)
f = lambda x: func(x, *args, **kwargs)
# iterate through "columns" ex exclusions to populate output dict
output = {}
for name, obj in self._iterate_slices():
try:
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/_GroupBy._python_agg_general |
7,394 | def _cython_operation(self, kind, values, how, axis):
assert kind in ['transform', 'aggregate']
arity = self._cython_arity.get(how, 1)
vdim = values.ndim
swapped = False
if vdim == 1:
values = values[:, None]
out_shape = (self.ngroups, arity)
els... | NotImplementedError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/BaseGrouper._cython_operation |
7,395 | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a Series excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
func : function
To apply to each group. Should return... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/SeriesGroupBy.filter |
7,396 | def nunique(self, dropna=True):
""" Returns number of unique elements in the group """
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except __HOLE__: # catches object dtypes
assert val.dtype == objec... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/SeriesGroupBy.nunique |
7,397 | def _aggregate_item_by_item(self, func, *args, **kwargs):
# only for axis==0
obj = self._obj_with_exclusions
result = {}
cannot_agg = []
errors = None
for item in obj:
try:
data = obj[item]
colg = SeriesGroupBy(data, selection=... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/NDFrameGroupBy._aggregate_item_by_item |
7,398 | def _wrap_applied_output(self, keys, values, not_indexed_same=False):
from pandas.core.index import _all_indexes_same
if len(keys) == 0:
# XXX
return DataFrame({})
key_names = self.grouper.names
if isinstance(values[0], DataFrame):
return self._conc... | AttributeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/NDFrameGroupBy._wrap_applied_output |
7,399 | def _transform_general(self, func, *args, **kwargs):
from pandas.tools.merge import concat
applied = []
obj = self._obj_with_exclusions
gen = self.grouper.get_iterator(obj, axis=self.axis)
fast_path, slow_path = self._define_paths(func, *args, **kwargs)
path = None
... | TypeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/NDFrameGroupBy._transform_general |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.