Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
7,400 | def filter(self, func, dropna=True, *args, **kwargs): # noqa
"""
Return a copy of a DataFrame excluding elements from groups that
do not satisfy the boolean criterion specified by func.
Parameters
----------
f : function
Function to apply to each subframe. S... | AttributeError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/NDFrameGroupBy.filter |
7,401 | def _aggregate_item_by_item(self, func, *args, **kwargs):
obj = self._obj_with_exclusions
result = {}
if self.axis > 0:
for item in obj:
try:
itemg = DataFrameGroupBy(obj[item],
axis=self.axis - 1,
... | ValueError | dataset/ETHPy150Open pydata/pandas/pandas/core/groupby.py/PanelGroupBy._aggregate_item_by_item |
7,402 | def post(self, route, data, headers=HEADERS):
result = self.fetch("/%s" % route, method = "POST",
body = json.dumps(data), headers=headers).body
try:
return json.loads(result)
except __HOLE__:
raise ValueError(result) | ValueError | dataset/ETHPy150Open sihrc/tornado-boilerplate/indico/tests/testutils/server.py/ServerTest.post |
7,403 | def vertebral_detection(fname, fname_seg, init_disc, verbose, laplacian=0):
shift_AP = 32 # shift the centerline towards the spine (in voxel).
size_AP = 11 # window size in AP direction (=y) (in voxel)
size_RL = 1 # window size in RL direction (=x) (in voxel)
size_IS = 19 # window size in IS direct... | ValueError | dataset/ETHPy150Open neuropoly/spinalcordtoolbox/scripts/sct_label_vertebrae.py/vertebral_detection |
7,404 | def setUp(self):
try:
djangorunner.DjangoRunner()
except __HOLE__:
raise unittest.SkipTest("Django is not installed")
saved_stdout = sys.stdout
self.stream = StringIO()
sys.stdout = self.stream
self.addCleanup(setattr, sys, 'stdout', saved_stdout) | ImportError | dataset/ETHPy150Open CleanCut/green/green/test/test_djangorunner.py/TestDjangoRunner.setUp |
7,405 | def handle(self, *args, **options):
if len(args) != 1:
raise CommandError('Incorrect arguments')
try:
with open(args[0]) as f:
data = json.load(f)
except __HOLE__ as exc:
raise CommandError("Malformed JSON: %s" % exc.message)
def slo... | ValueError | dataset/ETHPy150Open openstack-infra/odsreg/scheduling/management/commands/loadslots.py/Command.handle |
7,406 | def __getattr__(self, key):
try:
return self.__kwargs[key]
except __HOLE__:
raise AttributeError(key)
# Have to provide __setstate__ to avoid
# infinite recursion since we override
# __getattr__. | KeyError | dataset/ETHPy150Open mongodb/mongo-python-driver/bson/dbref.py/DBRef.__getattr__ |
7,407 | @staticmethod
def _make_db(updates):
try:
resource_provider = updates.pop('resource_provider')
updates['resource_provider_id'] = resource_provider.id
except (KeyError, NotImplementedError):
raise exception.ObjectActionError(
action='create',
... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/objects/resource_provider.py/_HasAResourceProvider._make_db |
7,408 | def _get_dci_id_and_proj_name(self, proj_name):
# dci_id can be embedded in the partition name, name:dci_id:27
dciid_key = ':dci_id:'
try:
dci_index = proj_name.index(dciid_key)
except __HOLE__:
# There is no dci_id in the project name
return proj_name... | ValueError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/DfaServer._get_dci_id_and_proj_name |
7,409 | def _get_segmentation_id(self, segid):
"""Allocate segmentation id."""
try:
newseg = (segid, self.segmentation_pool.remove(segid)
if segid and segid in self.segmentation_pool else
self.segmentation_pool.pop())
return newseg[0] if newse... | KeyError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/DfaServer._get_segmentation_id |
7,410 | def network_create_event(self, network_info):
"""Process network create event.
Save the network inforamtion in the database.
"""
net = network_info['network']
net_id = net['id']
self.network[net_id] = {}
self.network[net_id].update(net)
net_name = net.ge... | TypeError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/DfaServer.network_create_event |
7,411 | def _get_ip_leases(self):
if not self.cfg.dcnm.dcnm_dhcp_leases:
LOG.debug('DHCP lease file is not defined.')
return
try:
ssh_session = paramiko.SSHClient()
ssh_session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_session.connect(s... | IOError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/DfaServer._get_ip_leases |
7,412 | def save_my_pid(cfg):
mypid = os.getpid()
pid_path = cfg.dfa_log.pid_dir
pid_file = cfg.dfa_log.pid_server_file
if pid_path and pid_file:
try:
if not os.path.exists(pid_path):
os.makedirs(pid_path)
except __HOLE__:
LOG.error(_LE('Fail to create %s... | OSError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/save_my_pid |
7,413 | def dfa_server():
try:
cfg = config.CiscoDFAConfig().cfg
logging.setup_logger('dfa_enabler', cfg)
dfa = DfaServer(cfg)
save_my_pid(cfg)
dfa.create_threads()
while True:
time.sleep(constants.MAIN_INTERVAL)
if dfa.dcnm_dhcp:
dfa.u... | KeyboardInterrupt | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/apps/saf/server/dfa_server.py/dfa_server |
7,414 | def test_iterator_pickling(self):
testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1),
(13, 21, 3), (-2, 2, 2), (2**65, 2**65+2)]
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
for t in testcases:
it = itorg = iter(range(*t))
data = list... | StopIteration | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_range.py/RangeTest.test_iterator_pickling |
7,415 | def test_lock(self):
with FileLock(self.tmpfile, "r+w"):
try:
fcntl.flock(self.tmpfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
assert False, "Flock should have failed"
except __HOLE__:
pass | IOError | dataset/ETHPy150Open khamidou/kite/src/back/tests/test_lockfile.py/TestLockfile.test_lock |
7,416 | def __getattr__(self, attr):
from .browser_integration import warning
try:
return getattr(self.webdriver, attr)
except __HOLE__ as e:
raise e
except Exception as e:
warning(str(e)) | AttributeError | dataset/ETHPy150Open apiad/sublime-browser-integration/browser.py/Browser.__getattr__ |
7,417 | def parse_profile_html(html):
'''Parses a user profile page into the data fields and essays.
It turns out parsing HTML, with all its escaped characters, and handling
wacky unicode characters, and writing them all out to a CSV file (later),
is a pain in the ass because everything that is not ASCII goes ... | KeyError | dataset/ETHPy150Open everett-wetchler/okcupid/FetchProfiles.py/parse_profile_html |
7,418 | def read_usernames(filename):
'''Extracts usernames from the given file, returning a sorted list.
The file should either be:
1) A list of usernames, one per line
2) A CSV file with a 'username' column (specified in its header line)
'''
try:
rows = [r for r in csv.reader(open(fil... | ValueError | dataset/ETHPy150Open everett-wetchler/okcupid/FetchProfiles.py/read_usernames |
7,419 | def check_exists(fips_dir) :
try :
subprocess.check_output(['ccache', '--version'])
return True
except (__HOLE__, subprocess.CalledProcessError):
return False | OSError | dataset/ETHPy150Open floooh/fips/mod/tools/ccache.py/check_exists |
7,420 | def main(argv): # pragma: no cover
ip = "127.0.0.1"
port = 5683
try:
opts, args = getopt.getopt(argv, "hi:p:", ["ip=", "port="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
usage()
sys.exit()
el... | KeyboardInterrupt | dataset/ETHPy150Open Tanganelli/CoAPthon/plugtest_coapserver.py/main |
7,421 | def _get_version_output(self):
"""
Ignoring errors, call `ceph --version` and return only the version
portion of the output. For example, output like::
ceph version 9.0.1-1234kjd (asdflkj2k3jh234jhg)
Would return::
9.0.1-1234kjd
"""
if not self.... | IndexError | dataset/ETHPy150Open ceph/ceph-deploy/ceph_deploy/util/packages.py/Ceph._get_version_output |
7,422 | def _patched_convertTmplPathToModuleName(tmplPath):
try:
return splitdrive(tmplPath)[1].translate(_unitrans)
except (UnicodeError, __HOLE__):
return unicode(splitdrive(tmplPath)[1]).translate(_unitrans) # pylint: disable=E0602 | TypeError | dataset/ETHPy150Open ohmu/poni/poni/template.py/_patched_convertTmplPathToModuleName |
7,423 | def render_genshi(source_text, source_path, variables):
assert genshi, "Genshi is not installed"
if source_path:
source = open(source_path)
else:
source = StringIO(source_text)
try:
tmpl = genshi.template.MarkupTemplate(source, filepath=source_path)
stream = tmpl.generate... | IOError | dataset/ETHPy150Open ohmu/poni/poni/template.py/render_genshi |
7,424 | def main():
(options, args_, parser_) = simple_options(_parser, __version__, __dependencies__)
try:
with open(options.input) as xml_file:
xml_string = xml_file.read()
# At the moment there doesn't seem to be an obvious way to extract the xmlns from the asset.
# For ... | IOError | dataset/ETHPy150Open turbulenz/turbulenz_tools/turbulenz_tools/tools/xml2json.py/main |
7,425 | def _faa_di_bruno_partitions(n):
""" Return all non-negative integer solutions of the diophantine equation::
n*k_n + ... + 2*k_2 + 1*k_1 = n (1)
Parameters
----------
n: int
the r.h.s. of Eq. (1)
Returns
-------
partitions: a list of solutions of (1). Each solution i... | KeyError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/distributions/edgeworth.py/_faa_di_bruno_partitions |
7,426 | def _split_auth_string(auth_string):
""" split a digest auth string into individual key=value strings """
prev = None
for item in auth_string.split(","):
try:
if prev.count('"') == 1:
prev = "%s,%s" % (prev, item)
continue
except __HOLE__:
... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/auth/digest.py/_split_auth_string |
7,427 | def add_pending(self, f):
# Ignore symlinks
if os.path.islink(f):
return
# Get the file mode to check and see if it's a block/char device
try:
file_mode = os.stat(f).st_mode
except __HOLE__ as e:
return
# Only add this to the pending ... | OSError | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.add_pending |
7,428 | def callback(self, r):
# Make sure the file attribute is set to a compatible instance of binwalk.core.common.BlockFile
try:
r.file.size
except __HOLE__ as e:
pass
except Exception as e:
return
if not r.size:
size = r.file.size - r.... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.callback |
7,429 | def add_rule(self, txtrule=None, regex=None, extension=None, cmd=None, codes=[0, None], recurse=True):
'''
Adds a set of rules to the extraction rule list.
@txtrule - Rule string, or list of rule strings, in the format <regular expression>:<file extension>[:<command to run>]
@regex ... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.add_rule |
7,430 | def load_from_file(self, fname):
'''
Loads extraction rules from the specified file.
@fname - Path to the extraction rule file.
Returns None.
'''
try:
# Process each line from the extract file, ignoring comments
with open(fname, 'r') as f:
... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.load_from_file |
7,431 | def load_defaults(self):
'''
Loads default extraction rules from the user and system extract.conf files.
Returns None.
'''
# Load the user extract file first to ensure its rules take precedence.
extract_files = [
self.config.settings.user.extract,
... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.load_defaults |
7,432 | def build_output_directory(self, path):
'''
Set the output directory for extracted files.
@path - The path to the file that data will be extracted from.
Returns None.
'''
# If we have not already created an output directory for this target file, create one now
i... | IndexError | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.build_output_directory |
7,433 | def extract(self, offset, description, file_name, size, name=None):
'''
Extract an embedded file from the target file, if it matches an extract rule.
Called automatically by Binwalk.scan().
@offset - Offset inside the target file to begin the extraction.
@description - Desc... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.extract |
7,434 | def _parse_rule(self, rule):
'''
Parses an extraction rule.
@rule - Rule string.
Returns an array of ['<case insensitive matching string>', '<file extension>', '<command to run>', '<comma separated return codes>', <recurse into extracted directories: True|False>].
'''
v... | ValueError | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor._parse_rule |
7,435 | def _dd(self, file_name, offset, size, extension, output_file_name=None):
'''
Extracts a file embedded inside the target file.
@file_name - Path to the target file.
@offset - Offset inside the target file where the embedded file begins.
@size - Numbe... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor._dd |
7,436 | def execute(self, cmd, fname, codes=[0, None]):
'''
Execute a command against the specified file.
@cmd - Command to execute.
@fname - File to run command against.
@codes - List of return codes indicating cmd success.
Returns True on success, False on failure, or None ... | KeyboardInterrupt | dataset/ETHPy150Open devttys0/binwalk/src/binwalk/modules/extractor.py/Extractor.execute |
7,437 | def smisk_mvc_metadata(conf):
'''This config filter configures the underlying Elixir
and SQLAlchemy modules.
'''
global log
conf = conf.get('smisk.mvc.model')
if not conf:
return
# Aquire required parameter "url"
try:
url = conf['url']
except __HOLE__:
log.war... | KeyError | dataset/ETHPy150Open rsms/smisk/lib/smisk/mvc/model.py/smisk_mvc_metadata |
7,438 | def build_spider_registry(config):
SPIDER_REGISTRY.clear()
opt_modules = []
opt_modules = config['global'].get('spider_modules', [])
for path in opt_modules:
if ':' in path:
path, cls_name = path.split(':')
else:
cls_name = None
try:
mod = __... | ImportError | dataset/ETHPy150Open lorien/grab/grab/util/module.py/build_spider_registry |
7,439 | def _get_size(self):
try:
return self._size
except AttributeError:
try:
self._size = self.file.size
except __HOLE__:
self._size = len(self.file.getvalue())
return self._size | AttributeError | dataset/ETHPy150Open benoitbryon/django-downloadview/django_downloadview/files.py/VirtualFile._get_size |
7,440 | @property
def request(self):
try:
return self._request
except __HOLE__:
self._request = self.request_factory(self.url,
**self.request_kwargs)
return self._request | AttributeError | dataset/ETHPy150Open benoitbryon/django-downloadview/django_downloadview/files.py/HTTPFile.request |
7,441 | @property
def file(self):
try:
return self._file
except __HOLE__:
content = self.request.iter_content(decode_unicode=False)
self._file = BytesIteratorIO(content)
return self._file | AttributeError | dataset/ETHPy150Open benoitbryon/django-downloadview/django_downloadview/files.py/HTTPFile.file |
7,442 | def __getattribute__(self, name):
try:
return super(PersistentData, self).__getattribute__(name)
except __HOLE__, err:
typ, default = self.__class__._ATTRS.get(name, (None, None))
if typ is not None:
return default
raise | AttributeError | dataset/ETHPy150Open kdart/pycopia/storage/pycopia/durusplus/persistent_data.py/PersistentData.__getattribute__ |
7,443 | def _get_cache(self, name, constructor):
try:
return self.__dict__["_cache"][name]
except __HOLE__:
obj = constructor()
self.__dict__["_cache"][name] = obj
return obj | KeyError | dataset/ETHPy150Open kdart/pycopia/storage/pycopia/durusplus/persistent_data.py/PersistentData._get_cache |
7,444 | def _del_cache(self, name, destructor=None):
try:
obj = self.__dict__["_cache"].pop(name)
except __HOLE__:
return
else:
if destructor:
destructor(obj) | KeyError | dataset/ETHPy150Open kdart/pycopia/storage/pycopia/durusplus/persistent_data.py/PersistentData._del_cache |
7,445 | @classmethod
def clean_status_file(cls):
"""
Removes JMX status files
"""
try:
os.remove(os.path.join(cls._get_dir(), cls._STATUS_FILE))
except OSError:
pass
try:
os.remove(os.path.join(cls._get_dir(), cls._PYTHON_STATUS_FILE))
... | OSError | dataset/ETHPy150Open serverdensity/sd-agent/utils/jmx.py/JMXFiles.clean_status_file |
7,446 | @classmethod
def clean_exit_file(cls):
"""
Remove exit file trigger -may not exist-.
Note: Windows only
"""
try:
os.remove(os.path.join(cls._get_dir(), cls._JMX_EXIT_FILE))
except __HOLE__:
pass | OSError | dataset/ETHPy150Open serverdensity/sd-agent/utils/jmx.py/JMXFiles.clean_exit_file |
7,447 | def paintContent(self, target):
"""Paints any needed component-specific things to the given UIDL
stream.
@see: L{AbstractComponent.paintContent}
"""
self._initialPaint = False
if self._partialUpdate:
target.addAttribute('partialUpdate', True)
tar... | StopIteration | dataset/ETHPy150Open rwl/muntjac/muntjac/ui/tree.py/Tree.paintContent |
7,448 | def getVisibleItemIds(self):
"""Gets the visible item ids.
@see: L{Select.getVisibleItemIds}
"""
visible = list()
# Iterates trough hierarchical tree using a stack of iterators
iteratorStack = deque()
ids = self.rootItemIds()
if ids is not None:
... | StopIteration | dataset/ETHPy150Open rwl/muntjac/muntjac/ui/tree.py/Tree.getVisibleItemIds |
7,449 | def clean(self, value):
from .us_states import STATES_NORMALIZED
super(USStateField, self).clean(value)
if value in EMPTY_VALUES:
return ''
try:
value = value.strip().lower()
except __HOLE__:
pass
else:
try:
... | AttributeError | dataset/ETHPy150Open django/django-localflavor/localflavor/us/forms.py/USStateField.clean |
7,450 | def __get__(self, instance, instance_type=None):
if instance is None:
return self
try:
return getattr(instance, self.cache_attr)
except __HOLE__:
rel_obj = None
# Make sure to use ContentType.objects.get_for_id() to ensure that
# look... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/contenttypes/generic.py/GenericForeignKey.__get__ |
7,451 | def create_generic_related_manager(superclass):
"""
Factory function for a manager that subclasses 'superclass' (which is a
Manager) and adds behavior for generic related objects.
"""
class GenericRelatedObjectManager(superclass):
def __init__(self, model=None, instance=None, symmetrical=No... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/contenttypes/generic.py/create_generic_related_manager |
7,452 | def get_formatter(format):
"""Returns the formatter for the given format"""
try:
return _FORMATTERS_REGISTER[format]
except __HOLE__:
raise RuntimeError('No formatter registered for format "%s"' % format) | KeyError | dataset/ETHPy150Open fiam/wapi/formatters/__init__.py/get_formatter |
7,453 | def getid(obj):
"""Return id if argument is a Resource.
Abstracts the common pattern of allowing both an object or an object's ID
(UUID) as a parameter when dealing with relationships.
"""
try:
if obj.uuid:
return obj.uuid
except __HOLE__:
pass
try:
retur... | AttributeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/base.py/getid |
7,454 | def _list(self, url, response_key=None, obj_class=None, json=None):
"""List the collection.
:param url: a partial URL, e.g., '/servers'
:param response_key: the key to be looked up in response dictionary,
e.g., 'servers'. If response_key is None - all response body
will ... | TypeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/base.py/BaseManager._list |
7,455 | def findall(self, **kwargs):
"""Find all items with attributes matching ``**kwargs``.
This isn't very efficient: it loads the entire list then filters on
the Python side.
"""
found = []
searches = kwargs.items()
for obj in self.list():
try:
... | AttributeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/base.py/ManagerWithFind.findall |
7,456 | def _parse_extension_module(self):
self.manager_class = None
for attr_name, attr_value in self.module.__dict__.items():
if attr_name in self.SUPPORTED_HOOKS:
self.add_hook(attr_name, attr_value)
else:
try:
if issubclass(attr_val... | TypeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/base.py/Extension._parse_extension_module |
7,457 | def _add_details(self, info):
for (k, v) in six.iteritems(info):
try:
setattr(self, k, v)
self._info[k] = v
except __HOLE__:
# In this case we already defined the attribute on the class
pass | AttributeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/openstack/common/apiclient/base.py/Resource._add_details |
7,458 | def __init__(self):
cmd.Cmd.__init__(self)
self.logged_in = threading.Event()
self.logged_out = threading.Event()
self.logged_out.set()
self.session = spotify.Session()
self.session.on(
spotify.SessionEvent.CONNECTION_STATE_UPDATED,
self.on_conne... | ImportError | dataset/ETHPy150Open mopidy/pyspotify/examples/shell.py/Commander.__init__ |
7,459 | def do_play_uri(self, line):
"play <spotify track uri>"
if not self.logged_in.is_set():
self.logger.warning('You must be logged in to play')
return
try:
track = self.session.get_track(line)
track.load()
except (__HOLE__, spotify.Error) as e... | ValueError | dataset/ETHPy150Open mopidy/pyspotify/examples/shell.py/Commander.do_play_uri |
7,460 | def reset(self):
codecs.StreamReader.reset(self)
try:
del self.decode
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/encodings/utf_16.py/StreamReader.reset |
7,461 | def get_status(self, xmlresult, xml):
"""Gets the status code of T1 XML.
If code is valid, returns None; otherwise raises the appropriate Error.
"""
status = xmlresult.find('status')
if status is None:
raise T1Error(None, xml)
status_code = status.attrib['cod... | KeyError | dataset/ETHPy150Open MediaMath/t1-python/terminalone/xmlparser.py/XMLParser.get_status |
7,462 | def main(sysargs=None):
from bloom.config import upconvert_bloom_to_config_branch
upconvert_bloom_to_config_branch()
parser = get_argument_parser()
parser = add_global_arguments(parser)
args = parser.parse_args(sysargs)
handle_global_arguments(args)
# Check that the current directory is a ... | SystemExit | dataset/ETHPy150Open ros-infrastructure/bloom/bloom/commands/git/import_upstream.py/main |
7,463 | def __init__(self, module):
self.host = module.params["host"]
self.user = module.params["user"]
self.password = module.params["password"]
self.state = module.params["state"]
try:
self.payload = json.loads(module.params.get("payload"))
except __HOLE__:
self.payload = ''
self.resou... | TypeError | dataset/ETHPy150Open F5Networks/aws-deployments/src/f5_aws/test/manual_bigip_config.py/BigipConfig.__init__ |
7,464 | def http(self, method, host, payload=''):
print 'HTTP %s %s: %s' % (method, host, payload)
methodfn = getattr(requests, method.lower(), None)
if method is None:
raise NotImplementedError("requests module has not method %s " % method)
try:
if payload != '':
request = methodfn(url='%s/... | HTTPError | dataset/ETHPy150Open F5Networks/aws-deployments/src/f5_aws/test/manual_bigip_config.py/BigipConfig.http |
7,465 | def peek_last(self):
try:
return self[0]
except __HOLE__:
return None | IndexError | dataset/ETHPy150Open wiliamsouza/hystrix-py/hystrix/rolling_number.py/BucketCircular.peek_last |
7,466 | def _read_metadata(self):
"""Read metadata for current frame and return as dict"""
try:
tags = self.im.tag_v2 # for Pillow >= v3.0.0
except AttributeError:
tags = self.im.tag # for Pillow < v3.0.0
md = {}
try:
md["ImageDescription"] = tags[27... | KeyError | dataset/ETHPy150Open soft-matter/pims/pims/tiff_stack.py/TiffStack_pil._read_metadata |
7,467 | def __init__(self, filename = "", sid_params = {}, force_read_timestamp = False):
"""Two ways to create a SIDfile:
1) A file already exists and you want to read it: use 'filename'
2) A new empty file needs to be created: use 'sid_params'
to indicate the parameters of the file's heade... | IOError | dataset/ETHPy150Open ericgibert/supersid/supersid/sidfile.py/SidFile.__init__ |
7,468 | def read_timestamp_format(self):
"""Check the timestamp found on the first line to deduce the timestamp format"""
first_data_line = self.lines[self.headerNbLines].split(",")
if ':' in first_data_line[0]: # yes, a time stamp is found in the first data column
try:
datet... | ValueError | dataset/ETHPy150Open ericgibert/supersid/supersid/sidfile.py/SidFile.read_timestamp_format |
7,469 | @classmethod
def _StringToDatetime(cls, strTimestamp):
if type(strTimestamp) is not str: # i.e. byte array in Python 3
strTimestamp = strTimestamp.decode('utf-8')
try:
dts = datetime.strptime(strTimestamp, SidFile._timestamp_format)
except __HOLE__: # try the other fo... | ValueError | dataset/ETHPy150Open ericgibert/supersid/supersid/sidfile.py/SidFile._StringToDatetime |
7,470 | def get_station_data(self, stationId):
"""Return the numpy array of the given station's data"""
try:
idx = self.get_station_index(stationId)
return self.data[idx]
except __HOLE__:
return [] | ValueError | dataset/ETHPy150Open ericgibert/supersid/supersid/sidfile.py/SidFile.get_station_data |
7,471 | def copy_data(self, second_sidfile):
"""Copy the second_sidfile's data on the current data vector for every common stations.
If a copy is done then the timestamps are also copied."""
has_copied = False
for iStation, station in enumerate(self.stations):
try:
... | ValueError | dataset/ETHPy150Open ericgibert/supersid/supersid/sidfile.py/SidFile.copy_data |
7,472 | def __delitem__(self, k):
"""
C{del dirdbm[foo]}
Delete a file in this directory.
@type k: str
@param k: key to delete
@raise KeyError: Raised when there is no such key
"""
assert type(k) == types.StringType, "DirDBM key must be a string"... | OSError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/persisted/dirdbm.py/DirDBM.__delitem__ |
7,473 | def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not hasattr(self.transaction, '__call__')):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = D... | KeyError | dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/Templates/SkeletonPage.py/SkeletonPage.respond |
7,474 | def deepcopy(x):
"""Deep copy operation on gyp objects such as strings, ints, dicts
and lists. More than twice as fast as copy.deepcopy but much less
generic."""
try:
return _deepcopy_dispatch[type(x)](x)
except __HOLE__:
raise Error('Unsupported type %s for deepcopy. Use copy.deepcopy ' +
... | KeyError | dataset/ETHPy150Open adblockplus/gyp/pylib/gyp/simple_copy.py/deepcopy |
7,475 | def softspace(file, newvalue):
oldvalue = 0
try:
oldvalue = file.softspace
except AttributeError:
pass
try:
file.softspace = newvalue
except (__HOLE__, TypeError):
# "attribute-less object" or "read-only attributes"
pass
return oldvalue | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/code.py/softspace |
7,476 | def runsource(self, source, filename="<input>", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or Overflow... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/code.py/InteractiveInterpreter.runsource |
7,477 | def runcode(self, code):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to
display a traceback. All exceptions are caught except
SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur
elsewhere in thi... | SystemExit | dataset/ETHPy150Open babble/babble/include/jython/Lib/code.py/InteractiveInterpreter.runcode |
7,478 | def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the cur... | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/code.py/InteractiveConsole.interact |
7,479 | def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
... | ImportError | dataset/ETHPy150Open babble/babble/include/jython/Lib/code.py/interact |
7,480 | def __getitem__(self, key):
key = key.lower()
try:
return self.base_data_types_reverse[key]
except __HOLE__:
size = get_field_size(key)
if size is not None:
return ('CharField', {'max_length': size})
raise KeyError | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/db/backends/sqlite3/introspection.py/FlexibleFieldLookupDict.__getitem__ |
7,481 | def create_driver_settings(self, machine, pulse_ms=None, **kwargs):
return_dict = dict()
if pulse_ms is None:
pulse_ms = machine.config['mpf']['default_pulse_ms']
try:
return_dict['allow_enable'] = kwargs['allow_enable']
except __HOLE__:
return_dict['... | KeyError | dataset/ETHPy150Open missionpinball/mpf/mpf/platform/fast.py/FASTDriver.create_driver_settings |
7,482 | def update(self, data):
try:
self.dmd_frame = bytearray(data)
except __HOLE__:
pass | TypeError | dataset/ETHPy150Open missionpinball/mpf/mpf/platform/fast.py/FASTDMD.update |
7,483 | def identify_connection(self):
"""Identifies which processor this serial connection is talking to."""
# keep looping and wait for an ID response
msg = ''
while True:
self.platform.log.debug("Sending 'ID:' command to port '%s'",
self.seri... | ValueError | dataset/ETHPy150Open missionpinball/mpf/mpf/platform/fast.py/SerialCommunicator.identify_connection |
7,484 | def _to_arrays(*args):
nargs = []
single = True
for a, ndim in args:
try:
arg = np.array(a, copy=False)
except __HOLE__:
# Typically end up in here when list of Shapely geometries is
# passed in as input.
arrays = [np.array(el, copy=False) for ... | TypeError | dataset/ETHPy150Open jwass/geog/geog/geog.py/_to_arrays |
7,485 | def getFileByFileId(self, fileId, justPresent = True):
cu = self.db.cursor()
if justPresent:
cu.execute("SELECT path, stream FROM DBTroveFiles "
"WHERE fileId=? AND isPresent = 1", fileId)
else:
cu.execute("SELECT path, stream FROM DBTroveFiles "
... | StopIteration | dataset/ETHPy150Open sassoftware/conary/conary/local/sqldb.py/DBTroveFiles.getFileByFileId |
7,486 | def getId(self, theId, justPresent = True):
cu = self.db.cursor()
if justPresent:
pres = "AND isPresent=1"
else:
pres = ""
cu.execute("SELECT troveName, versionId, flavorId, isPresent "
"FROM Instances WHERE instanceId=? %s" % pres, theId)
... | StopIteration | dataset/ETHPy150Open sassoftware/conary/conary/local/sqldb.py/DBInstanceTable.getId |
7,487 | def __getitem__(self, item):
cu = self.db.cursor()
cu.execute("SELECT instanceId FROM Instances WHERE "
"troveName=? AND versionId=? AND flavorId=?",
item)
try:
return cu.next()[0]
except __HOLE__:
raise KeyError, item | StopIteration | dataset/ETHPy150Open sassoftware/conary/conary/local/sqldb.py/DBInstanceTable.__getitem__ |
7,488 | def getVersion(self, instanceId):
cu = self.db.cursor()
cu.execute("""SELECT version, timeStamps FROM Instances
INNER JOIN Versions ON
Instances.versionId = Versions.versionId
WHERE instanceId=?""", instanceId)
try:
... | StopIteration | dataset/ETHPy150Open sassoftware/conary/conary/local/sqldb.py/DBInstanceTable.getVersion |
7,489 | def _getTransactionCounter(self, field):
"""Get transaction counter
Return (Boolean, value) with boolean being True if the counter was
found in the table"""
if 'DatabaseAttributes' not in self.db.tables:
# We should already have converted the schema to have the table in
... | StopIteration | dataset/ETHPy150Open sassoftware/conary/conary/local/sqldb.py/Database._getTransactionCounter |
7,490 | def __getattr__(self, key):
try:
return self[key]
except __HOLE__, k:
if self.has_key('_default'):
return self['_default']
else:
raise AttributeError, k | KeyError | dataset/ETHPy150Open FooBarWidget/mizuho/asciidoc/a2x.py/AttrDict.__getattr__ |
7,491 | def __delattr__(self, key):
try: del self[key]
except __HOLE__, k: raise AttributeError, k | KeyError | dataset/ETHPy150Open FooBarWidget/mizuho/asciidoc/a2x.py/AttrDict.__delattr__ |
7,492 | def shell(cmd, raise_error=True):
'''
Execute command cmd in shell and return tuple
(stdoutdata, stderrdata, returncode).
If raise_error is True then a non-zero return terminates the application.
'''
if os.name == 'nt':
# TODO: this is probably unnecessary, see:
# http://groups.g... | OSError | dataset/ETHPy150Open FooBarWidget/mizuho/asciidoc/a2x.py/shell |
7,493 | def prompt_option(text, choices, default=NO_DEFAULT):
""" Prompt the user to choose one of a list of options """
while True:
for i, msg in enumerate(choices):
print "[%d] %s" % (i + 1, msg)
response = prompt(text, default=default)
try:
idx = int(response) - 1
... | IndexError | dataset/ETHPy150Open mathcamp/pypicloud/pypicloud/scripts.py/prompt_option |
7,494 | def __getitem__(self, key):
try:
return self._clsmap[key]
except (__HOLE__, e):
if not self.initialized:
self._mutex.acquire()
try:
if not self.initialized:
self._init()
self.initi... | KeyError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/cache.py/_backends.__getitem__ |
7,495 | def _init(self):
try:
import pkg_resources
# Load up the additional entry point defined backends
for entry_point in pkg_resources.iter_entry_points('beaker.backends'):
try:
namespace_manager = entry_point.load()
name = ... | ImportError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/cache.py/_backends._init |
7,496 | def __init__(self, namespace, type='memory', expiretime=None,
starttime=None, expire=None, **nsargs):
try:
cls = clsmap[type]
if isinstance(cls, InvalidCacheBackendError):
raise cls
except __HOLE__:
raise TypeError("Unknown cache imple... | KeyError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/cache.py/Cache.__init__ |
7,497 | @classmethod
def _get_cache(cls, namespace, kw):
key = namespace + str(kw)
try:
return cache_managers[key]
except __HOLE__:
cache_managers[key] = cache = cls(namespace, **kw)
return cache | KeyError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/beaker/cache.py/Cache._get_cache |
7,498 | def authenticate(self, user, password):
""" Method to get simplenote auth token
Arguments:
- user (string): simplenote email address
- password (string): simplenote password
Returns:
Simplenote API token as string
"""
auth_params = "emai... | IOError | dataset/ETHPy150Open cpbotha/nvpy/nvpy/simplenote.py/Simplenote.authenticate |
7,499 | def get_note(self, noteid):
""" method to get a specific note
Arguments:
- noteid (string): ID of the note to get
Returns:
A tuple `(note, status)`
- note (dict): note object
- status (int): 0 on sucesss and -1 otherwise
"""
# r... | IOError | dataset/ETHPy150Open cpbotha/nvpy/nvpy/simplenote.py/Simplenote.get_note |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.