Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,800 | def _create_stylecmds(self):
t2c = self.ttype2cmd = {Token: ''}
c2d = self.cmd2def = {}
cp = self.commandprefix
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
first = iter(letters)
second = iter(letters)
firstl = first.next()
def rgbcol... | StopIteration | dataset/ETHPy150Open joeyb/joeyb-blog/externals/pygments/formatters/latex.py/LatexFormatter._create_stylecmds |
5,801 | def load_hashers(password_hashers=None):
global HASHERS
global PREFERRED_HASHER
hashers = []
if not password_hashers:
password_hashers = settings.PASSWORD_HASHERS
for backend in password_hashers:
try:
mod_path, cls_name = backend.rsplit('.', 1)
mod = importlib... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/auth/hashers.py/load_hashers |
5,802 | def _load_library(self):
if self.library is not None:
if isinstance(self.library, (tuple, list)):
name, mod_path = self.library
else:
name = mod_path = self.library
try:
module = importlib.import_module(mod_path)
exc... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/contrib/auth/hashers.py/BasePasswordHasher._load_library |
5,803 | def _get_server_version_info(self, connection):
dbapi_con = connection.connection
version = []
r = re.compile('[.\-]')
for n in r.split(dbapi_con.dbversion):
try:
version.append(int(n))
except __HOLE__:
version.append(n)
ret... | ValueError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/dialects/mysql/zxjdbc.py/MySQLDialect_zxjdbc._get_server_version_info |
5,804 | def _parse_headers(self):
header_arr = utf8_clean(self.header_row).split(delimiter)
summary_line = utf8_clean(self.form_row).split(delimiter)
# These are always consistent
try:
self.headers['form'] = clean_entry(summary_line[0])
self.headers['fec_id'] = clean_en... | IndexError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/parsing/filing.py/filing._parse_headers |
5,805 | def get_form_type(self):
""" Get the base form -- remove the A, N or T (amended, new, termination) designations"""
try:
raw_form_type = self.headers['form']
a = re.search('(.*?)[A|N|T]', raw_form_type)
if (a):
return a.group(1)
else:
... | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/parsing/filing.py/filing.get_form_type |
5,806 | def get_version(self):
try:
return self.version
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/parsing/filing.py/filing.get_version |
5,807 | def _return(value, old_agent_version):
ctx.returns(value)
# Due to bug in celery:
# https://github.com/celery/celery/issues/897
if os.name == 'nt' and old_agent_version.startswith('3.2'):
from celery import current_task
try:
from cloudify_agent.app import app
except _... | ImportError | dataset/ETHPy150Open cloudify-cosmo/cloudify-manager/resources/rest-service/cloudify/install_agent.py/_return |
5,808 | def _flatten(implements, include_None=0):
try:
r = implements.flattened()
except __HOLE__:
if implements is None:
r=()
else:
r = Declaration(implements).flattened()
if not include_None:
return r
r = list(r)
r.append(None)
return r | AttributeError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/zope/zope/interface/_flatten.py/_flatten |
5,809 | def post(self, request, *args, **kwargs):
offset = request.POST.get('offset', None)
if not offset:
return HttpResponse("No 'offset' parameter provided", status=400)
try:
offset = int(offset)
except __HOLE__:
return HttpResponse("Invalid 'offset' value... | ValueError | dataset/ETHPy150Open adamcharnock/django-tz-detect/tz_detect/views.py/SetOffsetView.post |
5,810 | def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('negate', node)
if value is not None:
if value in ('true', '1'):
self.negate = True
elif value in ('false', '0'):
self.negate = False
else:
... | ValueError | dataset/ETHPy150Open CybOXProject/python-cybox/cybox/bindings/cybox_core.py/ObservableType.buildAttributes |
5,811 | def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('units', node)
if value is not None:
self.units = value
value = find_attr_value_('trend', node)
if value is not None:
self.trend = value
value = find_attr_value_('rate', ... | ValueError | dataset/ETHPy150Open CybOXProject/python-cybox/cybox/bindings/cybox_core.py/FrequencyType.buildAttributes |
5,812 | def buildAttributes(self, node, attrs, already_processed):
value = find_attr_value_('timestamp', node)
if value is not None:
try:
self.timestamp = self.gds_parse_datetime(value, node, 'timestamp')
except ValueError as exp:
raise ValueError('Bad da... | ValueError | dataset/ETHPy150Open CybOXProject/python-cybox/cybox/bindings/cybox_core.py/ActionType.buildAttributes |
5,813 | def _readline_from_keyboard(self):
c=self.console
def nop(e):
pass
while 1:
self._update_line()
lbuf=self.l_buffer
log_sock("point:%d mark:%d selection_mark:%d"%(lbuf.point,lbuf.mark,lbuf.selection_mark))
try:
e... | KeyboardInterrupt | dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/pyreadline/modes/emacs.py/EmacsMode._readline_from_keyboard |
5,814 | def b16_slug_to_arguments(b16_slug):
"""
Raises B16DecodingFail exception on
"""
try:
url = b16decode(b16_slug.decode('utf-8'))
except BinaryError:
raise B16DecodingFail
except __HOLE__:
raise B16DecodingFail('Non-base16 digit found')
except AttributeError:
... | TypeError | dataset/ETHPy150Open pydanny/dj-spam/spam/utils.py/b16_slug_to_arguments |
5,815 | def get_app(defs, add_help=True):
"""Small wrapper function to returns an instance of :class:`Application`
which serves the objects in the defs. Usually this is called with return
value globals() from the module where the resources are defined. The
returned WSGI application will serve all subclasses of
... | TypeError | dataset/ETHPy150Open pneff/wsgiservice/wsgiservice/application.py/get_app |
5,816 | def tree_image(tree, fout=None):
try:
import pydot
import a_reliable_dot_rendering
except __HOLE__:
return None
dot_data = StringIO()
export_graphviz(tree, out_file=dot_data)
data = re.sub(r"gini = 0\.[0-9]+\\n", "", dot_data.getvalue())
data = re.sub(r"samples = [0-9]+\\... | ImportError | dataset/ETHPy150Open amueller/nyu_ml_lectures/plots/plot_interactive_tree.py/tree_image |
5,817 | def get_parser():
p = Parser()
try:
os.mkdir("/tmp/Test Dir")
except __HOLE__:
pass # dir exists
open("/tmp/Test Dir/test.txt", "w").close()
return p | OSError | dataset/ETHPy150Open Calysto/metakernel/metakernel/tests/test_parser.py/get_parser |
5,818 | @permission_required("core.manage_shop")
def manage_delivery_times(request):
"""Dispatches to the first delivery time or to the form to add a delivery
time (if there is no delivery time yet).
"""
try:
delivery_time = DeliveryTime.objects.all()[0]
url = reverse("lfs_manage_delivery_time",... | IndexError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/manage/delivery_times/views.py/manage_delivery_times |
5,819 | def get_product_delivery_time(request, product, for_cart=False):
"""Returns the delivery time object for the product.
If the ``for_cart`` parameter is False, the default delivery time for
product is calculated. This is at the moment the first valid (iow with the
hightest priority) shipping method.
... | AttributeError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/shipping/utils.py/get_product_delivery_time |
5,820 | def search_notemodel(self, note_model):
content_words = note_model.wordset
try:
content_tags = note_model.metadata['tags']
except (__HOLE__, TypeError):
content_tags = ''
has_tag_filters = len(self.use_tags + self.ignore_tags) > 0 # are there tags in the search ... | KeyError | dataset/ETHPy150Open akehrer/Motome/Motome/Models/Search.py/SearchModel.search_notemodel |
5,821 | def remove_settings(self, filename, is_dir=False):
test_dir = os.path.dirname(os.path.dirname(__file__))
full_name = os.path.join(test_dir, filename)
if is_dir:
shutil.rmtree(full_name)
else:
os.remove(full_name)
# Also try to remove the compiled file; if... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/admin_scripts/tests.py/AdminScriptTestCase.remove_settings |
5,822 | def run_test(self, script, args, settings_file=None, apps=None):
test_dir = os.path.dirname(os.path.dirname(__file__))
project_dir = os.path.dirname(test_dir)
base_dir = os.path.dirname(project_dir)
ext_backend_base_dirs = self._ext_backend_paths()
# Remember the old environment... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/tests/regressiontests/admin_scripts/tests.py/AdminScriptTestCase.run_test |
5,823 | def setup_labels(self, size=None, color=None, shadow=None):
"""Sets up coordinates for labels wrt SVG file (2D flatmap)"""
# Recursive call for multiple layers
if self.layer == 'multi_layer':
label_layers = []
for L in self.layer_names:
label_layers.append... | ValueError | dataset/ETHPy150Open gallantlab/pycortex/cortex/svgroi.py/ROIpack.setup_labels |
5,824 | def _parse_svg_pts(self, datastr):
data = list(_tokenize_path(datastr))
#data = data.replace(",", " ").split()
if data.pop(0).lower() != "m":
raise ValueError("Unknown path format")
#offset = np.array([float(x) for x in data[1].split(',')])
offset = np.array(map(float... | ValueError | dataset/ETHPy150Open gallantlab/pycortex/cortex/svgroi.py/ROI._parse_svg_pts |
5,825 | def scrub(svgfile):
"""Remove data layers from an svg object prior to rendering
Returns etree-parsed svg object
"""
svg = etree.parse(svgfile, parser=parser)
try:
rmnode = _find_layer(svg, "data")
rmnode.getparent().remove(rmnode)
except __HOLE__:
pass
svgtag = svg.g... | ValueError | dataset/ETHPy150Open gallantlab/pycortex/cortex/svgroi.py/scrub |
5,826 | def get_object_type(self, obj):
try:
return SupportedServices.get_name_for_model(obj.object_content_type.model_class())
except __HOLE__:
return '.'.join(obj.object_content_type.natural_key()) | AttributeError | dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/template/serializers.py/TemplateSerializer.get_object_type |
5,827 | def load_backend(path):
i = path.rfind('.')
module, attr = path[:i], path[i + 1:]
try:
mod = import_module(module)
except __HOLE__ as e:
raise ImproperlyConfigured('Error importing authentication backend %s: "%s"' % (path, e))
except ValueError:
raise ImproperlyConfigured('Er... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/auth/__init__.py/load_backend |
5,828 | def authenticate(**credentials):
"""
If the given credentials are valid, return a User object.
"""
for backend in get_backends():
try:
user = backend.authenticate(**credentials)
except __HOLE__:
# This backend doesn't accept these credentials as arguments. Try the... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/auth/__init__.py/authenticate |
5,829 | def get_user_model():
"Return the User model that is active in this project"
from django.conf import settings
from django.db.models import get_model
try:
app_label, model_name = settings.AUTH_USER_MODEL.split('.')
except __HOLE__:
raise ImproperlyConfigured("AUTH_USER_MODEL must be ... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/auth/__init__.py/get_user_model |
5,830 | def get_user(request):
from django.contrib.auth.models import AnonymousUser
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
except __HOLE__... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/auth/__init__.py/get_user |
5,831 | def get_matching_features(datasource, where_clause, page_number, include_geom):
'''
'''
layer, offset, count = datasource.GetLayer(0), (page_number - 1) * 25, 25
try:
layer.SetAttributeFilter(where_clause)
except __HOLE__, e:
raise QueryError('Bad where clause: ' + str(e))
... | RuntimeError | dataset/ETHPy150Open codeforamerica/US-Census-Area-API/geo.py/get_matching_features |
5,832 | def cut_tree(Z, n_clusters=None, height=None):
"""
Given a linkage matrix Z, return the cut tree.
Parameters
----------
Z : scipy.cluster.linkage array
The linkage matrix.
n_clusters : array_like, optional
Number of clusters in the tree at the cut point.
height : array_like,... | TypeError | dataset/ETHPy150Open scipy/scipy/scipy/cluster/hierarchy.py/cut_tree |
5,833 | def _plot_dendrogram(icoords, dcoords, ivl, p, n, mh, orientation,
no_labels, color_list, leaf_font_size=None,
leaf_rotation=None, contraction_marks=None,
ax=None, above_threshold_color='b'):
# Import matplotlib here so that it's not imported unless den... | ImportError | dataset/ETHPy150Open scipy/scipy/scipy/cluster/hierarchy.py/_plot_dendrogram |
5,834 | def save_as(self, version):
""""the save action for fusion environment
uses Fusions own python binding
"""
# set the extension to '.comp'
from stalker import Version
assert isinstance(version, Version)
# its a new version please update the paths
version.u... | OSError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/fusion/__init__.py/Fusion.save_as |
5,835 | def get_version_from_recent_files(self):
"""It will try to create a
:class:`~oyProjectManager.models.version.Version` instance by looking
at the recent files list.
It will return None if it can not find one.
:return: :class:`~oyProjectManager.models.version.Version`
"""... | KeyError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/fusion/__init__.py/Fusion.get_version_from_recent_files |
5,836 | def create_main_saver_node(self, version):
"""Creates the default saver node if there is no created before.
Creates the default saver nodes if there isn't any existing outputs,
and updates the ones that is already created
"""
def output_path_generator(file_format):
... | OSError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/fusion/__init__.py/Fusion.create_main_saver_node |
5,837 | def import_from_string(val, setting_name):
"""
Attempt to import a class from a string representation.
"""
try:
parts = val.split('.')
module_path, class_name = '.'.join(parts[:-1]), parts[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name... | ImportError | dataset/ETHPy150Open ankitpopli1891/django-autotranslate/autotranslate/utils.py/import_from_string |
5,838 | def __init__(self, app, conf, logger=None):
self.app = app
self.conf = conf
self.logger = logger or get_logger(conf, log_route='container_sync')
self.realms_conf = ContainerSyncRealms(
os.path.join(
conf.get('swift_dir', '/etc/swift'),
'contain... | ValueError | dataset/ETHPy150Open openstack/swift/swift/common/middleware/container_sync.py/ContainerSync.__init__ |
5,839 | def register_info(self):
dct = {}
for realm in self.realms_conf.realms():
clusters = self.realms_conf.clusters(realm)
if clusters:
dct[realm] = {'clusters': dict((c, {}) for c in clusters)}
if self.realm and self.cluster:
try:
d... | KeyError | dataset/ETHPy150Open openstack/swift/swift/common/middleware/container_sync.py/ContainerSync.register_info |
5,840 | def _load_output(output_dir, func_name, timestamp=None, metadata=None,
mmap_mode=None, verbose=0):
"""Load output of a computation."""
if verbose > 1:
signature = ""
try:
if metadata is not None:
args = ", ".join(['%s=%s' % (name, value)
... | KeyError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/memory.py/_load_output |
5,841 | def _write_func_code(self, filename, func_code, first_line):
""" Write the function code and the filename to a file.
"""
# We store the first line because the filename and the function
# name is not always enough to identify a function: people
# sometimes have several functions n... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/memory.py/MemorizedFunc._write_func_code |
5,842 | def _check_previous_func_code(self, stacklevel=2):
"""
stacklevel is the depth a which this function is called, to
issue useful warnings to the user.
"""
# First check if our function is in the in-memory store.
# Using the in-memory store not only makes things fas... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/memory.py/MemorizedFunc._check_previous_func_code |
5,843 | def _persist_output(self, output, dir):
""" Persist the given output tuple in the directory.
"""
try:
mkdirp(dir)
filename = os.path.join(dir, 'output.pkl')
numpy_pickle.dump(output, filename, compress=self.compress)
if self._verbose > 10:
... | OSError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/memory.py/MemorizedFunc._persist_output |
5,844 | def updateMessages(self, parameters):
"""Modify the messages created by internal validation for each tool
parameter. This method is called after internal validation."""
input_parameter = parameters[0]
variable_parameter = parameters[1]
dimension_parameter = parameters[2]
... | RuntimeError | dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/get_variable_statistics_over_dimension.py/GetVariableStatisticsOverDimension.updateMessages |
5,845 | def execute(self, parameters, messages):
"""The source code of the tool."""
input_parameter = parameters[0]
variable_parameter = parameters[1]
dimension_parameter = parameters[2]
output_parameter = parameters[3]
output_var_parameter = parameters[4]
type_parameter... | RuntimeError | dataset/ETHPy150Open Esri/solutions-geoprocessing-toolbox/suitability/toolboxes/scripts/MultidimensionSupplementalTools/MultidimensionSupplementalTools/Scripts/mds/tools/get_variable_statistics_over_dimension.py/GetVariableStatisticsOverDimension.execute |
5,846 | def _parse_range_header(range_header):
"""Parse HTTP Range header.
Args:
range_header: A str representing the value of a range header as retrived
from Range or X-AppEngine-BlobRange.
Returns:
Tuple (start, end):
start: Start index of blob to retrieve. May be negative index.
end: None ... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/blob_download.py/_parse_range_header |
5,847 | def authenticate(self, **credentials):
User = get_user_model()
try:
lookup_kwargs = get_user_lookup_kwargs({
"{username}__iexact": credentials["username"]
})
user = User.objects.get(**lookup_kwargs)
except (User.DoesNotExist, __HOLE__):
... | KeyError | dataset/ETHPy150Open pinax/django-user-accounts/account/auth_backends.py/UsernameAuthenticationBackend.authenticate |
5,848 | def authenticate(self, **credentials):
qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))
try:
email_address = qs.get(email__iexact=credentials["username"])
except (EmailAddress.DoesNotExist, KeyError):
return None
else:
user = email_... | KeyError | dataset/ETHPy150Open pinax/django-user-accounts/account/auth_backends.py/EmailAuthenticationBackend.authenticate |
5,849 | def testProbabilisticEncryptDecryptUnicodeString(self):
logging.debug('Running testProbabilisticEncryptDecryptUtf8String method.')
# test success with different plaintexts
for plaintext in (u'22', u'this is test string one', u'-1.3', u'5545',
u"""this is a longer test string that shoul... | ValueError | dataset/ETHPy150Open google/encrypted-bigquery-client/src/ebq_crypto_test.py/ProbabilisticCiphertTest.testProbabilisticEncryptDecryptUnicodeString |
5,850 | def testPseudonymEncryptDecryptUnicodeString(self):
logging.debug('Running testPseudonymEncryptDecryptUtf8String method.')
# test success with different plaintexts
for plaintext in (u'22', u'this is test string one', u'-1.3', u'5545',
u"""this is a longer test string that should go on ... | ValueError | dataset/ETHPy150Open google/encrypted-bigquery-client/src/ebq_crypto_test.py/PseudonymCiphertTest.testPseudonymEncryptDecryptUnicodeString |
5,851 | def testHomomorphicEncryptIntDecryptInt(self):
logging.debug('Running testHomomorphicEncryptIntDecryptInt method.')
# test success with different plaintexts
for plaintext in (2, 5, 55, 333333333, 44444444444):
ciphertext = self.cipher.Encrypt(plaintext)
self.assertEqual(plaintext, self.cipher.De... | ValueError | dataset/ETHPy150Open google/encrypted-bigquery-client/src/ebq_crypto_test.py/HomomorphicIntCiphertTest.testHomomorphicEncryptIntDecryptInt |
5,852 | def testHomomorphicEncryptFloatDecryptFloat(self):
logging.debug('Running testHomomorphicEncryptFloatDecryptFloat method.')
# test success with different plaintexts
for plaintext in (1.22, 0.4565, 55.45, 33.3333333, 444444444.44):
ciphertext = self.cipher.Encrypt(plaintext)
self.assertEqual(plai... | ValueError | dataset/ETHPy150Open google/encrypted-bigquery-client/src/ebq_crypto_test.py/HomomorphicFloatCipherTest.testHomomorphicEncryptFloatDecryptFloat |
5,853 | def build_image():
openstack_client = init()
flavor_name = cfg.CONF.flavor_name
image_name = cfg.CONF.image_name
if nova.does_flavor_exist(openstack_client.nova, flavor_name):
LOG.info('Using existing flavor: %s', flavor_name)
else:
try:
nova.create_flavor(openstack_clie... | IOError | dataset/ETHPy150Open openstack/shaker/shaker/engine/image_builder.py/build_image |
5,854 | def xss_strip_all_tags(s):
"""
Strips out all HTML.
"""
return s
def fixup(m):
text = m.group(0)
if text[:1] == "<":
return "" # ignore tags
if text[:2] == "&#":
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1... | ValueError | dataset/ETHPy150Open benadida/helios-server/helios/utils.py/xss_strip_all_tags |
5,855 | @staticmethod
def is_reg(name):
try:
return name.upper() in x86_regs + x86_16bits_regs
except __HOLE__: # Not a string
return False | AttributeError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/X86.is_reg |
5,856 | def mem(data):
"""Parse a memory access string of format ``[EXPR]`` or ``seg:[EXPR]``
``EXPR`` may describe: ``BASE | INDEX * SCALE | DISPLACEMENT`` or any combinaison (in this order)
"""
if not isinstance(data, str):
raise TypeError("mem need a string to parse")
data = data.strip()
... | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/mem |
5,857 | def accept_arg(self, args, instr_state):
x = args[0]
try:
return (1, self.reg_opcode[x.upper()])
except (KeyError, __HOLE__):
return (None, None) | AttributeError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/X86RegisterSelector.accept_arg |
5,858 | def accept_arg(self, args, instr_state):
try:
x = int(args[0])
except (__HOLE__, TypeError):
return (None, None)
try:
imm8 = accept_as_8immediat(x)
except ImmediatOverflow:
return None, None
return (1, BitArray.from_string(imm8)) | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/Imm8.accept_arg |
5,859 | def accept_arg(self, args, instr_state):
try:
x = int(args[0])
except (__HOLE__, TypeError):
return (None, None)
try:
imm16 = accept_as_16immediat(x)
except ImmediatOverflow:
return None, None
return (1, BitArray.from_string(imm16)) | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/Imm16.accept_arg |
5,860 | def accept_arg(self, args, instr_state):
try:
x = int(args[0])
except (__HOLE__, TypeError):
return (None, None)
try:
imm32 = accept_as_32immediat(x)
except ImmediatOverflow:
return None, None
return (1, BitArray.from_string(imm32)) | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/Imm32.accept_arg |
5,861 | def accept_arg(self, args, instr_state):
writecr = self.writecr
if len(args) < 2:
return None, None
reg = args[writecr]
cr = args[not writecr]
if not isinstance(cr, str):
return None, None
if not cr.lower().startswith("cr"):
return None... | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/ControlRegisterModRM.accept_arg |
5,862 | def accept_arg(self, args, instr_state):
try:
jump_size = int(args[0])
except (__HOLE__, TypeError):
return (None, None)
jump_size -= self.sub
try:
jmp_imm = self.accept_as_Ximmediat(jump_size)
except ImmediatOverflow:
return (None,... | ValueError | dataset/ETHPy150Open hakril/PythonForWindows/windows/native_exec/simple_x86.py/JmpImm.accept_arg |
5,863 | def update_metaconfig(metaconfig_name, *args, **kwargs):
zk_value, version = _kazoo_client(ZK_HOSTS).get(
METACONFIG_ZK_PATH_FORMAT.format(metaconfig_name))
s3_key = METACONFIG_S3_KEY_FORMAT.format(metaconfig_name)
s3_path = zk_util.construct_s3_path(s3_key, zk_value)
try:
metaconfig_dat... | ValueError | dataset/ETHPy150Open pinterest/kingpin/kingpin/zk_update_monitor/zk_update_monitor.py/update_metaconfig |
5,864 | def _safe(self, fn):
try:
fn()
except (__HOLE__, KeyboardInterrupt):
raise
except Exception as e:
warnings.warn(
"testing_reaper couldn't "
"rollback/close connection: %s" % e) | SystemExit | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/engines.py/ConnectionKiller._safe |
5,865 | def _safe(self, fn):
try:
fn()
except (__HOLE__, KeyboardInterrupt):
raise
except Exception as e:
warnings.warn(
"ReconnectFixture couldn't "
"close connection: %s" % e) | SystemExit | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/engines.py/ReconnectFixture._safe |
5,866 | def __getattribute__(self, key):
try:
return object.__getattribute__(self, key)
except __HOLE__:
pass
subject, buffer = [object.__getattribute__(self, x)
for x in ('_subject', '_buffer')]
try:
... | AttributeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/engines.py/ReplayableSession.Recorder.__getattribute__ |
5,867 | def __getattribute__(self, key):
try:
return object.__getattribute__(self, key)
except __HOLE__:
pass
buffer = object.__getattribute__(self, '_buffer')
result = buffer.popleft()
if result is ReplayableSession.Callable:
... | AttributeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/testing/engines.py/ReplayableSession.Player.__getattribute__ |
5,868 | def decode(path):
if isinstance(path, bytes_cls):
try:
path = path.decode(fs_encoding, 'strict')
except __HOLE__:
if not platform.is_linux():
raise
path = path.decode(fs_fallback_encoding, 'strict')
return path | UnicodeDecodeError | dataset/ETHPy150Open ppalex7/SourcePawnCompletions/watchdog/utils/unicode_paths.py/decode |
5,869 | def DeleteById(self, sid):
"""Delete session data for a session id.
Args:
sid: str, session id
"""
try:
del self._sessions[sid]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/AuthSessionDict.DeleteById |
5,870 | def _LoadKey(self, keystr):
"""Load a key and return a key object.
Args:
keystr: str, key in PEM format
Returns:
tlslite.utils.RSAKey instance
Raises:
ValueError: keystr is improperly formed
"""
try:
key = tlslite_bridge.parsePEMKey(keystr)
except (SyntaxError, __HOL... | AttributeError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/Auth1._LoadKey |
5,871 | def VerifyCertSignedByCA(self, cert):
"""Verify that a client cert was signed by the required CA cert.
Args:
cert: certificate object, client cert to verify
Returns:
True or False
"""
ca_cert = self.LoadOtherCert(self._ca_pem)
try:
return cert.IsSignedBy(ca_cert)
except (x... | AssertionError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/Auth1.VerifyCertSignedByCA |
5,872 | def VerifyDataSignedWithCert(self, data, signature, cert=None):
"""Verify that this cert signed this data.
Args:
data: str, data to verify signing
signature: str, signature data
cert: certificate object, or None for this instance's cert
Returns:
True or False
Raises:
Crypt... | AssertionError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/Auth1.VerifyDataSignedWithCert |
5,873 | def Input(self, n=None, m=None, s=None): # pylint: disable=arguments-differ
"""Input parameters to the auth function.
Callers should provide n, OR m and s.
Args:
n: str, nonce from client, an integer in str form e.g. '12345'
m: str, message from client
s: str, b64 signature from client
... | TypeError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/Auth1.Input |
5,874 | def Input(self, m=None, t=None): # pylint: disable=arguments-differ
"""Accept input to auth methods.
Callers should provide either m OR t, or neither, but not both.
Args:
m: str, message from server (cn, sn, signature)
t: str, token reply from server
Raises:
ValueError: if invalid c... | ValueError | dataset/ETHPy150Open google/simian/src/simian/auth/base.py/Auth1Client.Input |
5,875 | def parser(chunks):
"""
Parse a data chunk into a dictionary; catch failures and return suitable
defaults
"""
dictionaries = []
for chunk in chunks:
try:
dictionaries.append(json.loads(chunk))
except __HOLE__:
dictionaries.append({
'unpars... | ValueError | dataset/ETHPy150Open jomido/jogger/jogger/jogger.py/parser |
5,876 | def _where(self, *comparators, **comparator):
def by_schema(self, schema):
log = self[:]
to_remove = set()
for line in log:
if not isinstance(line, collections.Mapping):
try:
d = line.__dict__
... | AttributeError | dataset/ETHPy150Open jomido/jogger/jogger/jogger.py/APIMixin._where |
5,877 | def run(self):
self.log.info('ListenerThread started on {0}:{1}(udp)'.format(
self.host, self.port))
rdr = collectd_network.Reader(self.host, self.port)
try:
while ALIVE:
try:
items = rdr.interpret(poll_interval=self.poll_interval)
... | ValueError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/jcollectd/jcollectd.py/ListenerThread.run |
5,878 | def handle(self, *args, **options):
try:
from celery.task.control import broadcast
except __HOLE__:
raise CommandError("Celery is not currently installed.")
# Shut them all down.
broadcast("shutdown") | ImportError | dataset/ETHPy150Open duointeractive/django-fabtastic/fabtastic/management/commands/ft_celeryd_restart.py/Command.handle |
5,879 | def show_current(name):
'''
Display the current highest-priority alternative for a given alternatives
link
CLI Example:
.. code-block:: bash
salt '*' alternatives.show_current editor
'''
alt_link_path = '/etc/alternatives/{0}'.format(name)
try:
return os.readlink(alt_l... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/alternatives.py/show_current |
5,880 | def run(self):
"""Include a file as part of the content of this reST file."""
if not self.state.document.settings.file_insertion_enabled:
raise self.warning('"%s" directive disabled.' % self.name)
source = self.state_machine.input_lines.source(
self.lineno - self.state_ma... | IOError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Include.run |
5,881 | def run(self):
if (not self.state.document.settings.raw_enabled
or (not self.state.document.settings.file_insertion_enabled
and ('file' in self.options
or 'url' in self.options))):
raise self.warning('"%s" directive disabled.' % self.name)
att... | IOError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Raw.run |
5,882 | def run(self):
if not isinstance(self.state, states.SubstitutionDef):
raise self.error(
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
substitution_definition = self.state_machine.node
if 'trim'... | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Unicode.run |
5,883 | def run(self):
try:
class_value = directives.class_option(self.arguments[0])
except __HOLE__:
raise self.error(
'Invalid class attribute value for "%s" directive: "%s".'
% (self.name, self.arguments[0]))
node_list = []
if self.conte... | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Class.run |
5,884 | def run(self):
"""Dynamically create and register a custom interpreted text role."""
if self.content_offset > self.lineno or not self.content:
raise self.error('"%s" directive requires arguments on the first '
'line.' % self.name)
args = self.content[0]
... | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Role.run |
5,885 | def run(self):
if not isinstance(self.state, states.SubstitutionDef):
raise self.error(
'Invalid context: the "%s" directive can only be used within '
'a substitution definition.' % self.name)
format_str = '\n'.join(self.content) or '%Y-%m-%d'
if sys.v... | UnicodeDecodeError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/docutils/parsers/rst/directives/misc.py/Date.run |
5,886 | def get_node(self, k):
try:
db = self.nodeDB
except AttributeError:
return k
else:
try:
return db[k]
except __HOLE__:
db[k] = Node(k)
return db[k] | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Query_Test.get_node |
5,887 | def node_graph(self, g):
try:
db = self.nodeDB
except __HOLE__:
return g
out = {}
for k, e in g.items():
k = self.get_node(k)
d = out.setdefault(k, {})
for dest, edge in e.items():
d[self.get_node(dest)] = edge
... | AttributeError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Query_Test.node_graph |
5,888 | def node_list(self, l):
try:
db = self.nodeDB
except __HOLE__:
return l
out = []
for k in l:
out.append(self.get_node(k))
return out | AttributeError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Query_Test.node_list |
5,889 | def node_result(self, r):
try:
db = self.nodeDB
except __HOLE__:
return r
l = []
for d in r:
d2 = {}
for k, v in d.items():
d2[k] = self.get_node(v)
l.append(d2)
return l | AttributeError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Query_Test.node_result |
5,890 | def update_graph(self, datagraph):
try:
g = self.datagraph
except __HOLE__:
return datagraph
else:
g.update(datagraph)
return g | AttributeError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Query_Test.update_graph |
5,891 | def test_delraise(self):
"Delete raise"
datagraph = self.datagraph
datagraph += self.get_node(1)
datagraph += self.get_node(2)
datagraph[self.get_node(2)] += self.get_node(3)
try:
for i in range(0, 2):
datagraph -= self.get_node(3)
... | KeyError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Mapping_Test.test_delraise |
5,892 | def test_setitemraise(self):
"Setitemraise"
datagraph = self.datagraph
datagraph += self.get_node(1)
try:
datagraph[self.get_node(1)] = self.get_node(2)
raise KeyError('failed to catch bad setitem attempt')
except __HOLE__:
pass # THIS IS THE C... | ValueError | dataset/ETHPy150Open cjlee112/pygr/tests/graph_test.py/Mapping_Test.test_setitemraise |
5,893 | def clean(self, value):
from ca_provinces import PROVINCES_NORMALIZED
super(CAProvinceField, self).clean(value)
if value in EMPTY_VALUES:
return u''
try:
value = value.strip().lower()
except __HOLE__:
pass
else:
try:
... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/localflavor/ca/forms.py/CAProvinceField.clean |
5,894 | def main(args=None):
try:
if args is None:
args = sys.argv[1:]
SenlinShell().main(args)
except __HOLE__:
print(_("... terminating senlin client"), file=sys.stderr)
sys.exit(130)
except Exception as e:
if '--debug' in args or '-d' in args:
rais... | KeyboardInterrupt | dataset/ETHPy150Open openstack/python-senlinclient/senlinclient/shell.py/main |
5,895 | def _calculate(self, data):
x = data.pop('x')
fun = self.params['fun']
n = self.params['n']
args = self.params['args']
if not hasattr(fun, '__call__'):
raise GgplotError("stat_function requires parameter 'fun' to be " +
"a function or any ... | KeyError | dataset/ETHPy150Open yhat/ggplot/ggplot/stats/stat_function.py/stat_function._calculate |
5,896 | def configure(self):
"""
Configure the driver to use the stored configuration options
Any store that needs special configuration should implement
this method. If the store was not able to successfully configure
itself, it should raise `exception.BadDriverConfiguration`
""... | IOError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/image_cache/drivers/xattr.py/Driver.configure |
5,897 | def get_xattr(path, key, **kwargs):
"""Return the value for a particular xattr
If the key doesn't not exist, or xattrs aren't supported by the file
system then a KeyError will be raised, that is, unless you specify a
default using kwargs.
"""
namespaced_key = _make_namespaced_xattr_key(key)
... | KeyError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/image_cache/drivers/xattr.py/get_xattr |
5,898 | def test_abs__file__(self):
# Make sure all imported modules have their __file__ attribute
# as an absolute path.
# Handled by abs__file__()
site.abs__file__()
for module in (sys, os, __builtin__):
try:
self.assertTrue(os.path.isabs(module.__file__), r... | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_site.py/ImportSideEffectTests.test_abs__file__ |
5,899 | def test_sitecustomize_executed(self):
# If sitecustomize is available, it should have been imported.
if "sitecustomize" not in sys.modules:
try:
import sitecustomize
except __HOLE__:
pass
else:
self.fail("sitecustomize ... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_site.py/ImportSideEffectTests.test_sitecustomize_executed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.