Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
6,400 | def user_data(self, token, *args, **kwargs):
"""Loads user data from service"""
url = 'https://api.digitalocean.com/v2/account'
auth_header = {"Authorization": "Bearer %s" % token}
try:
return self.get_json(url, headers=auth_header)
except __HOLE__:
return... | ValueError | dataset/ETHPy150Open omab/python-social-auth/social/backends/digitalocean.py/DigitalOceanOAuth.user_data |
6,401 | def delegator(self, images):
"""
Receive all images, check them and send them to the worker thread.
"""
delegatorlist = []
for fullpath in images:
try: # recompress images already in the list
image = (i.image for i in self.imagelist
... | StopIteration | dataset/ETHPy150Open Kilian/Trimage/src/trimage/trimage.py/StartQT4.delegator |
6,402 | def safe_call(self, command):
""" cross-platform command-line check """
while True:
try:
return call(command, shell=True, stdout=PIPE)
except __HOLE__, e:
if e.errno == errno.EINTR:
continue
else:
... | OSError | dataset/ETHPy150Open Kilian/Trimage/src/trimage/trimage.py/StartQT4.safe_call |
6,403 | def __init__(self, opts, remote, per_remote_defaults,
override_params, cache_root, role='gitfs'):
self.opts = opts
self.role = role
self.env_blacklist = self.opts.get(
'{0}_env_blacklist'.format(self.role), [])
self.env_whitelist = self.opts.get(
... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitProvider.__init__ |
6,404 | def clear_lock(self, lock_type='update'):
'''
Clear update.lk
'''
lock_file = self._get_lock_file(lock_type=lock_type)
def _add_error(errlist, exc):
msg = ('Unable to remove update lock for {0} ({1}): {2} '
.format(self.url, lock_file, exc))
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitProvider.clear_lock |
6,405 | def _lock(self, lock_type='update', failhard=False):
'''
Place a lock file if (and only if) it does not already exist.
'''
try:
fh_ = os.open(self._get_lock_file(lock_type),
os.O_CREAT | os.O_EXCL | os.O_WRONLY)
with os.fdopen(fh_, 'w'):
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitProvider._lock |
6,406 | @contextlib.contextmanager
def gen_lock(self, lock_type='update'):
'''
Set and automatically clear a lock
'''
lock_set = False
try:
self._lock(lock_type=lock_type, failhard=True)
lock_set = True
yield
except (OSError, __HOLE__, GitL... | IOError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitProvider.gen_lock |
6,407 | def get_url(self):
'''
Examine self.id and assign self.url (and self.branch, for git_pillar)
'''
if self.role in ('git_pillar', 'winrepo'):
# With winrepo and git_pillar, the remote is specified in the
# format '<branch> <url>', so that we can get a unique identif... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitProvider.get_url |
6,408 | def dir_list(self, tgt_env):
'''
Get list of directories for the target environment using GitPython
'''
ret = set()
tree = self.get_tree(tgt_env)
if not tree:
return ret
if self.root:
try:
tree = tree / self.root
... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitPython.dir_list |
6,409 | def _fetch(self):
'''
Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
'''
origin = self.repo.remotes[0]
try:
fetch_results = origin.fetch()
except __HOLE__:
fetch_results =... | AssertionError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitPython._fetch |
6,410 | def file_list(self, tgt_env):
'''
Get file list for the target environment using GitPython
'''
files = set()
symlinks = {}
tree = self.get_tree(tgt_env)
if not tree:
# Not found, return empty objects
return files, symlinks
if self.r... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitPython.file_list |
6,411 | def find_file(self, path, tgt_env):
'''
Find the specified file in the specified environment
'''
tree = self.get_tree(tgt_env)
if not tree:
# Branch/tag/SHA not found
return None, None
blob = None
depth = 0
while True:
d... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitPython.find_file |
6,412 | def checkout(self):
'''
Checkout the configured branch/tag
'''
local_ref = 'refs/heads/' + self.branch
remote_ref = 'refs/remotes/origin/' + self.branch
tag_ref = 'refs/tags/' + self.branch
try:
local_head = self.repo.lookup_reference('HEAD')
... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.checkout |
6,413 | def clean_stale_refs(self, local_refs=None): # pylint: disable=arguments-differ
'''
Clean stale local refs so they don't appear as fileserver environments
'''
if self.credentials is not None:
log.debug(
'pygit2 does not support detecting stale refs for '
... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.clean_stale_refs |
6,414 | def init_remote(self):
'''
Initialize/attach to a remote using pygit2. Return a boolean which
will let the calling function know whether or not a new repo was
initialized by this function.
'''
new = False
if not os.listdir(self.cachedir):
# Repo cached... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.init_remote |
6,415 | def dir_list(self, tgt_env):
'''
Get a list of directories for the target environment using pygit2
'''
def _traverse(tree, blobs, prefix):
'''
Traverse through a pygit2 Tree object recursively, accumulating all
the empty directories within it in the "b... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.dir_list |
6,416 | def _fetch(self):
'''
Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
'''
origin = self.repo.remotes[0]
refs_pre = self.repo.listall_references()
fetch_kwargs = {}
if self.credentials is n... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2._fetch |
6,417 | def file_list(self, tgt_env):
'''
Get file list for the target environment using pygit2
'''
def _traverse(tree, blobs, prefix):
'''
Traverse through a pygit2 Tree object recursively, accumulating all
the file paths and symlink info in the "blobs" dict
... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.file_list |
6,418 | def find_file(self, path, tgt_env):
'''
Find the specified file in the specified environment
'''
tree = self.get_tree(tgt_env)
if not tree:
# Branch/tag/SHA not found in repo
return None, None
blob = None
depth = 0
while True:
... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.find_file |
6,419 | def get_tree(self, tgt_env):
'''
Return a pygit2.Tree object if the branch/tag/SHA is found, otherwise
None
'''
if tgt_env == 'base':
tgt_ref = self.base
else:
tgt_ref = tgt_env
for ref in self.repo.listall_references():
_, rtyp... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Pygit2.get_tree |
6,420 | def dir_list(self, tgt_env):
'''
Get a list of directories for the target environment using dulwich
'''
def _traverse(tree, blobs, prefix):
'''
Traverse through a dulwich Tree object recursively, accumulating
all the empty directories within it in the ... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.dir_list |
6,421 | def _fetch(self):
'''
Fetch the repo. If the local copy was updated, return True. If the
local copy was already up-to-date, return False.
'''
# origin is just a url here, there is no origin object
origin = self.url
client, path = \
dulwich.client.get_t... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich._fetch |
6,422 | def file_list(self, tgt_env):
'''
Get file list for the target environment using dulwich
'''
def _traverse(tree, blobs, prefix):
'''
Traverse through a dulwich Tree object recursively, accumulating
all the file paths and symlinks info in the "blobs" di... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.file_list |
6,423 | def find_file(self, path, tgt_env):
'''
Find the specified file in the specified environment
'''
tree = self.get_tree(tgt_env)
if not tree:
# Branch/tag/SHA not found
return None, None
blob = None
depth = 0
while True:
d... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.find_file |
6,424 | def get_tree(self, tgt_env):
'''
Return a dulwich.objects.Tree object if the branch/tag/SHA is found,
otherwise None
'''
if tgt_env == 'base':
tgt_ref = self.base
else:
tgt_ref = tgt_env
refs = self.repo.get_refs()
# Sorting ensures... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.get_tree |
6,425 | def init_remote(self):
'''
Initialize/attach to a remote using dulwich. Return a boolean which
will let the calling function know whether or not a new repo was
initialized by this function.
'''
if self.url.startswith('ssh://'):
# Dulwich will throw an error if... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.init_remote |
6,426 | def walk_tree(self, tree, path):
'''
Dulwich does not provide a means of directly accessing subdirectories.
This function will walk down to the directory specified by 'path', and
return a Tree object at that path. If path is an empty string, the
original tree will be returned, an... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/Dulwich.walk_tree |
6,427 | def clear_old_remotes(self):
'''
Remove cache directories for remotes no longer configured
'''
try:
cachedir_ls = os.listdir(self.cache_root)
except OSError:
cachedir_ls = []
# Remove actively-used remotes from list
for repo in self.remotes... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.clear_old_remotes |
6,428 | def clear_cache(self):
'''
Completely clear cache
'''
errors = []
for rdir in (self.cache_root, self.file_list_cachedir):
if os.path.exists(rdir):
try:
shutil.rmtree(rdir)
except __HOLE__ as exc:
... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.clear_cache |
6,429 | def clear_lock(self, remote=None, lock_type='update'):
'''
Clear update.lk for all remotes
'''
cleared = []
errors = []
for repo in self.remotes:
if remote:
# Specific remote URL/pattern was passed, ensure that the URL
# matches... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.clear_lock |
6,430 | def lock(self, remote=None):
'''
Place an update.lk
'''
locked = []
errors = []
for repo in self.remotes:
if remote:
# Specific remote URL/pattern was passed, ensure that the URL
# matches or else skip this one
t... | TypeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.lock |
6,431 | def update(self):
'''
Execute a git fetch on all of the repos and perform maintenance on the
fileserver cache.
'''
# data for the fileserver event
data = {'changed': False,
'backend': 'gitfs'}
data['changed'] = self.clear_old_remotes()
if ... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.update |
6,432 | def get_provider(self):
'''
Determine which provider to use
'''
if 'verified_{0}_provider'.format(self.role) in self.opts:
self.provider = self.opts['verified_{0}_provider'.format(self.role)]
else:
desired_provider = self.opts.get('{0}_provider'.format(sel... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.get_provider |
6,433 | def write_remote_map(self):
'''
Write the remote_map.txt
'''
remote_map = os.path.join(self.cache_root, 'remote_map.txt')
try:
with salt.utils.fopen(remote_map, 'w+') as fp_:
timestamp = \
datetime.now().strftime('%d %b %Y %H:%M:%S.... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitBase.write_remote_map |
6,434 | def find_file(self, path, tgt_env='base', **kwargs): # pylint: disable=W0613
'''
Find the first file to match the path and ref, read the file out of git
and send the path to the newly cached file
'''
fnd = {'path': '',
'rel': ''}
if os.path.isabs(path) or ... | OSError | dataset/ETHPy150Open saltstack/salt/salt/utils/gitfs.py/GitFS.find_file |
6,435 | def DrawPaneButton(self, dc, window, button, button_state, rect, pane):
"""
Draws a pane button in the pane caption area.
:param `dc`: a :class:`DC` device context;
:param `window`: an instance of :class:`Window`;
:param integer `button`: the button to be drawn;
:param i... | TypeError | dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/wx/wx_upstream/aui/dockart.py/ModernDockArt.DrawPaneButton |
6,436 | def rosetta_csrf_token(parser, token):
try:
from django.template.defaulttags import csrf_token
return csrf_token(parser, token)
except __HOLE__:
return RosettaCsrfTokenPlaceholder() | ImportError | dataset/ETHPy150Open mbi/django-rosetta/rosetta/templatetags/rosetta.py/rosetta_csrf_token |
6,437 | def __init__(self):
self.creds_file = 'credentials.txt'
self.creds_fullpath = None
self.oauth = {}
try:
self.twitter_dir = os.environ['TWITTER']
self.creds_subdir = self.twitter_dir
except __HOLE__:
self.twitter_dir = None
self.cre... | KeyError | dataset/ETHPy150Open nltk/nltk/nltk/twitter/util.py/Authenticate.__init__ |
6,438 | def isDate(date_text):
try:
datetime.datetime.strptime(date_text, '%Y-%m-%d')
return True
except __HOLE__:
return False | ValueError | dataset/ETHPy150Open JeffHoogland/qutemtgstats/Code/PasteWindow.py/isDate |
6,439 | def testThemAll(self):
for entry in self.listOfTests:
output = entry[0]
exception = entry[1]
try:
args = entry[2]
except __HOLE__:
args = ()
try:
kwargs = entry[3]
except IndexError:
... | IndexError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/test/test_error.py/TestStringification.testThemAll |
6,440 | def open_config_file(config_file):
""" Opens a config file, logging common IOError exceptions.
"""
try:
return open(config_file)
except __HOLE__, e:
# This should only happen with the top level config file, since
# we use glob.glob on includes
if e.errno == 2:
... | IOError | dataset/ETHPy150Open cloudtools/nymms/nymms/config/yaml_config.py/open_config_file |
6,441 | def test_unique_for_date(self):
p1 = Post.objects.create(title="Django 1.0 is released",
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3))
try:
p.full_clean()
except... | ValidationError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/modeltests/validation/test_unique.py/PerformUniqueChecksTest.test_unique_for_date |
6,442 | def test_unique_for_date_with_nullable_date(self):
p1 = FlexibleDatePost.objects.create(title="Django 1.0 is released",
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
p = FlexibleDatePost(title="Django 1.0 is released")
try:
p.full_clean()
... | ValidationError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/modeltests/validation/test_unique.py/PerformUniqueChecksTest.test_unique_for_date_with_nullable_date |
6,443 | def __init__(self, container, service, entrypoint, args=None, kwargs=None,
data=None):
self.container = container
self.config = container.config # TODO: remove?
self.parent_calls_tracked = self.config.get(
PARENT_CALLS_CONFIG_KEY, DEFAULT_PARENT_CALLS_TRACKED)
... | IndexError | dataset/ETHPy150Open onefinestay/nameko/nameko/containers.py/WorkerContextBase.__init__ |
6,444 | def test_maps(self):
try:
maps = nis.maps()
except nis.error as msg:
# NIS is probably not active, so this test isn't useful
if support.verbose:
print("Test Skipped:", msg)
# Can't raise SkipTest as regrtest only recognizes the exception
... | ValueError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_nis.py/NisTests.test_maps |
6,445 | def main(self):
source = ogr.Open(self.args.input, False)
source_layer = source.GetLayer(0)
try:
shutil.rmtree(self.args.output)
except __HOLE__:
pass
driver = ogr.GetDriverByName('ESRI Shapefile')
dest = driver.CreateDataSource(self.args.output)... | OSError | dataset/ETHPy150Open onyxfish/ogrkit/ogrkit/utilities/difference.py/OGRDifference.main |
6,446 | def InstallPerfmonForService(serviceName, iniName, dllName = None):
# If no DLL name, look it up in the INI file name
if not dllName: # May be empty string!
dllName = win32api.GetProfileVal("Python", "dll", "", iniName)
# Still not found - look for the standard one in the same dir as win32servic... | AttributeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/InstallPerfmonForService |
6,447 | def InstallService(pythonClassString, serviceName, displayName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
# Handle the default arguments.
if startT... | NotImplementedError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/InstallService |
6,448 | def ChangeServiceConfig(pythonClassString, serviceName, startType = None, errorControl = None, bRunInteractive = 0, serviceDeps = None, userName = None, password = None, exeName = None, displayName = None, perfMonIni = None, perfMonDll = None, exeArgs = None, description = None):
# Before doing anything, remove an... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/ChangeServiceConfig |
6,449 | def SetServiceCustomOption(serviceName, option, value):
try:
serviceName = serviceName._svc_name_
except __HOLE__:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\%s\\Parameters" % serviceName)
try:
if type(value)==type(0... | AttributeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/SetServiceCustomOption |
6,450 | def GetServiceCustomOption(serviceName, option, defaultValue = None):
# First param may also be a service class/instance.
# This allows services to pass "self"
try:
serviceName = serviceName._svc_name_
except __HOLE__:
pass
key = win32api.RegCreateKey(win32con.HKEY_LOCAL_MACHI... | AttributeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/GetServiceCustomOption |
6,451 | def RemoveService(serviceName):
try:
import perfmon
perfmon.UnloadPerfCounterTextStrings("python.exe "+serviceName)
except (__HOLE__, win32api.error):
pass
hscm = win32service.OpenSCManager(None,None,win32service.SC_MANAGER_ALL_ACCESS)
try:
hs = SmartOpenService... | ImportError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/RemoveService |
6,452 | def HandleCommandLine(cls, serviceClassString = None, argv = None, customInstallOptions = "", customOptionHandler = None):
"""Utility function allowing services to process the command line.
Allows standard commands such as 'start', 'stop', 'debug', 'install' etc.
Install supports 'standard' command l... | AttributeError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/HandleCommandLine |
6,453 | def SvcOther(self, control):
try:
print "Unknown control status - %d" % control
except __HOLE__:
# services may not have a valid stdout!
pass | IOError | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/win32/lib/win32serviceutil.py/ServiceFramework.SvcOther |
6,454 | def get_global_variable_named(self, name):
try:
return self.globals[name]
except __HOLE__:
raise LLVMException(name) | KeyError | dataset/ETHPy150Open numba/llvmlite/llvmlite/llvmpy/core.py/Module.get_global_variable_named |
6,455 | def get_or_insert_named_metadata(self, name):
try:
return self.get_named_metadata(name)
except __HOLE__:
return self.add_named_metadata(name) | KeyError | dataset/ETHPy150Open numba/llvmlite/llvmlite/llvmpy/core.py/Module.get_or_insert_named_metadata |
6,456 | def postcommit_after_request(response, base_status_error_code=500):
if response.status_code >= base_status_error_code:
_local.postcommit_queue = set()
return response
try:
if settings.ENABLE_VARNISH and postcommit_queue():
import gevent
threads = [gevent.spawn(fun... | AttributeError | dataset/ETHPy150Open CenterForOpenScience/osf.io/framework/postcommit_tasks/handlers.py/postcommit_after_request |
6,457 | def main():
# Parse the command-line options.
parser = OptionParser()
parser.add_option(
"-v", "--verbosity",
action="store",
dest="verbosity",
default="1",
type="choice",
choices=["0", "1", "2", "3"],
help="Verbosity level; 0=minimal output, 1=normal ... | AttributeError | dataset/ETHPy150Open etianen/django-watson/src/tests/runtests.py/main |
6,458 | def load_tokens(email):
logger.debug('load_tokens')
try:
tokens = open('/tmp/resources/' + email, 'rU').read()
return tokens
except __HOLE__:
logger.exception('load_tokens')
return None | IOError | dataset/ETHPy150Open anantb/voicex/transport/google_voice/login.py/load_tokens |
6,459 | @property
def _api(self):
if not self._db_api:
with self._lock:
if not self._db_api:
db_api = api.DBAPI.from_config(
conf=self._conf, backend_mapping=self._backend_mapping)
if self._conf.database.use_tpool:
... | ImportError | dataset/ETHPy150Open openstack/oslo.db/oslo_db/concurrency.py/TpoolDbapiWrapper._api |
6,460 | def get(self, url, parameters={}):
response = self.client.get(url, parameters)
try:
rv = simplejson.loads(response.content)
return rv
except __HOLE__, e:
print response.content
raise | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/common/test/api.py/ApiIntegrationTest.get |
6,461 | def __contains__(self, key):
try:
value = self[key]
except __HOLE__:
return False
return True | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/test/utils.py/ContextList.__contains__ |
6,462 | def setup_test_template_loader(templates_dict, use_cached_loader=False):
"""
Changes Django to only find templates from within a dictionary (where each
key is the template name and each value is the corresponding template
content to return).
Use meth:`restore_template_loaders` to restore the origin... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/test/utils.py/setup_test_template_loader |
6,463 | def setsudo(self, user=None):
"""Set the subsequent API calls to the user provided
:param user: User id or username to change to, None to return to the logged user
:return: Nothing
"""
if user is None:
try:
self.headers.pop("SUDO")
except ... | KeyError | dataset/ETHPy150Open pyapi-gitlab/pyapi-gitlab/gitlab/__init__.py/Gitlab.setsudo |
6,464 | @register.tag
def membersof(parser, token):
"""
Given a collection and a content type, sets the results of :meth:`collection.members.with_model <.CollectionMemberManager.with_model>` as a variable in the context.
Usage::
{% membersof <collection> with <app_label>.<model_name> as <var> %}
"""
params=token.s... | ValueError | dataset/ETHPy150Open ithinksw/philo/philo/templatetags/collections.py/membersof |
6,465 | def close(self):
"""Close the consumer, waiting indefinitely for any needed cleanup."""
if self._closed:
return
log.debug("Closing the KafkaConsumer.")
self._closed = True
self._coordinator.close()
self._metrics.close()
self._client.close()
try... | AttributeError | dataset/ETHPy150Open dpkp/kafka-python/kafka/consumer/group.py/KafkaConsumer.close |
6,466 | def __next__(self):
if not self._iterator:
self._iterator = self._message_generator()
self._set_consumer_timeout()
try:
return next(self._iterator)
except __HOLE__:
self._iterator = None
raise | StopIteration | dataset/ETHPy150Open dpkp/kafka-python/kafka/consumer/group.py/KafkaConsumer.__next__ |
6,467 | def run(self):
spec = self.get_spec()
assert not spec.is_local()
if spec.is_url():
return self._run_url(spec)
data = self.get_meta(spec)
try:
chk = data['sha1']
except __HOLE__:
raise PgxnClientException(
"sha1 missin... | KeyError | dataset/ETHPy150Open dvarrazzo/pgxnclient/pgxnclient/commands/install.py/Download.run |
6,468 | def is_libdir_writable(self):
"""
Check if the Postgres installation directory is writable.
If it is, we will assume that sudo is not required to
install/uninstall the library, so the sudo program will not be invoked
or its specification will not be required.
"""
... | OSError | dataset/ETHPy150Open dvarrazzo/pgxnclient/pgxnclient/commands/install.py/SudoInstallUninstall.is_libdir_writable |
6,469 | def _get_extensions(self):
"""
Return a list of pairs (name, sql file) to be loaded/unloaded.
Items are in loading order.
"""
spec = self.get_spec()
dist = self.get_meta(spec)
if 'provides' not in dist:
# No 'provides' specified: assume a single exte... | KeyError | dataset/ETHPy150Open dvarrazzo/pgxnclient/pgxnclient/commands/install.py/LoadUnload._get_extensions |
6,470 | def execute_task(task, retries=0, handlers_map=None):
"""Execute mapper's executor task.
This will try to determine the correct mapper handler for the task, will set
up all mock environment necessary for task execution, and execute the task
itself.
This function can be used for functional-style testing of f... | TypeError | dataset/ETHPy150Open GoogleCloudPlatform/appengine-mapreduce/python/src/mapreduce/test_support.py/execute_task |
6,471 | def is_botocore():
try:
import botocore
return True
except ImportError:
if six.PY2:
try:
import boto
return False
except __HOLE__:
raise NotConfigured('missing botocore or boto library')
else:
rai... | ImportError | dataset/ETHPy150Open scrapy/scrapy/scrapy/utils/boto.py/is_botocore |
6,472 | def runtests(*test_args):
if not settings.configured:
settings.configure(**DEFAULT_SETTINGS)
# Compatibility with Django 1.7's stricter initialization
if hasattr(django, "setup"):
django.setup()
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
try... | ImportError | dataset/ETHPy150Open pinax/django-mailer/runtests.py/runtests |
6,473 | def init_app(self, app):
"""
Do setup that requires a Flask app.
"""
# register callback route and cookie-setting decorator
app.route('/oidc_callback')(self.oidc_callback)
app.after_request(self.after_request)
# load client_secrets.json
self.flow = flow_f... | KeyError | dataset/ETHPy150Open SteelPangolin/flask-oidc/flask_oidc/__init__.py/OpenIDConnect.init_app |
6,474 | def get_cookie_id_token(self):
try:
id_token_cookie = request.cookies[self.id_token_cookie_name]
return self.cookie_serializer.loads(id_token_cookie)
except (__HOLE__, SignatureExpired):
logger.debug("Missing or invalid ID token cookie", exc_info=True)
ret... | KeyError | dataset/ETHPy150Open SteelPangolin/flask-oidc/flask_oidc/__init__.py/OpenIDConnect.get_cookie_id_token |
6,475 | def authenticate_or_redirect(self):
"""
Helper function suitable for @app.before_request and @check (below).
Sets g.oidc_id_token to the ID token if the user has successfully
authenticated, else returns a redirect object so they can go try
to authenticate.
:return: A redi... | KeyError | dataset/ETHPy150Open SteelPangolin/flask-oidc/flask_oidc/__init__.py/OpenIDConnect.authenticate_or_redirect |
6,476 | def oidc_callback(self):
"""
Exchange the auth code for actual credentials,
then redirect to the originally requested page.
"""
# retrieve session and callback variables
try:
session_csrf_token = session.pop('oidc_csrf_token')
state = json.loads(r... | KeyError | dataset/ETHPy150Open SteelPangolin/flask-oidc/flask_oidc/__init__.py/OpenIDConnect.oidc_callback |
6,477 | def _verify_action(self, actions, type_, name, value):
try:
action = actions[0]
if action.cls_action_type != type_:
return "Action type error. send:%s, val:%s" \
% (type_, action.cls_action_type)
except IndexError:
return "Action is... | AttributeError | dataset/ETHPy150Open osrg/ryu/ryu/tests/integrated/test_add_flow_v10.py/RunTest._verify_action |
6,478 | def get_disk_statistics(self):
"""
Create a map of disks in the machine.
http://www.kernel.org/doc/Documentation/iostats.txt
Returns:
(major, minor) -> DiskStatistics(device, ...)
"""
result = {}
if os.access('/proc/diskstats', os.R_OK):
s... | ValueError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/diskusage/diskusage.py/DiskUsageCollector.get_disk_statistics |
6,479 | def get_callable(lookup_view, can_fail=False):
"""
Convert a string version of a function name to the callable object.
If the lookup_view is not an import path, it is assumed to be a URL pattern
label and the original string is returned.
If can_fail is True, lookup_view might be a URL pattern labe... | ImportError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/get_callable |
6,480 | def get_mod_func(callback):
# Converts 'django.views.news.stories.story_detail' to
# ['django.views.news.stories', 'story_detail']
try:
dot = callback.rindex('.')
except __HOLE__:
return callback, ''
return callback[:dot], callback[dot+1:] | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/get_mod_func |
6,481 | def _get_callback(self):
if self._callback is not None:
return self._callback
try:
self._callback = get_callable(self._callback_str)
except ImportError, e:
mod_name, _ = get_mod_func(self._callback_str)
raise ViewDoesNotExist, "Could not import %s.... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/RegexURLPattern._get_callback |
6,482 | def _get_urlconf_module(self):
try:
return self._urlconf_module
except __HOLE__:
self._urlconf_module = import_module(self.urlconf_name)
return self._urlconf_module | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/RegexURLResolver._get_urlconf_module |
6,483 | def _get_url_patterns(self):
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
try:
iter(patterns)
except __HOLE__:
raise ImproperlyConfigured("The included urlconf %s doesn't have any "
"patterns in it" % self.urlconf_name)
... | TypeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/RegexURLResolver._get_url_patterns |
6,484 | def _resolve_special(self, view_type):
callback = getattr(self.urlconf_module, 'handler%s' % view_type)
mod_name, func_name = get_mod_func(callback)
try:
return getattr(import_module(mod_name), func_name), {}
except (ImportError, __HOLE__), e:
raise ViewDoesNotExi... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/RegexURLResolver._resolve_special |
6,485 | def reverse(self, lookup_view, *args, **kwargs):
if args and kwargs:
raise ValueError("Don't mix *args and **kwargs in call to reverse()!")
try:
lookup_view = get_callable(lookup_view, True)
except (ImportError, __HOLE__), e:
raise NoReverseMatch("Error import... | AttributeError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/RegexURLResolver.reverse |
6,486 | def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
resolver = get_resolver(urlconf)
args = args or []
kwargs = kwargs or {}
if prefix is None:
prefix = get_script_prefix()
if not isinstance(viewname, basestring):
view = viewname
else:
... | KeyError | dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/core/urlresolvers.py/reverse |
6,487 | def do_transform(self):
"""Apply the transformation (if it exists) to the latest_value"""
if not self.transform:
return
try:
self.latest_value = utils.Transform(
expr=self.transform, value=self.latest_value,
timedelta=self.time_between_upda... | TypeError | dataset/ETHPy150Open lincolnloop/salmon/salmon/metrics/models.py/Metric.do_transform |
6,488 | def get_module(path):
"""
A modified duplicate from Django's built in backend
retriever.
slugify = get_module('django.template.defaultfilters.slugify')
"""
try:
from importlib import import_module
except ImportError as e:
from django.utils.importlib import import_module
... | AttributeError | dataset/ETHPy150Open zapier/django-rest-hooks/rest_hooks/utils.py/get_module |
6,489 | def _format_firewall_rules(firewall_policy):
try:
output = '[' + ',\n '.join([rule for rule in
firewall_policy['firewall_rules']]) + ']'
return output
except (__HOLE__, KeyError):
return '' | TypeError | dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/neutron/v2_0/fw/firewallpolicy.py/_format_firewall_rules |
6,490 | def api_call(request, format="json"):
""" the public api
attempts to validate a request as a valid oauth request then
builds the appropriate api_user object and tries to dispatch
to the provided method
"""
servertime = api.utcnow()
try:
kwargs = oauth_util.get_method_kwargs(request)
json_params =... | TypeError | dataset/ETHPy150Open CollabQ/CollabQ/api/views.py/api_call |
6,491 | def _socketpair(self):
"""Return a socket pair regardless of platform.
:rtype: (socket, socket)
"""
try:
server, client = socket.socketpair()
except __HOLE__:
# Connect in Windows
LOGGER.debug('Falling back to emulated socketpair behavior')
... | AttributeError | dataset/ETHPy150Open gmr/rabbitpy/rabbitpy/io.py/IO._socketpair |
6,492 | def get_2000_top_level_counts(geography):
try:
pop2000 = geography['data']['2000']['P1']['P001001']
hu2000 = geography['data']['2000']['H1']['H001001']
return pop2000,hu2000
except __HOLE__:
return '','' | KeyError | dataset/ETHPy150Open ireapps/census/dataprocessing/deploy_csv.py/get_2000_top_level_counts |
6,493 | def write_table_data(flo, state_fips, sumlev, table_id):
"""Given a File-Like Object, write a table to it"""
w = UnicodeCSVWriter(flo)
metadata = fetch_table_label(table_id)
header = ['GEOID', 'SUMLEV'] + METADATA_HEADERS + ['POP100.2000','HU100.2000']
for key in sorted(metadata['labels']):
... | KeyError | dataset/ETHPy150Open ireapps/census/dataprocessing/deploy_csv.py/write_table_data |
6,494 | def gid_to_group(gid):
'''
Convert the group id to the group name on this system
gid
gid to convert to a group name
CLI Example:
.. code-block:: bash
salt '*' file.gid_to_group 0
'''
try:
gid = int(gid)
except __HOLE__:
# This is not an integer, maybe ... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/gid_to_group |
6,495 | def group_to_gid(group):
'''
Convert the group to the gid on this system
group
group to convert to its gid
CLI Example:
.. code-block:: bash
salt '*' file.group_to_gid root
'''
if group is None:
return ''
try:
if isinstance(group, int):
ret... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/group_to_gid |
6,496 | def uid_to_user(uid):
'''
Convert a uid to a user name
uid
uid to convert to a username
CLI Example:
.. code-block:: bash
salt '*' file.uid_to_user 0
'''
try:
return pwd.getpwuid(uid).pw_name
except (__HOLE__, NameError):
# If user is not present, fall... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/uid_to_user |
6,497 | def user_to_uid(user):
'''
Convert user name to a uid
user
user name to convert to its uid
CLI Example:
.. code-block:: bash
salt '*' file.user_to_uid root
'''
if user is None:
user = salt.utils.get_user()
try:
if isinstance(user, int):
ret... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/user_to_uid |
6,498 | def chown(path, user, group):
'''
Chown a file, pass the file the desired user and group
path
path to the file or directory
user
user owner
group
group owner
CLI Example:
.. code-block:: bash
salt '*' file.chown /etc/passwd root root
'''
path = o... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/chown |
6,499 | def find(path, *args, **kwargs):
'''
Approximate the Unix ``find(1)`` command and return a list of paths that
meet the specified criteria.
The options include match criteria:
.. code-block:: text
name = path-glob # case sensitive
iname = path-glob ... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/file.py/find |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.