Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
8,200 | def get_action_class_instance(action_cls, config=None, action_service=None):
"""
Instantiate and return Action class instance.
:param action_cls: Action class to instantiate.
:type action_cls: ``class``
:param config: Config to pass to the action class.
:type config: ``dict``
:param actio... | TypeError | dataset/ETHPy150Open StackStorm/st2/st2actions/st2actions/runners/utils.py/get_action_class_instance |
8,201 | def get(self, **kwargs):
if 'pk' in kwargs:
pk = kwargs.pop('pk')
elif 'id' in kwargs:
pk = kwargs.pop('id')
else:
try:
pk = self.instance.id
except __HOLE__:
raise AttributeError("The 'es.get' method needs to be cal... | AttributeError | dataset/ETHPy150Open liberation/django-elasticsearch/django_elasticsearch/managers.py/ElasticsearchManager.get |
8,202 | def make_mapping(self):
"""
Create the model's es mapping on the fly
"""
mappings = {}
for field_name in self.get_fields():
try:
field = self.model._meta.get_field(field_name)
except FieldDoesNotExist:
# abstract field
... | KeyError | dataset/ETHPy150Open liberation/django-elasticsearch/django_elasticsearch/managers.py/ElasticsearchManager.make_mapping |
8,203 | @pytest.fixture
def dbm_db(request):
db = dbm.open(db_file, 'n')
db.close()
def fin():
try:
os.remove(db_file)
except __HOLE__:
pass
request.addfinalizer(fin) | OSError | dataset/ETHPy150Open eleme/thriftpy/tests/test_tracking.py/dbm_db |
8,204 | @property
def function(self):
"""
The function pointed to by the path_str attribute.
Returns:
A handle to a Python function or None if function is not valid.
"""
if not self._function and self._valid is None:
try:
# Split into parts an... | ValueError | dataset/ETHPy150Open tethysplatform/tethys/tethys_apps/base/persistent_store.py/TethysFunctionExtractor.function |
8,205 | def __init__(self, pickle_file_path):
cmd.Cmd.__init__(self)
if not os.path.isfile(pickle_file_path):
print "File %s does not exist." % pickle_file_path
sys.exit(1)
try:
pickle_file = open(pickle_file_path, 'rb')
except __HOLE__ as e:
pri... | IOError | dataset/ETHPy150Open cowrie/cowrie/utils/fsctl.py/fseditCmd.__init__ |
8,206 | @contextmanager
def patched_settings(**kwargs):
old = {}
for k, v in kwargs.items():
try:
old[k] = getattr(settings, k)
except __HOLE__:
pass
setattr(settings, k, v)
yield
for k, v in old.items():
setattr(settings, k, v) | AttributeError | dataset/ETHPy150Open hzdg/django-staticbuilder/staticbuilder/utils.py/patched_settings |
8,207 | @manage(['op'])
def init(self, op):
try:
self.op = {
'<': operator.lt,
'<=': operator.le,
'=': operator.eq,
'!=': operator.ne,
'>=': operator.ge,
'>': operator.gt,
}[op]
except __H... | KeyError | dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/actorstore/systemactors/std/Compare.py/Compare.init |
8,208 | @property
def _core_plugin(self):
try:
return self._plugin
except __HOLE__:
self._plugin = manager.NeutronManager.get_plugin()
return self._plugin | AttributeError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/service_vm_lib.py/ServiceVMManager._core_plugin |
8,209 | def dispatch_service_vm_real(
self, context, instance_name, vm_image, vm_flavor,
hosting_device_drv, credentials_info, connectivity_info,
ports=None):
mgmt_port = connectivity_info['mgmt_port']
nics = [{'port-id': mgmt_port['id']}]
for port in ports or {}:
... | IOError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/service_vm_lib.py/ServiceVMManager.dispatch_service_vm_real |
8,210 | def dispatch_service_vm_fake(self, context, instance_name, vm_image,
vm_flavor, hosting_device_drv,
credentials_info, connectivity_info,
ports=None):
mgmt_port = connectivity_info['mgmt_port']
try:
... | IOError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/service_vm_lib.py/ServiceVMManager.dispatch_service_vm_fake |
8,211 | def main():
global SETTINGS, args
try:
# warn the user that they are starting PyPXE as non-root user
if os.getuid() != 0:
print '\nWARNING: Not root. Servers will probably fail to bind.\n'
# configure
args = parse_cli_arguments()
if args.JSON_CONFIG: # load f... | ValueError | dataset/ETHPy150Open psychomario/PyPXE/pypxe/server.py/main |
8,212 | def is_fp_closed(obj):
"""
Checks whether a given file-like object is closed.
:param obj:
The file-like object to check.
"""
try:
# Check via the official file-like-object way.
return obj.closed
except AttributeError:
pass
try:
# Check if the object... | AttributeError | dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/requests/packages/urllib3/util/response.py/is_fp_closed |
8,213 | def options_tab(request, template_name="manage/voucher/options.html"):
"""Displays the vouchers options
"""
try:
voucher_options = VoucherOptions.objects.all()[0]
except __HOLE__:
voucher_options = VoucherOptions.objects.create()
form = VoucherOptionsForm(instance=voucher_options)
... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/voucher/views.py/options_tab |
8,214 | @permission_required("core.manage_shop")
def manage_vouchers(request):
"""Redirects to the first voucher group or to no voucher groups view.
"""
try:
voucher_group = VoucherGroup.objects.all()[0]
except __HOLE__:
url = reverse("lfs_no_vouchers")
else:
url = reverse("lfs_manag... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/voucher/views.py/manage_vouchers |
8,215 | @permission_required("core.manage_shop")
def add_vouchers(request, group_id):
"""
"""
voucher_group = VoucherGroup.objects.get(pk=group_id)
form = VoucherForm(data=request.POST)
msg = ""
if form.is_valid():
try:
amount = int(request.POST.get("amount", 0))
except __H... | TypeError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/voucher/views.py/add_vouchers |
8,216 | @permission_required("core.manage_shop")
def save_voucher_options(request):
"""Saves voucher options.
"""
try:
voucher_options = VoucherOptions.objects.all()[0]
except __HOLE__:
voucher_options = VoucherOptions.objects.create()
form = VoucherOptionsForm(instance=voucher_options, dat... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/voucher/views.py/save_voucher_options |
8,217 | @wsgi.response(202)
def create(self, req, body, gid, is_proxy=False):
def _validate(context, body, gid, is_proxy=False):
proxy = db.process_get_all(
context, gid, filters={"is_proxy": True})
if is_proxy:
if len(proxy) > 0:
msg = _(... | TypeError | dataset/ETHPy150Open openstack/rack/rack/api/v1/processes.py/Controller.create |
8,218 | def decode_to_string(toDecode):
"""
This function is needed for Python 3,
because a subprocess can return bytes instead of a string.
"""
try:
return toDecode.decode('utf-8')
except __HOLE__: # bytesToDecode was of type string before
return toDecode | AttributeError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/util.py/decode_to_string |
8,219 | def measure_energy(oldEnergy=None):
'''
returns a dictionary with the currently available values of energy consumptions (like a time-stamp).
If oldEnergy is not None, the difference (currentValue - oldEnergy) is returned.
'''
newEnergy = {}
executable = find_executable('read-energy.sh', exitOnE... | ValueError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/util.py/measure_energy |
8,220 | def main():
global FIELDS_TO_CONVERT
# construct option parser
parser = OptionParser()
parser.add_option("-f","--from", dest="fromencoding",
help="Override original encoding (ascii)",
default='ascii')
parser.add_option("-t","--to", dest="toencoding",
help="Override target encoding (utf-16)",... | UnicodeDecodeError | dataset/ETHPy150Open Ciantic/pytagger/mp3conv.py/main |
8,221 | def load_library(self, *names, **kwargs):
'''Find and load a library.
More than one name can be specified, they will be tried in order.
Platform-specific library names (given as kwargs) are tried first.
Raises ImportError if library is not found.
'''
if 'frame... | OSError | dataset/ETHPy150Open ardekantur/pyglet/pyglet/lib.py/LibraryLoader.load_library |
8,222 | def _create_ld_so_cache(self):
# Recreate search path followed by ld.so. This is going to be
# slow to build, and incorrect (ld.so uses ld.so.cache, which may
# not be up-to-date). Used only as fallback for distros without
# /sbin/ldconfig.
#
# We assume the DT_RPATH an... | IOError | dataset/ETHPy150Open ardekantur/pyglet/pyglet/lib.py/LinuxLibraryLoader._create_ld_so_cache |
8,223 | def _get_plugins_from_settings():
plugins = (list(getattr(settings, 'NOSE_PLUGINS', [])) +
['django_nose.plugin.TestReorderer'])
for plug_path in plugins:
try:
dot = plug_path.rindex('.')
except __HOLE__:
raise exceptions.ImproperlyConfigured(
... | ValueError | dataset/ETHPy150Open django-nose/django-nose/django_nose/runner.py/_get_plugins_from_settings |
8,224 | def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
# Nod to tastypie's use of importlib.
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_p... | AttributeError | dataset/ETHPy150Open tomchristie/django-rest-framework/rest_framework/settings.py/import_from_string |
8,225 | def __getattr__(self, attr):
if attr not in self.defaults:
raise AttributeError("Invalid API setting: '%s'" % attr)
try:
# Check if present in user settings
val = self.user_settings[attr]
except __HOLE__:
# Fall back to defaults
val = ... | KeyError | dataset/ETHPy150Open tomchristie/django-rest-framework/rest_framework/settings.py/APISettings.__getattr__ |
8,226 | def supershapes_dict():
"""Return a dict of all supershapes in this module keyed by name."""
current_module = sys.modules[__name__]
supershapes = dict()
for name, obj in inspect.getmembers(current_module):
try:
if issubclass(obj, _SuperShape) and (name[0] != '_'):
sup... | TypeError | dataset/ETHPy150Open kobejohn/polymaze/polymaze/shapes.py/supershapes_dict |
8,227 | def edge(self, neighbor_index):
"""Return one edge of this shape by the index of the sharing neighbor.
Note:
When an edge is shared, both shapes will return the same edge.
"""
# try to get from self
try:
return self._owned_edges[neighbor_index]
except... | KeyError | dataset/ETHPy150Open kobejohn/polymaze/polymaze/shapes.py/_ComponentShape.edge |
8,228 | def endpoints(self, requesting_shape_index=None):
"""Return the xy, xy end points of this edge.
kwargs: requesting_shape_index - if the clockwise order of vertices is
desired, provide this so the edge knows which way to sort
"""
# default if the sorting doesn't matte... | KeyError | dataset/ETHPy150Open kobejohn/polymaze/polymaze/shapes.py/Edge.endpoints |
8,229 | def locateOnScreen(image, minSearchTime=0, **kwargs):
"""minSearchTime - amount of time in seconds to repeat taking
screenshots and trying to locate a match. The default of 0 performs
a single search.
"""
start = time.time()
while True:
try:
screenshotIm = screenshot(region=... | AttributeError | dataset/ETHPy150Open asweigart/pyscreeze/pyscreeze/__init__.py/locateOnScreen |
8,230 | def locateAllOnScreen(image, **kwargs):
screenshotIm = screenshot(region=None) # the locateAll() function must handle cropping to return accurate coordinates, so don't pass a region here.
retVal = locateAll(image, screenshotIm, **kwargs)
try:
screenshotIm.fp.close()
except __HOLE__:
# Sc... | AttributeError | dataset/ETHPy150Open asweigart/pyscreeze/pyscreeze/__init__.py/locateAllOnScreen |
8,231 | def get_library(name):
"""
Returns a ctypes.CDLL or None
"""
try:
if platform.system() == 'Windows':
return ctypes.windll.LoadLibrary(name)
else:
return ctypes.cdll.LoadLibrary(name)
except __HOLE__:
pass
return None | OSError | dataset/ETHPy150Open NVIDIA/DIGITS/digits/device_query.py/get_library |
8,232 | def _trim_disassembly(stdout):
if not stdout:
return stdout
start_loc = stdout.find("Dump of assembler code")
end_loc = stdout.find("End of assembler dump.", start_loc)
if start_loc == -1 or end_loc == -1:
return "%s\nError trimming assembler dump. start_loc = %d, end_loc = %d" % (stdout... | ValueError | dataset/ETHPy150Open blackberry/ALF/alf/debug/_gdb.py/_trim_disassembly |
8,233 | def run_with_gdb(target_cmd, symbols=None, solib_search=None, env=None, callback=None,
callback_args=None, timeout=_common.DEFAULT_TIMEOUT, memory_limit=None,
idle_limit=None):
"""
This function is similar to the :func:`run` function above,
except the target is executed und... | OSError | dataset/ETHPy150Open blackberry/ALF/alf/debug/_gdb.py/run_with_gdb |
8,234 | def Load(self):
fname = User.User.OwnFile(self._name, "usermemo")
try:
os.stat(fname)
except OSError as exc:
data = self.read()
if (data is None):
raise ServerError("can't load usermemo for %s" % self._name)
try:
w... | IOError | dataset/ETHPy150Open HenryHu/pybbs/UserMemo.py/UserMemo.Load |
8,235 | def read(self):
datafile = User.User.OwnFile(self._name, ".userdata")
try:
with open(datafile, "rb") as f:
return f.read(self.size)
except IOError:
try:
if not hasattr(self, '__reserved'):
Util.InitStruct(self)
... | IOError | dataset/ETHPy150Open HenryHu/pybbs/UserMemo.py/UserMemo.read |
8,236 | def auth_api_request(self, api_endpoint, method='GET', input_dict=None):
'''Send API request to DEP or depsim providing OAuth where necessary.
We implement the logic of attempting OAuth1 authentication here. We
could have tried to implement recursive calling of `api_request()` but
to av... | HTTPError | dataset/ETHPy150Open jessepeterson/commandment/commandment/utils/dep.py/DEP.auth_api_request |
8,237 | def get_admin(self):
""" Returns the current admin system to render templates within the
``Flask-Admin`` system.
Returns
-------
obj
Current admin view
"""
try:
return self._admin
except __HOLE__:
raise NotImplemented... | AttributeError | dataset/ETHPy150Open thisissoon/Flask-Velox/flask_velox/admin/mixins/template.py/AdminTemplateMixin.get_admin |
8,238 | def write(self,vb=voicebox):
if not vb.voices:
print("Cannot write with an empty Voicebox!")
return
self.chooseVoiceMenu(vb)
scriptlog =[]
cur = 0
linelog = []
hashtable = {}
while 1:
before = linelog[:cur]
after ... | NameError | dataset/ETHPy150Open jbrew/pt-voicebox/writer.py/Writer.write |
8,239 | def writing_menu(self,vb):
top_menu_prompt = "Choose an option from below:" \
"\n 1. Select one voice." \
"\n 2. Assign custom weights." \
"\n 3. Change ranktypes." \
"\n 4. Get voice info." \
"\n 5. Ad... | NameError | dataset/ETHPy150Open jbrew/pt-voicebox/writer.py/Writer.writing_menu |
8,240 | def chooseVoiceMenu(self,vb):
print(self.voiceHeader(vb))
try:
response = raw_input('Choose a voice by number from above. \nOr:\n'
'0 to use an equal mixture.\n'
'C to assign custom weights.\n')
except __HOLE__:
... | NameError | dataset/ETHPy150Open jbrew/pt-voicebox/writer.py/Writer.chooseVoiceMenu |
8,241 | def setWeightMenu(self,vb):
vb.getVoices()
for v in sorted(vb.voices):
try:
response = raw_input('Set weight for '+v+'\n')
except __HOLE__:
response = input('Set weight for '+v+'\n')
if response.isdigit():
response = int... | NameError | dataset/ETHPy150Open jbrew/pt-voicebox/writer.py/Writer.setWeightMenu |
8,242 | def addVoiceMenu(self,vb):
print(self.voiceHeader(vb))
import glob
textfiles = glob.glob('texts/*')
count = 1
for filename in textfiles:
print(str(count) + ": " + filename[6:])
count+=1
try:
response = raw_input('Choose a file by number... | NameError | dataset/ETHPy150Open jbrew/pt-voicebox/writer.py/Writer.addVoiceMenu |
8,243 | def test_tryexcept(input,output):
def endpoint(v):
if v == 7:
raise ValueError
return v
def callee(v):
return endpoint(v)
def caller(v):
try:
return callee(v)
except __HOLE__:
return 0
assert caller(input) == output | ValueError | dataset/ETHPy150Open rfk/withrestart/withrestart/tests/overhead.py/test_tryexcept |
8,244 | def from_dict(self, dic):
for k, v in dic.items():
try:
ctor = self.OPTIONS[k]
except __HOLE__:
fmt = "Does not support option: '%s'"
raise KeyError(fmt % k)
else:
self.values[k] = ctor(v) | KeyError | dataset/ETHPy150Open numba/numba/numba/targets/options.py/TargetOptions.from_dict |
8,245 | def parse_entry_points(self):
def split_and_strip(entry_point):
console_script, entry_point = entry_point.split('=', 2)
return console_script.strip(), entry_point.strip()
raw_entry_points = self.distribution.entry_points
if isinstance(raw_entry_points, string):
parser = ConfigParser()
... | ValueError | dataset/ETHPy150Open pantsbuild/pex/pex/commands/bdist_pex.py/bdist_pex.parse_entry_points |
8,246 | def _refleak_cleanup():
# Collect cyclic trash and read memory statistics immediately after.
try:
func1 = sys.getallocatedblocks
except AttributeError:
func1 = lambda: 42
try:
func2 = sys.gettotalrefcount
except __HOLE__:
func2 = lambda: 42
# Flush standard outpu... | AttributeError | dataset/ETHPy150Open numba/llvmlite/llvmlite/tests/customize.py/_refleak_cleanup |
8,247 | def addSuccess(self, test):
try:
rc_deltas, alloc_deltas = self._huntLeaks(test)
except __HOLE__:
# Test failed when repeated
assert not self.wasSuccessful()
return
# These checkers return False on success, True on failure
def check_rc_del... | AssertionError | dataset/ETHPy150Open numba/llvmlite/llvmlite/tests/customize.py/RefleakTestResult.addSuccess |
8,248 | def test(self, verbose=1, extra_argv=None, coverage=False, capture=True,
knownfailure=True):
"""
Run tests for module using nose.
:type verbose: int
:param verbose: Verbosity value for test outputs, in the range 1-10.
Default is 1.
:type ext... | ImportError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/tests/main.py/TheanoNoseTester.test |
8,249 | def setup_backend(self):
from pymongo import ASCENDING, DESCENDING
from pymongo.connection import Connection
try:
from pymongo.uri_parser import parse_uri
except __HOLE__:
from pymongo.connection import _parse_uri as parse_uri
from pymongo.errors... | ImportError | dataset/ETHPy150Open getlogbook/logbook/logbook/ticketing.py/MongoDBBackend.setup_backend |
8,250 | def main():
#---Load environment settings from SETTINGS.json in root directory and build filepaths for all base submissions---#
settings = utils.load_settings('SETTINGS.json')
base_filepaths = (settings['file_bryan_submission'],
settings['file_miroslaw_submission'])
segment_we... | IOError | dataset/ETHPy150Open theusual/kaggle-seeclickfix-ensemble/main.py/main |
8,251 | def configure(name, path=None):
""" Configure logging and return a logger and the location of its logging
configuration file.
This function expects:
+ A Splunk app directory structure::
<app-root>
bin
...
default
...
local
... | KeyError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/logging.py/configure |
8,252 | def single_file_action(self, path, apply_template=True):
attempt_open = True
file_exist = os.path.exists(path)
if not file_exist:
try:
self.create(path)
except __HOLE__ as e:
attempt_open = False
sublime.error_message("Canno... | OSError | dataset/ETHPy150Open skuroda/Sublime-AdvancedNewFile/advanced_new_file/commands/new_file_command.py/AdvancedNewFileNew.single_file_action |
8,253 | def load_configs_from_directory(config_dir, overrides):
"""
Returns a master configuration object and a list of configuration objects
:param config_dir: the directory where the configuration files are located
:param overrides: mapping of the command line overrides
"""
MASTER_CONFIG_FILE_NAME = "master"
D... | ValueError | dataset/ETHPy150Open linkedin/Zopkio/zopkio/test_runner_helper.py/load_configs_from_directory |
8,254 | @staticmethod
def _create_scoped_credentials(credentials, scope):
"""Create a scoped set of credentials if it is required.
:type credentials: :class:`oauth2client.client.OAuth2Credentials` or
:class:`NoneType`
:param credentials: The OAuth2 Credentials to add a sc... | AttributeError | dataset/ETHPy150Open GoogleCloudPlatform/gcloud-python/gcloud/connection.py/Connection._create_scoped_credentials |
8,255 | def set_character_set(self, charset):
"""Set the connection character set to charset. The character
set can only be changed in MySQL-4.1 and newer. If you try
to change the character set from the current value in an
older version, NotSupportedError will be raised."""
if char... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/MySQL-python-1.2.5/MySQLdb/connections.py/Connection.set_character_set |
8,256 | def __init__(self, file_path=None):
self.index = 0
self.string_encoding = None
self.file_path = file_path
self.file_type = None
try:
fd = open(file_path, 'r')
self.data = fd.read()
fd.close()
except __HOLE__ as e:
print('I/O... | IOError | dataset/ETHPy150Open samdmarshall/xcparse/xcparse/Helpers/pbPlist/pbParser.py/PBParser.__init__ |
8,257 | def next(self):
item = self.iterator.next()
if not isinstance(item, self.as_is):
try:
new_iter = iter(item)
self.iterator = itertools.chain(new_iter, self.iterator)
return self.next()
except __HOLE__:
pass
... | TypeError | dataset/ETHPy150Open sunlightlabs/clearspending/utils.py/flattened.next |
8,258 | def get_node_or_fail(conn, node_id, coroutine=None, cargs=(), ckwargs={}):
"""Shortcut to get a single node by its id. In case when
such node could not be found, coroutine could be called
to handle such case. Typically coroutine will output an
error message and exit from application.
@param conn: ... | IndexError | dataset/ETHPy150Open novel/lc-tools/lctools/shortcuts.py/get_node_or_fail |
8,259 | def __init__(self,stl_file):
"""given an stl file object, imports points and reshapes array to an
array of n_facetsx3 points."""
if not hasattr(stl_file,'readline'):
stl_file_name = stl_file
stl_file = open(stl_file,'rb')
else:
stl_file_name = stl_fil... | KeyError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/geometry/stl.py/STL.__init__ |
8,260 | @classmethod
def get_for_instance(cls, instance):
try:
permissions = cls._registry[type(instance)]
except KeyError:
try:
permissions = cls._registry[cls._proxies[type(instance)]]
except __HOLE__:
permissions = ()
pks = [per... | KeyError | dataset/ETHPy150Open mayan-edms/mayan-edms/mayan/apps/acls/classes.py/ModelPermission.get_for_instance |
8,261 | def _init_toolkit():
""" Initialise the current toolkit. """
def import_toolkit(tk):
try:
# Try and import the toolkit's pyface backend init module.
__import__('tvtk.pyface.ui.%s.init' % tk)
except:
raise
if ETSConfig.toolkit:
# If the toolkit ha... | ImportError | dataset/ETHPy150Open enthought/mayavi/tvtk/pyface/toolkit.py/_init_toolkit |
8,262 | def toolkit_object(name):
""" Return the toolkit specific object with the given name. The name
consists of the relative module path and the object name separated by a
colon.
"""
mname, oname = name.split(':')
be = 'tvtk.pyface.ui.%s.' % _toolkit
be_mname = be + mname
class Unimplement... | ImportError | dataset/ETHPy150Open enthought/mayavi/tvtk/pyface/toolkit.py/toolkit_object |
8,263 | def GetFeedItemIdsForCampaign(campaign_feed):
"""Gets the Feed Item Ids used by a campaign through a given Campaign Feed.
Args:
campaign_feed: the Campaign Feed we are retrieving Feed Item Ids from.
Returns:
A list of Feed Item IDs.
"""
feed_item_ids = set()
try:
lhs_operand = campaign_feed['... | KeyError | dataset/ETHPy150Open googleads/googleads-python-lib/examples/adwords/v201603/migration/migrate_to_extension_settings.py/GetFeedItemIdsForCampaign |
8,264 | def run_tests(self):
import sys
if sys.version_info[:2] == (2, 6):
import unittest2 as unittest # Python 2.6
else:
import unittest
setup_file = sys.modules['__main__'].__file__
setup_dir = os.path.abspath(os.path.dirname(setup_file))
tests = un... | ImportError | dataset/ETHPy150Open laike9m/ezcf/setup.py/PyTest.run_tests |
8,265 | def register_rule_types():
LOG.debug('Start : register default RuleTypes.')
for rule_type in RULE_TYPES:
rule_type = copy.deepcopy(rule_type)
try:
rule_type_db = RuleType.get_by_name(rule_type['name'])
update = True
except __HOLE__:
rule_type_db = No... | ValueError | dataset/ETHPy150Open StackStorm/st2/st2common/st2common/bootstrap/ruletypesregistrar.py/register_rule_types |
8,266 | def __init__(self, request, model, list_display, list_display_links,
list_filter, date_hierarchy, search_fields, list_select_related,
list_per_page, list_max_show_all, list_editable, model_admin):
self.model = model
self.opts = model._meta
self.lookup_opts = self.opts
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/views/main.py/ChangeList.__init__ |
8,267 | def get_ordering(self, request, queryset):
"""
Returns the list of ordering fields for the change list.
First we check the get_ordering() method in model admin, then we check
the object's default ordering. Then, any manually-specified ordering
from the query string overrides anyt... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/views/main.py/ChangeList.get_ordering |
8,268 | def get_ordering_field_columns(self):
"""
Returns a SortedDict of ordering field column numbers and asc/desc
"""
# We must cope with more than one column having the same underlying sort
# field, so we base things on column numbers.
ordering = self._get_default_ordering()... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/views/main.py/ChangeList.get_ordering_field_columns |
8,269 | @publisher('model')
def check_uvs():
"""checks uvs with no uv area
The area of a 2d polygon calculation is based on the answer of Darius Bacon
in http://stackoverflow.com/questions/451426/how-do-i-calculate-the-surface-area-of-a-2d-polygon
"""
# skip if this is a representation
v = staging.get... | RuntimeError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/publish.py/check_uvs |
8,270 | @publisher(['animation', 'shot previs'])
def set_frame_range():
"""sets the frame range from the shot node
"""
shot_node = pm.ls(type='shot')[0]
start_frame = shot_node.startFrame.get()
end_frame = shot_node.endFrame.get()
handle_count = 1
try:
handle_count = shot_node.getAttr('hand... | AttributeError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/publish.py/set_frame_range |
8,271 | @publisher(['animation', 'shot previs'], publisher_type=POST_PUBLISHER_TYPE)
def export_camera():
"""exports camera and the related shot node
"""
from stalker import Task, Version
from anima.env import mayaEnv
m = mayaEnv.Maya()
v = m.get_current_version()
shot = pm.ls(type='shot')[0]
... | IndexError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/mayaEnv/publish.py/export_camera |
8,272 | def cleanse_setting(key, value):
"""Cleanse an individual setting key/value of sensitive content.
If the value is a dictionary, recursively cleanse the keys in
that dictionary.
"""
try:
if HIDDEN_SETTINGS.search(key):
cleansed = CLEANSED_SUBSTITUTE
else:
if i... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/cleanse_setting |
8,273 | def get_exception_reporter_filter(request):
global default_exception_reporter_filter
if default_exception_reporter_filter is None:
# Load the default filter for the first time and cache it.
modpath = settings.DEFAULT_EXCEPTION_REPORTER_FILTER
modname, classname = modpath.rsplit('.', 1)
... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/get_exception_reporter_filter |
8,274 | def get_traceback_data(self):
"Return a Context instance containing traceback information."
if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
from django.template.loader import template_source_loaders
self.template_does_not_exist = True
self.loade... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/ExceptionReporter.get_traceback_data |
8,275 | def get_template_exception_info(self):
origin, (start, end) = self.exc_value.django_template_source
template_source = origin.reload()
context_lines = 10
line = 0
upto = 0
source_lines = []
before = during = after = ""
for num, next in enumerate(linebreak_i... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/ExceptionReporter.get_template_exception_info |
8,276 | def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
"""
Returns context_lines before and after lineno from file.
Returns (pre_context_lineno, pre_context, context_line, post_context).
"""
source = None
if loader is not None and ... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/ExceptionReporter._get_lines_from_file |
8,277 | def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
tried = exception.args[0]['tried']
except (__HOLE__, TypeError, KeyError):
tried = []
else:
if not tried:
# tried exists but is an empty ... | IndexError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/debug.py/technical_404_response |
8,278 | def _real_extract(self, url):
from ..extractor import gen_extractors
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
extractor_id = mobj.group('extractor')
all_extractors = gen_extractors()
rex = re.compile(extractor_id, flags=re.IGNORECASE)
ma... | IndexError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/extractor/testurl.py/TestURLIE._real_extract |
8,279 | def expect_line(self, content):
try:
line = next(self)
except __HOLE__:
raise ParsingError('expected %r but got end of input' % content)
if line != content:
raise ParsingError('expected %r but got %r' % (content, line)) | StopIteration | dataset/ETHPy150Open tonyseek/openvpn-status/openvpn_status/parser.py/LogParser.expect_line |
8,280 | def expect_list(self):
try:
line = next(self)
except __HOLE__:
raise ParsingError('expected list but got end of input')
splited = line.split(self.list_separator)
if len(splited) == 1:
raise ParsingError('expected list but got %r' % line)
return... | StopIteration | dataset/ETHPy150Open tonyseek/openvpn-status/openvpn_status/parser.py/LogParser.expect_list |
8,281 | def expect_tuple(self, name):
try:
line = next(self)
except __HOLE__:
raise ParsingError('expected 2-tuple but got end of input')
splited = line.split(self.list_separator)
if len(splited) != 2:
raise ParsingError('expected 2-tuple but got %r' % line)
... | StopIteration | dataset/ETHPy150Open tonyseek/openvpn-status/openvpn_status/parser.py/LogParser.expect_tuple |
8,282 | def _find_cgroup_mounts():
"""
Return the information which subsystems are mounted where.
@return a generator of tuples (subsystem, mountpoint)
"""
try:
with open('/proc/mounts', 'rt') as mountsFile:
for mount in mountsFile:
mount = mount.split(' ')
... | IOError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/_find_cgroup_mounts |
8,283 | def _find_own_cgroups():
"""
For all subsystems, return the information in which (sub-)cgroup this process is in.
(Each process is in exactly cgroup in each hierarchy.)
@return a generator of tuples (subsystem, cgroup)
"""
try:
with open('/proc/self/cgroup', 'rt') as ownCgroupsFile:
... | IOError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/_find_own_cgroups |
8,284 | def _parse_proc_pid_cgroup(content):
"""
Parse a /proc/*/cgroup file into tuples of (subsystem,cgroup).
@param content: An iterable over the lines of the file.
@return: a generator of tuples
"""
for ownCgroup in content:
#each line is "id:subsystem,subsystem:path"
ownCgroup = own... | IndexError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/_parse_proc_pid_cgroup |
8,285 | def kill_all_tasks_in_cgroup(cgroup, kill_process_fn):
tasksFile = os.path.join(cgroup, 'tasks')
freezer_file = os.path.join(cgroup, 'freezer.state')
def try_write_to_freezer(content):
try:
util.write_file(content, freezer_file)
except __HOLE__:
pass # expected if fr... | IOError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/kill_all_tasks_in_cgroup |
8,286 | def remove_cgroup(cgroup):
if not os.path.exists(cgroup):
logging.warning('Cannot remove CGroup %s, because it does not exist.', cgroup)
return
assert os.path.getsize(os.path.join(cgroup, 'tasks')) == 0
try:
os.rmdir(cgroup)
except OSError:
# sometimes this fails because ... | OSError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/remove_cgroup |
8,287 | def _register_process_with_cgrulesengd(pid):
"""Tell cgrulesengd daemon to not move the given process into other cgroups,
if libcgroup is available.
"""
# Logging/printing from inside preexec_fn would end up in the output file,
# not in the correct logger, thus it is disabled here.
from ctypes i... | OSError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/_register_process_with_cgrulesengd |
8,288 | def require_subsystem(self, subsystem):
"""
Check whether the given subsystem is enabled and is writable
(i.e., new cgroups can be created for it).
Produces a log message for the user if one of the conditions is not fulfilled.
If the subsystem is enabled but not writable, it will... | OSError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/Cgroup.require_subsystem |
8,289 | def create_fresh_child_cgroup(self, *subsystems):
"""
Create child cgroups of the current cgroup for at least the given subsystems.
@return: A Cgroup instance representing the new child cgroup(s).
"""
assert set(subsystems).issubset(self.per_subsystem.keys())
createdCgrou... | IOError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/cgroups.py/Cgroup.create_fresh_child_cgroup |
8,290 | def main():
import argparse
import redis
import time
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from scutils.redis_queue import RedisPriorityQueue
from scutils.redis_throttled_queue import RedisThrottledQueue
parser = argpar... | KeyboardInterrupt | dataset/ETHPy150Open istresearch/scrapy-cluster/utils/tests/test_throttled_queue.py/main |
8,291 | def test_error_messages(self):
self.model.driver.clear_objectives()
self.model.driver.clear_constraints()
try:
self.model.driver._check()
except __HOLE__, err:
msg = "driver: Missing outputs for gradient calculation"
self.assertEqual(str(err), msg)
... | ValueError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/drivers/test/test_sensitivity.py/SensitivityDriverTestCase.test_error_messages |
8,292 | def _register():
for pduKlass in globals().values():
try:
if issubclass(pduKlass, PDU):
PDUS[pduKlass.commandId] = pduKlass
except __HOLE__:
pass | TypeError | dataset/ETHPy150Open jookies/jasmin/jasmin/vendor/smpp/pdu/operations.py/_register |
8,293 | def __init__(self, key, msg = None, digestmod = None):
"""Create a new HMAC object.
:Parameters:
key : byte string
secret key for the MAC object.
It must be long enough to match the expected security level of the
MAC. However, there is no benefit in using k... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/Hash/HMAC.py/HMAC.__init__ |
8,294 | def handle(self, request, context):
url = reverse("horizon:project:network_services:index")
try:
try:
del context['template_string']
del context['template_file']
del context['config_type']
except __HOLE__:
pass
... | KeyError | dataset/ETHPy150Open openstack/group-based-policy-ui/gbpui/panels/network_services/forms.py/CreateServiceChainNodeForm.handle |
8,295 | def test01_basic(self):
d = db.DB()
get_returns_none = d.set_get_returns_none(2)
d.set_get_returns_none(get_returns_none)
d.open(self.filename, db.DB_RECNO, db.DB_CREATE)
for x in string.ascii_letters:
recno = d.append(x * 60)
self.assertIsInstance(recn... | KeyError | dataset/ETHPy150Open francelabs/datafari/windows/python/Lib/bsddb/test/test_recno.py/SimpleRecnoTestCase.test01_basic |
8,296 | def authenticator(session_manager, login_url='/auth/login'):
'''Create an authenticator decorator.
:param session_manager: A session manager class to be used for storing
and retrieving session data. Probably based on
:class:`BaseSession`.
:param login_url: The URL to redirect to if... | KeyError | dataset/ETHPy150Open linsomniac/bottlesession/bottlesession.py/authenticator |
8,297 | def forwards(self, orm):
# Adding field 'Thumb.image'
db.add_column('cropduster4_thumb', 'image', self.gf('django.db.models.fields.related.ForeignKey')(blank=True, related_name='+', null=True, to=orm['cropduster.Image']), keep_default=False)
if not db.dry_run:
Thumb = orm['cropduster... | IndexError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/south_migrations/0006_auto__add_field_thumb_image.py/Migration.forwards |
8,298 | def _create_autocompleter_system(files_only, directories_only, handler_type_cls, get_host_func):
def local_handler(func):
class ChildHandler(SCPHandler):
is_leaf = True
def __init__(self, shell, path):
self.path = path
SCPHandler.__init__(self, shell)... | IOError | dataset/ETHPy150Open jonathanslenders/python-deployer/deployer/scp_shell.py/_create_autocompleter_system |
8,299 | def get_metadata(full_path):
metadata = {
'filename': os.path.basename(full_path)[:-4],
}
if full_path.endswith('mp4') or full_path.endswith('m4a'):
id3_cls = EasyMP4
elif full_path.endswith('mp3'):
id3_cls = EasyMP3
else:
id3_cls = None
if id3_cls:
... | KeyError | dataset/ETHPy150Open disqus/playa/playa/ext/audio/index.py/get_metadata |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.