Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
2,100 | def get_sections(self):
SECTION_DIVIDER = '\f\n'
sections = self.data.split(SECTION_DIVIDER)
sections = [x for x in map(str.splitlines, sections)]
try:
# remove the SVN version number from the first line
svn_version = int(sections[0].pop(0))
if not svn... | ValueError | dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/setuptools/svn_utils.py/SVNEntriesFileText.get_sections |
2,101 | def readme():
try:
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
except __HOLE__:
return '' | IOError | dataset/ETHPy150Open vlasovskikh/convoread/setup.py/readme |
2,102 | def archive_month(request, year, month, queryset, date_field, allow_future=False, month_format='%b', **kwargs):
try:
date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3])
except __HOLE__:
raise Http404
now = datetime.datetime.now()
# Calculate first and last day of... | ValueError | dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_month |
2,103 | def archive_week(request, year, week, queryset, date_field, allow_future=False, **kwargs):
try:
date = datetime.date(*time.strptime(year+'-0-'+week, '%Y-%w-%U')[:3])
except __HOLE__:
raise Http404
now = datetime.datetime.now()
# Calculate first and last day of week, for use in ... | ValueError | dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_week |
2,104 | def archive_day(request, year, month, day, queryset, date_field, allow_future=False, month_format='%b', day_format='%d', **kwargs):
try:
date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
except __HOLE__:
raise Http404
model = queryset.model
now =... | ValueError | dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_day |
2,105 | def object_detail(request, year, month, day, queryset, date_field, allow_future=False, month_format='%b', day_format='%d', **kwargs):
try:
date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3])
except __HOLE__:
raise Http404
model = queryset.model
now... | ValueError | dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/object_detail |
2,106 | def checkout(self, url, version='', verbose=False,
shallow=False, timeout=None):
if url is None or url.strip() == '':
raise ValueError('Invalid empty url : "%s"' % url)
# make sure that the parent directory exists for #3497
base_path = os.path.split(self.get_path())[... | OSError | dataset/ETHPy150Open vcstools/vcstools/src/vcstools/hg.py/HgClient.checkout |
2,107 | def run(self, info):
""" Set extended attributes on downloaded file (if xattr support is found). """
# This mess below finds the best xattr tool for the job and creates a
# "write_xattr" function.
try:
# try the pyxattr module...
import xattr
def wri... | OSError | dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/postprocessor/xattrpp.py/XAttrMetadataPP.run |
2,108 | def get_devices(self):
try:
return [IPDevice(iface) for iface in netifaces.interfaces()]
except (__HOLE__, MemoryError):
LOG.error(_LE("Failed to get network interfaces."))
return [] | OSError | dataset/ETHPy150Open openstack/neutron/neutron/agent/windows/ip_lib.py/IPWrapper.get_devices |
2,109 | def device_has_ip(self, ip):
try:
device_addresses = netifaces.ifaddresses(self.device_name)
except __HOLE__: # The device does not exist on the system
return False
try:
addresses = [ip_addr['addr'] for ip_addr in
device_addresses.ge... | ValueError | dataset/ETHPy150Open openstack/neutron/neutron/agent/windows/ip_lib.py/IPDevice.device_has_ip |
2,110 | def _validate_recaptcha(self, response, remote_addr):
"""Performs the actual validation."""
try:
private_key = current_app.config['RECAPTCHA_PRIVATE_KEY']
except __HOLE__:
raise RuntimeError("No RECAPTCHA_PRIVATE_KEY config set")
data = url_encode({
'... | KeyError | dataset/ETHPy150Open lepture/flask-wtf/flask_wtf/recaptcha/validators.py/Recaptcha._validate_recaptcha |
2,111 | def perspectiveMessageReceived(self, broker, message, args, kw):
"""
This method is called when a network message is received.
This will call::
self.perspective_%(message)s(*broker.unserialize(args),
**broker.unserialize(kw))
to han... | TypeError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/spread/pb.py/Avatar.perspectiveMessageReceived |
2,112 | def dontNotifyOnDisconnect(self, notifier):
"""Remove a callback from list of disconnect callbacks."""
try:
self.disconnects.remove(notifier)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/spread/pb.py/Broker.dontNotifyOnDisconnect |
2,113 | def validate_options(options):
"""Validates options."""
kwcase = options.get('keyword_case', None)
if kwcase not in [None, 'upper', 'lower', 'capitalize']:
raise SQLParseError('Invalid value for keyword_case: %r' % kwcase)
idcase = options.get('identifier_case', None)
if idcase not in [None... | ValueError | dataset/ETHPy150Open andialbrecht/sqlparse/sqlparse/formatter.py/validate_options |
2,114 | def main():
import os.path
import argparse
from argparse import ArgumentParser
opener = URLOpener()
def get_spec(value):
if value not in SPECS:
raise argparse.ArgumentTypeError('Unknown specification')
spec_cls = SPECS[value]
if os.path.exists(value + '.xml'):... | IOError | dataset/ETHPy150Open Dav1dde/glad/glad/__main__.py/main |
2,115 | def get(self, key, default=None):
try:
return self[key]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/Mapping.get |
2,116 | def __contains__(self, key):
try:
self[key]
except __HOLE__:
return False
else:
return True | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/Mapping.__contains__ |
2,117 | def pop(self, key, default=__marker):
try:
value = self[key]
except __HOLE__:
if default is self.__marker:
raise
return default
else:
del self[key]
return value | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.pop |
2,118 | def popitem(self):
try:
key = next(iter(self))
except __HOLE__:
raise KeyError
value = self[key]
del self[key]
return key, value | StopIteration | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.popitem |
2,119 | def clear(self):
try:
while True:
self.popitem()
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.clear |
2,120 | def setdefault(self, key, default=None):
try:
return self[key]
except __HOLE__:
self[key] = default
return default | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.setdefault |
2,121 | def extend(self, elem_seq):
"""Extends by appending the given iterable. Similar to list.extend()."""
if elem_seq is None:
return
try:
elem_seq_iter = iter(elem_seq)
except __HOLE__:
if not elem_seq:
# silently ignore falsy inputs :-/.
# TODO(ptucker): Deprecate this be... | TypeError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/RepeatedScalarFieldContainer.extend |
2,122 | def __getitem__(self, key):
try:
return self._values[key]
except __HOLE__:
key = self._key_checker.CheckValue(key)
val = self._value_checker.DefaultValue()
self._values[key] = val
return val | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/ScalarMap.__getitem__ |
2,123 | def __getitem__(self, key):
try:
return self._values[key]
except __HOLE__:
key = self._key_checker.CheckValue(key)
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
self._values[key] = new_element
self._message_listener.... | KeyError | dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MessageMap.__getitem__ |
2,124 | def peek(self, index=0):
try:
return self.buffer[self.pointer + index]
except __HOLE__:
self.update(index + 1)
return self.buffer[self.pointer + index] | IndexError | dataset/ETHPy150Open powerline/powerline/powerline/lint/markedjson/reader.py/Reader.peek |
2,125 | def update(self, length):
if self.raw_buffer is None:
return
self.buffer = self.buffer[self.pointer:]
self.pointer = 0
while len(self.buffer) < length:
if not self.eof:
self.update_raw()
try:
data, converted = self.raw_decode(self.raw_buffer, 'strict', self.eof)
except __HOLE__ as exc:
c... | UnicodeDecodeError | dataset/ETHPy150Open powerline/powerline/powerline/lint/markedjson/reader.py/Reader.update |
2,126 | def StopDaemon(self, require_running=True):
"""Stops any currently running daemon process on the system."""
current_pid = self._get_current_pid()
if require_running and current_pid is None:
raise DaemonError('Daemon process was not running.')
try:
os.kill(current_pid, signal.SIGTERM)
ex... | OSError | dataset/ETHPy150Open viewfinderco/viewfinder/backend/base/daemon.py/DaemonManager.StopDaemon |
2,127 | def _get_current_pid(self):
"""Get the process ID of any currently running daemon process. Returns
None if no process is running.
"""
current_pid = None
if self.lockfile.is_locked():
current_pid = self.lockfile.read_pid()
if current_pid is not None:
try:
# A 0 signal w... | OSError | dataset/ETHPy150Open viewfinderco/viewfinder/backend/base/daemon.py/DaemonManager._get_current_pid |
2,128 | def forwards(self, orm):
"Write your forwards methods here."
try:
role = orm["auth.Group"].objects.get(name="Test Manager")
perm = orm["auth.Permission"].objects.get(codename="manage_products")
except __HOLE__:
pass
else:
role.permissions.a... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/moztrap/moztrap/model/core/migrations/0005_add_manage_products_permission_for_test_managers.py/Migration.forwards |
2,129 | def __init__(self, resp=None):
self.scope = []
self.token_expiration_time = 0
self.access_token = None
self.refresh_token = None
self.token_type = None
self.replaced = False
if resp:
for prop, val in resp.items():
setattr(self, prop, v... | KeyError | dataset/ETHPy150Open rohe/pyoidc/src/oic/oauth2/grant.py/Token.__init__ |
2,130 | def add_code(self, resp):
try:
self.code = resp["code"]
self.grant_expiration_time = utc_time_sans_frac() + self.exp_in
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open rohe/pyoidc/src/oic/oauth2/grant.py/Grant.add_code |
2,131 | def ParseArguments(argv):
"""Parses command-line arguments.
Args:
argv: Command-line arguments, including the executable name, used to
execute this application.
Returns:
Tuple (args, option_dict) where:
args: List of command-line arguments following the executable name.
option_dict: Di... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_main.py/ParseArguments |
2,132 | def main(argv):
"""Runs the development application server."""
args, option_dict = ParseArguments(argv)
if len(args) != 1:
print >>sys.stderr, 'Invalid arguments'
PrintUsageExit(1)
root_path = args[0]
if '_DEFAULT_ENV_AUTH_DOMAIN' in option_dict:
auth_domain = option_dict['_DEFAULT_ENV_AUTH_DOM... | KeyboardInterrupt | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_main.py/main |
2,133 | def handle_label(self, app_name, directory=None, **options):
if directory is None:
directory = os.getcwd()
# Determine the project_name by using the basename of directory,
# which should be the full path of the project directory (or the
# current directory if no directory wa... | ImportError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/management/commands/startapp.py/Command.handle_label |
2,134 | def get_index_tags(self, index, results, index_tags, column_tags):
'''
Gather the tags for this row of the table (index) based on the
results (all the results from the query).
index_tags and column_tags are the tags to gather.
- Those specified in index_tags contain the tag_grou... | KeyError | dataset/ETHPy150Open serverdensity/sd-agent/checks.d/snmp.py/SnmpCheck.get_index_tags |
2,135 | def stream_in(p, data):
"""
Streams to dat from the given command into python
Parameters
----------
cmd: str
the command to execute
parse: boolean
TODO: if true, will try to parse the output from python generator or list
"""
if isinstance(data, str):
data = data.encode()
stdout, stderr =... | ValueError | dataset/ETHPy150Open karissa/datpy/datpy.py/stream_in |
2,136 | def stream_out(p, parse=True):
"""
Streams the stdout from the given command into python
Parameters
----------
cmd: str
the command to execute
parse: boolean
to parse the file into json
"""
res = []
for line in iter(p.stdout.readline, b''):
try:
line = line.decode()
if parse:
... | UnicodeDecodeError | dataset/ETHPy150Open karissa/datpy/datpy.py/stream_out |
2,137 | @classmethod
def bench(cls, text, loops=1000):
print('Parsing the Markdown Syntax document %d times...' % loops)
for name, func in cls.suites:
try:
total = func(text, loops=loops)
print('{0}: {1}'.format(name, total))
except __HOLE__:
... | ImportError | dataset/ETHPy150Open MikeCoder/markdown-preview.vim/pythonx/tests/bench.py/benchmark.bench |
2,138 | def get_output(self, cmd):
try:
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
except (__HOLE__, EnvironmentError): # can't use FileNotFoundError in Python 2
return False
out, err = process.communicate()
return out | OSError | dataset/ETHPy150Open richrd/suplemon/suplemon/modules/system_clipboard.py/SystemClipboard.get_output |
2,139 | def _addressed(nick, msg, prefixChars=None, nicks=None,
prefixStrings=None, whenAddressedByNick=None,
whenAddressedByNickAtEnd=None):
def get(group):
if ircutils.isChannel(target):
group = group.get(target)
return group()
def stripPrefixStrings(payload):
... | ValueError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/_addressed |
2,140 | def tokenize(s, channel=None):
"""A utility function to create a Tokenizer and tokenize a string."""
pipe = False
brackets = ''
nested = conf.supybot.commands.nested
if nested():
brackets = conf.get(nested.brackets, channel)
if conf.get(nested.pipeSyntax, channel): # No nesting, no p... | ValueError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/tokenize |
2,141 | def checkCommandCapability(msg, cb, commandName):
if not isinstance(commandName, minisix.string_types):
commandName = '.'.join(commandName)
plugin = cb.name().lower()
pluginCommand = '%s.%s' % (plugin, commandName)
def checkCapability(capability):
assert ircdb.isAntiCapability(capability... | RuntimeError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/checkCommandCapability |
2,142 | def errorNoCapability(self, capability, s='', **kwargs):
if 'Raise' not in kwargs:
kwargs['Raise'] = True
log.warning('Denying %s for lacking %q capability.',
self.msg.prefix, capability)
# noCapability means "don't send a specific capability error
# messa... | TypeError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/RichReplyMethods.errorNoCapability |
2,143 | def errorNoUser(self, s='', name='that user', **kwargs):
if 'Raise' not in kwargs:
kwargs['Raise'] = True
v = self._getConfig(conf.supybot.replies.noUser)
try:
v = v % name
except __HOLE__:
log.warning('supybot.replies.noUser should have one "%s" in it... | TypeError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/RichReplyMethods.errorNoUser |
2,144 | def reply(self, s, noLengthCheck=False, prefixNick=None, action=None,
private=None, notice=None, to=None, msg=None, sendImmediately=False):
"""
Keyword arguments:
* `noLengthCheck=False`: True if the length shouldn't be checked
(used for 'more'... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/NestedCommandsIrcProxy.reply |
2,145 | def userValue(self, name, prefixOrName, default=None):
try:
id = str(ircdb.users.getUserId(prefixOrName))
except __HOLE__:
return None
plugin = self.name()
group = conf.users.plugins.get(plugin)
names = registry.split(name)
for name in names:
... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/PluginMixin.userValue |
2,146 | def setUserValue(self, name, prefixOrName, value,
ignoreNoUser=True, setValue=True):
try:
id = str(ircdb.users.getUserId(prefixOrName))
except __HOLE__:
if ignoreNoUser:
return
else:
raise
plugin = self.name... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/PluginMixin.setUserValue |
2,147 | def find_template(self, name, context, peeking=False):
"""
Replacement for Django's ``find_template`` that uses the current
template context to keep track of which template directories it
has used when finding a template. This allows multiple templates
with the same relative name... | AttributeError | dataset/ETHPy150Open stephenmcd/django-overextends/overextends/templatetags/overextends_tags.py/OverExtendsNode.find_template |
2,148 | def checkFilingDTS(val, modelDocument, isEFM, isGFM, visited):
global targetNamespaceDatePattern, efmFilenamePattern, htmlFileNamePattern, roleTypePattern, arcroleTypePattern, \
arcroleDefinitionPattern, namePattern, linkroleDefinitionBalanceIncomeSheet, \
namespacesConflictPattern
if ta... | ValueError | dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/validate/EFM/DTS.py/checkFilingDTS |
2,149 | def _validate_date_part(self, value):
daypart, monthpart, yearpart = int(value[:2]), int(value[2:4]), int(value[4:7])
if yearpart >= 800:
yearpart += 1000
else:
yearpart += 2000
try:
date = datetime.datetime(year = yearpart, month = monthpart, day = da... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/mk/forms.py/UMCNField._validate_date_part |
2,150 | def build_cipher(key, iv, alg="aes_128_cbc"):
"""
:param key: encryption key
:param iv: init vector
:param alg: cipher algorithm
:return: A Cipher instance
"""
typ, bits, cmode = alg.split("_")
if not iv:
iv = Random.new().read(AES.block_size)
else:
assert len(iv) ==... | KeyError | dataset/ETHPy150Open rohe/pyoidc/src/oic/utils/aes.py/build_cipher |
2,151 | def __new__(cls, meth, callback=None):
try:
obj = meth.__self__
func = meth.__func__
except __HOLE__:
raise TypeError("argument should be a bound method, not {}"
.format(type(meth)))
def _cb(arg):
... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/WeakMethod.__new__ |
2,152 | def __init__(self, fn):
try:
self._obj = ref(fn.im_self)
self._meth = fn.im_func
except __HOLE__:
# It's not a bound method.
self._obj = None
self._meth = fn | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/WeakMethod.__init__ |
2,153 | def __init__(self, parent, port, worker_class_or_function, args,
on_receive=None):
super(JsonTcpClient, self).__init__(parent)
self._port = port
self._worker = worker_class_or_function
self._args = args
self._header_complete = False
self._header_buf = by... | TypeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient.__init__ |
2,154 | def _on_disconnected(self):
try:
comm('disconnected from backend: %s:%d', self.peerName(),
self.peerPort())
except (AttributeError, RuntimeError):
# logger might be None if for some reason qt deletes the socket
# after python global exit
p... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._on_disconnected |
2,155 | def _read_header(self):
comm('reading header')
self._header_buf += self.read(4)
if len(self._header_buf) == 4:
self._header_complete = True
try:
header = struct.unpack('=I', self._header_buf)
except __HOLE__:
# pyside
... | TypeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._read_header |
2,156 | def _read_payload(self):
""" Reads the payload (=data) """
comm('reading payload data')
comm('remaining bytes to read: %d', self._to_read)
data_read = self.read(self._to_read)
nb_bytes_read = len(data_read)
comm('%d bytes read', nb_bytes_read)
self._data_buf += da... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._read_payload |
2,157 | def _on_process_finished(self, exit_code):
""" Logs process exit status """
comm('backend process finished with exit code %d', exit_code)
try:
self.running = False
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_finished |
2,158 | def _on_process_stdout_ready(self):
""" Logs process output """
if not self:
return
o = self.readAllStandardOutput()
try:
output = bytes(o).decode(self._encoding)
except __HOLE__:
output = bytes(o.data()).decode(self._encoding)
for line... | TypeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_stdout_ready |
2,159 | def _on_process_stderr_ready(self):
""" Logs process output (stderr) """
if not self:
return
o = self.readAllStandardError()
try:
output = bytes(o).decode(self._encoding)
except __HOLE__:
output = bytes(o.data()).decode(self._encoding)
... | TypeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_stderr_ready |
2,160 | @classmethod
def get_result(cls, request):
"""
Get the result (or None) of a transparent redirect given a Django
Request object.
>>> result = MyForm.get_result(request)
>>> if result.is_success:
take_some_action()
... | KeyError | dataset/ETHPy150Open danielgtaylor/braintree_django/django_braintree/forms.py/BraintreeForm.get_result |
2,161 | def construct_response(scenario_name):
# load up response data
data = json.load(open('scenario.cache','r'))
lookup = TemplateLookup(directories=['./scenarios'])
for path in glob2.glob('./scenarios/**/request.mako'):
if path != scenario_name:
continue
event_name = path.split(... | KeyError | dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/construct_response |
2,162 | def render_executables():
# load up scenario data
data = json.load(open('scenario.cache','r'))
lookup = TemplateLookup(directories=['./scenarios'])
for path in glob2.glob('./scenarios/**/request.mako'):
event_name = path.split('/')[-2]
template = Template(filename=path, lookup=lookup,)
... | KeyError | dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/render_executables |
2,163 | def fetch_scenario_cache():
try:
os.remove('scenario.cache')
except __HOLE__:
pass
with open('scenario.cache', 'wb') as fo:
response = requests.get(SCENARIO_CACHE_URL)
if not response.ok:
sys.exit()
for block in response.iter_content():
fo.wri... | OSError | dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/fetch_scenario_cache |
2,164 | def list_devices(self, number):
if number:
try:
number = number.strip()
number = int(number)
except __HOLE__:
text = '{} is not a number, now is it. You see, it needs to be.'.format(number)
return text
devices = self... | ValueError | dataset/ETHPy150Open serverdensity/sdbot/limbo/plugins/devices.py/Wrapper.list_devices |
2,165 | def load_sanders_data(dirname=".", line_count=-1):
count = 0
topics = []
labels = []
tweets = []
with open(os.path.join(DATA_DIR, dirname, "corpus.csv"), "r") as csvfile:
metareader = csv.reader(csvfile, delimiter=',', quotechar='"')
for line in metareader:
count += 1
... | IOError | dataset/ETHPy150Open luispedro/BuildingMachineLearningSystemsWithPython/ch06/utils.py/load_sanders_data |
2,166 | def getComponentByPosition(self, idx):
try:
return self._componentValues[idx]
except __HOLE__:
if idx < len(self._componentType):
return
raise | IndexError | dataset/ETHPy150Open kurrik/chrome-extensions/crx-appengine-packager/pyasn1/type/univ.py/SequenceAndSetBase.getComponentByPosition |
2,167 | def start(self):
"""Poet server control shell."""
debug.info('Entering control shell')
self.conn = PoetSocket(self.s.accept()[0])
print 'Welcome to posh, the Poet Shell!'
print 'Running `help\' will give you a list of supported commands.'
while True:
try:
... | KeyboardInterrupt | dataset/ETHPy150Open mossberg/poet/server.py/PoetServer.start |
2,168 | def drop_privs():
try:
new_uid = int(os.getenv('SUDO_UID'))
new_gid = int(os.getenv('SUDO_GID'))
except __HOLE__:
# they were running directly from a root user and didn't have
# sudo env variables
print """[!] WARNING: Couldn't drop privileges! To avoid this error, run fr... | TypeError | dataset/ETHPy150Open mossberg/poet/server.py/drop_privs |
2,169 | def main():
args = get_args()
if args.version:
print 'Poet version {}'.format(__version__)
sys.exit(0)
print_header()
PORT = int(args.port) if args.port else 443
try:
s = PoetSocketServer(PORT)
except socket.error as e:
if e.errno == 13:
die('You need ... | KeyboardInterrupt | dataset/ETHPy150Open mossberg/poet/server.py/main |
2,170 | @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/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._core_plugin |
2,171 | @classmethod
def _get_interface_info(cls, device_id, network_id, external=False):
if cls._device_network_interface_map is None:
cls._get_network_interface_map_from_config()
try:
dev_info = cls._device_network_interface_map[device_id]
if external:
r... | TypeError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._get_interface_info |
2,172 | @classmethod
def _get_network_interface_map_from_config(cls):
dni_dict = config.get_specific_config(
'HwVLANTrunkingPlugDriver'.lower())
temp = {}
for hd_uuid, kv_dict in dni_dict.items():
# ensure hd_uuid is properly formatted
hd_uuid = config.uuidify(hd_... | ValueError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._get_network_interface_map_from_config |
2,173 | def __get_yubico_users(username):
'''
Grab the YubiKey Client ID & Secret Key
'''
user = {}
try:
if __opts__['yubico_users'].get(username, None):
(user['id'], user['key']) = list(__opts__['yubico_users'][username].values())
else:
return None
except __HOLE... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/auth/yubico.py/__get_yubico_users |
2,174 | def main():
args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]),
version=const.VERSION)
logging.basicConfig(
level=logging.DEBUG if args['--verbose'] else logging.INFO,
stream=sys.stdout,
)
if len(args['<mail_uid>']) == 0:
args['<mail_uid>'] = sys.st... | KeyboardInterrupt | dataset/ETHPy150Open Gentux/imap-cli/imap_cli/fetch.py/main |
2,175 | def start_dev_appserver():
"""Starts the appengine dev_appserver program for the Django project.
The appserver is run with default parameters. If you need to pass any special
parameters to the dev_appserver you will have to invoke it manually.
"""
from google.appengine.tools import dev_appserver_main
progn... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/appengine_django/management/commands/runserver.py/start_dev_appserver |
2,176 | def RenderAjax(self, request, response):
"""Run the flow for granting access."""
approval_urn = rdfvalue.RDFURN(request.REQ.get("acl", "/"))
_, namespace, _ = approval_urn.Split(3)
if namespace == "hunts":
try:
_, _, hunt_id, user, reason = approval_urn.Split()
self.subject = rdfv... | TypeError | dataset/ETHPy150Open google/grr/grr/gui/plugins/acl_manager.py/GrantAccess.RenderAjax |
2,177 | def test13_range(self):
"""Checking ranges in table iterators (case13)"""
if common.verbose:
print('\n', '-=' * 30)
print("Running %s.test13_range..." % self.__class__.__name__)
# Case where step < 0
self.step = -11
try:
self.check_range()
... | ValueError | dataset/ETHPy150Open PyTables/PyTables/tables/tests/test_tablesMD.py/BasicRangeTestCase.test13_range |
2,178 | def to_xml(self, encoding = "iso-8859-1"):
try:
import cStringIO as StringIO
except __HOLE__:
import StringIO
f = StringIO.StringIO()
self.write_xml(f, encoding)
return f.getvalue() | ImportError | dataset/ETHPy150Open joeyb/joeyb-blog/externals/PyRSS2Gen.py/WriteXmlMixin.to_xml |
2,179 | def l10n_float(string):
"""Takes a country specfic decimal value as string and returns a float.
"""
# TODO: Implement a proper transformation with babel or similar
if settings.LANGUAGE_CODE == "de":
string = string.replace(",", ".")
try:
return float(string)
except __HOLE__:
... | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/l10n_float |
2,180 | def atof(value):
"""
locale.atof() on unicode string fails in some environments, like Czech.
"""
val = str(value)
try:
return float(val)
except ValueError:
try:
return float(val.replace(',', '.'))
except __HOLE__:
pass
if isinstance(value, uni... | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/atof |
2,181 | def get_default_shop(request=None):
"""Returns the default shop.
"""
from lfs.core.models import Shop
if request:
try:
return request.shop
except __HOLE__:
pass
try:
shop = Shop.objects.get(pk=1)
except Shop.DoesNotExist, e: # No guarantee that o... | AttributeError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_default_shop |
2,182 | def import_module(module):
"""Imports module with given dotted name.
"""
try:
module = sys.modules[module]
except __HOLE__:
__import__(module)
module = sys.modules[module]
return module | KeyError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/import_module |
2,183 | def get_start_day(date):
"""Takes a string such as ``2009-07-23`` and returns datetime object of
this day.
"""
try:
year, month, day = date.split("-")
start = datetime.datetime(int(year), int(month), int(day))
except __HOLE__:
return None
return start | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_start_day |
2,184 | def get_end_day(date):
"""Takes a string such as ``2009-07-23`` and returns a datetime object with
last valid second of this day: 23:59:59.
"""
try:
year, month, day = date.split("-")
except __HOLE__:
return None
end = datetime.datetime(int(year), int(month), int(day))
end = ... | ValueError | dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_end_day |
2,185 | def __call__(self, environ, start_response):
# initialize a session for the current user
_tls.current_session = Session(lifetime=self.lifetime, no_datastore=self.no_datastore, cookie_only_threshold=self.cookie_only_thresh, cookie_key=self.cookie_key)
# create a hook for us to insert a cookie in... | ValueError | dataset/ETHPy150Open rwl/muntjac/appengine_config.py/GaeSessionMiddleware.__call__ |
2,186 | def tearDown(self):
"""
Disconnect the player and observer from their respective transports.
"""
for p in self.player, self.observer:
try:
p.destroy()
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open twisted/imaginary/imaginary/test/commandutils.py/CommandTestCaseMixin.tearDown |
2,187 | @classmethod
def _vpn_connection_get_route_state(cls, vpn_connection_id,
destination_cidr_block=None):
try:
data = cls.client.describe_vpn_connections(
VpnConnectionIds=[vpn_connection_id])
try:
route = next(
... | StopIteration | dataset/ETHPy150Open openstack/ec2-api/ec2api/tests/functional/base.py/EC2TestCase._vpn_connection_get_route_state |
2,188 | def query(self, properties=None, filteriw=None, showalldb=None,
numberinggroup=None, inlanguagecode=None):
"""
General information about the site.
See `<https://www.mediawiki.org/wiki/API:Meta#siteinfo_.2F_si>`_
:Parameters:
properties: set(str)
... | KeyError | dataset/ETHPy150Open mediawiki-utilities/python-mediawiki-utilities/mw/api/collections/site_info.py/SiteInfo.query |
2,189 | def formfield_for_dbfield(self, db_field, **kwargs):
field = super(FilePickerAdmin, self).formfield_for_dbfield(
db_field, **kwargs)
if db_field.name in self.adminfiles_fields:
try:
field.widget.attrs['class'] += " adminfilespicker"
except __HOLE__:
... | KeyError | dataset/ETHPy150Open carljm/django-adminfiles/adminfiles/admin.py/FilePickerAdmin.formfield_for_dbfield |
2,190 | def get_form(self, *args, **kwargs):
initial = self.get_form_kwargs()
if 'ip_type' in self.request.GET and 'ip_str' in self.request.GET:
ip_str = self.request.GET['ip_str']
ip_type = self.request.GET['ip_type']
network = calc_parent_str(ip_str, ip_type)
if... | ObjectDoesNotExist | dataset/ETHPy150Open mozilla/inventory/mozdns/address_record/views.py/AddressRecordCreateView.get_form |
2,191 | def longestCommonPrefix(self, strs):
"""
O(k*n)
:param strs: a list of string
:return: string, prefix
"""
# checking, otherwise: ValueError: min() arg is an empty sequence
if not strs:
return ""
n = len(strs)
str_builder =... | IndexError | dataset/ETHPy150Open algorhythms/LeetCode/015 Longest Common Prefix.py/Solution.longestCommonPrefix |
2,192 | def authenticate(self, auth, stored_password):
if auth:
username = auth.username
client_password = auth.password
else:
username = ""
client_password = ""
if self.verify_password_callback:
return self.verify_password_callback(username, c... | TypeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/flask_httpauth.py/HTTPBasicAuth.authenticate |
2,193 | def __init__(self, scheme=None, realm=None, use_ha1_pw=False):
super(HTTPDigestAuth, self).__init__(scheme, realm)
self.use_ha1_pw = use_ha1_pw
self.random = SystemRandom()
try:
self.random.random()
except __HOLE__:
self.random = Random()
def _gen... | NotImplementedError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/flask_httpauth.py/HTTPDigestAuth.__init__ |
2,194 | def _pct_encoded_replace_unreserved(mo):
try:
i = int(mo.group(1), 16)
if _unreserved[i]:
return chr(i)
else:
return mo.group().upper()
except __HOLE__:
return mo.group() | ValueError | dataset/ETHPy150Open necaris/python3-openid/openid/urinorm.py/_pct_encoded_replace_unreserved |
2,195 | def _pct_encoded_replace(mo):
try:
return chr(int(mo.group(1), 16))
except __HOLE__:
return mo.group() | ValueError | dataset/ETHPy150Open necaris/python3-openid/openid/urinorm.py/_pct_encoded_replace |
2,196 | def runEventTransaction(self, player, line, match):
"""
Take a player, input, and dictionary of parse results, resolve those
parse results into implementations of appropriate interfaces in the
game world, and execute the actual Action implementation (contained in
the 'do' method)... | NotImplementedError | dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Action.runEventTransaction |
2,197 | def do(self, player, line, attribute, target, value):
"""
Dispatch handling to an attribute-specific method.
@type attribute: C{unicode}
@param attribute: The model-level attribute of which to manipulate
the value. Handling of each attribute will be dispatched to a
... | AttributeError | dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Set.do |
2,198 | def set_GENDER(self, player, line, target, value):
"""
Attempt to change the gender of a thing.
@param target: The thing to change the gender of.
@param value: A string naming a gender on L{language.Gender}.
"""
try:
target.gender = getattr(language.Gender, v... | AttributeError | dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Set.set_GENDER |
2,199 | def do(self, player, line, topic):
topic = topic.lower().strip()
try:
helpFile = self.helpContentPath.child(topic).open()
except (__HOLE__, IOError, filepath.InsecurePath):
player.send("No help available on ", topic, ".", "\n")
else:
player.send(helpFi... | OSError | dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Help.do |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.