Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
4,600 | def generate_matches(self, nodes):
"""
Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named subm... | RuntimeError | dataset/ETHPy150Open ctxis/canape/CANAPE.Scripting/Lib/lib2to3/pytree.py/WildcardPattern.generate_matches |
4,601 | def _detect_environment():
# ## -eventlet-
if 'eventlet' in sys.modules:
try:
from eventlet.patcher import is_monkey_patched as is_eventlet
import socket
if is_eventlet(socket):
return 'eventlet'
except __HOLE__:
pass
# ## -ge... | ImportError | dataset/ETHPy150Open celery/kombu/kombu/syn.py/_detect_environment |
4,602 | def interaction_plot(x, trace, response, func=np.mean, ax=None, plottype='b',
xlabel=None, ylabel=None, colors=[], markers=[],
linestyles=[], legendloc='best', legendtitle=None,
**kwargs):
"""
Interaction plot for factor level statistics.
Note.... | AssertionError | dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/graphics/factorplots.py/interaction_plot |
4,603 | def _post_hook(self, msg, urls):
body = json.dumps(msg)
headers = { "Content-Length": str(len(body)),
"Content-Type": "application/json" }
client = HTTPClient()
for url in urls:
try:
client.fetch(url, method="POST", headers=headers,
... | HTTPError | dataset/ETHPy150Open benoitc/gaffer/gaffer/webhooks.py/WebHooks._post_hook |
4,604 | def realm_list(request, id=None):
"""List all realms, or the given realm if id!=None."""
if id == None:
realms = Policy.objects.all()
else:
try:
realms = [Policy.objects.get(id=id)]
except ValueError:
# id wasn't an int, which it should be
realms ... | ObjectDoesNotExist | dataset/ETHPy150Open bmbouter/Opus/opus/project/dcmux/views.py/realm_list |
4,605 | def image_list(request, id=None):
"""List all aggregate images, or the given image if id!=None."""
if id == None:
images = AggregateImage.objects.all()
else:
try:
images = [AggregateImage.objects.get(id=id)]
except __HOLE__:
# id wasn't an int, which it shoul... | ValueError | dataset/ETHPy150Open bmbouter/Opus/opus/project/dcmux/views.py/image_list |
4,606 | def instance_list(request, id=None):
"""List all instances, or the given instance if id!=None."""
if id == None:
instances = Instance.objects.all()
else:
try:
instances = [Instance.objects.get(id=id)]
except __HOLE__:
# id wasn't an int, which it should be
... | ValueError | dataset/ETHPy150Open bmbouter/Opus/opus/project/dcmux/views.py/instance_list |
4,607 | def instance_create(request):
"""Creates an instance with the policy given by realm_id.
Uses image_id and realm_id from the application/x-www-form-urlencoded
format. Both of these fields are required.
"""
# Get multipart-form data: image_id, realm_id, hwp_name, name
try:
image_id = r... | KeyError | dataset/ETHPy150Open bmbouter/Opus/opus/project/dcmux/views.py/instance_create |
4,608 | def test():
"""Interactive test run."""
try:
while 1:
x, digs = input('Enter (x, digs): ')
print x, fix(x, digs), sci(x, digs)
except (EOFError, __HOLE__):
pass | KeyboardInterrupt | dataset/ETHPy150Open babble/babble/include/jython/Lib/fpformat.py/test |
4,609 | def handle(self, addrport, **options):
# setup unbuffered I/O
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)
interactive_debug_listen()
import django
from tornado import httpserver, web
try:
ad... | ValueError | dataset/ETHPy150Open zulip/zulip/zerver/management/commands/runtornado.py/Command.handle |
4,610 | def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
try:
try:
# Setup default url resolver for this thread.
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = url... | SystemExit | dataset/ETHPy150Open zulip/zulip/zerver/management/commands/runtornado.py/AsyncDjangoHandler.get_response |
4,611 | def contribute_to_state(self, state):
try:
contribute = state.contribute_to_state
except __HOLE__:
# set default state attributes.
return self.contribute_to_object(state, {
'actor': self,
'agent': self.agent,
'connection... | AttributeError | dataset/ETHPy150Open celery/cell/cell/actors.py/Actor.contribute_to_state |
4,612 | def lookup_action(self, name):
try:
if not name:
method = self.default_receive
else:
method = getattr(self.state, name)
except __HOLE__:
raise KeyError(name)
if not callable(method) or name.startswith('_'):
raise Key... | AttributeError | dataset/ETHPy150Open celery/cell/cell/actors.py/Actor.lookup_action |
4,613 | def __call__(self, *args, **kw):
if not args:
raise WrongNumberOfArguments(
'No arguments given to %s' % self.func)
try:
meth = getattr(self.parent.state, args[0]).__name__
except __HOLE__:
if kw.get('typed', True):
... | AttributeError | dataset/ETHPy150Open celery/cell/cell/actors.py/ActorProxy.state.__call__ |
4,614 | def setup_user_files():
""" Returns nothing
Create a path for the users prefs files to be stored in their
home folder. Create default config files and place them in the relevant
directory.
"""
print('Setting up dmenu-extended prefs files...')
try:
os.makedirs(path_plugins)
... | OSError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/setup_user_files |
4,615 | def get_plugins(self, force=False):
""" Returns a list of loaded plugins
This method will load plugins in the plugins directory if they
havent already been loaded. Optionally, you may force the
reloading of plugins by setting the parameter 'force' to true.
"""
if self.p... | NameError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/dmenu.get_plugins |
4,616 | def system_path(self):
"""
Array containing system paths
"""
# Get the PATH environmental variable
path = os.environ.get('PATH')
# If we're in Python <3 (less-than-three), we want this to be a unicode string
# In python 3, all strings are unicode already, trying... | AttributeError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/dmenu.system_path |
4,617 | def try_remove(self, needle, haystack):
"""
Gracefully try to remove an item from an array. It not found, fire no
errors. This is a convenience function to reduce code size.
"""
try:
haystack.remove(needle)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/dmenu.try_remove |
4,618 | def cache_build(self):
self.load_preferences()
valid_extensions = []
if 'valid_extensions' in self.prefs:
for extension in self.prefs['valid_extensions']:
if extension == '*':
valid_extensions = True
break
elif ... | ValueError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/dmenu.cache_build |
4,619 | def run(debug=False):
d = dmenu()
if debug:
d.debug = True
cache = d.cache_load()
out = d.menu(cache,'Open:').strip()
if len(out) > 0:
if debug:
print("Menu closed with user input: " + out)
# Check if the action relates to a plugin
plugins = load_plugins(d... | ValueError | dataset/ETHPy150Open markjones112358/dmenu-extended/dmenu_extended.py/run |
4,620 | def __contains__(self, key):
try:
if key in self._dict:
state = self._dict[key]
o = state.obj()
else:
return False
except __HOLE__:
return False
else:
return o is not None | KeyError | dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/orm/identity.py/WeakInstanceDict.__contains__ |
4,621 | def add(self, state):
key = state.key
# inline of self.__contains__
if key in self._dict:
try:
existing_state = self._dict[key]
if existing_state is not state:
o = existing_state.obj()
if o is not None:
... | KeyError | dataset/ETHPy150Open zzzeek/sqlalchemy/lib/sqlalchemy/orm/identity.py/WeakInstanceDict.add |
4,622 | def test_unicode(self):
G = nx.Graph()
try: # Python 3.x
name1 = chr(2344) + chr(123) + chr(6543)
name2 = chr(5543) + chr(1543) + chr(324)
except __HOLE__: # Python 2.6+
name1 = unichr(2344) + unichr(123) + unichr(6543)
name2 = unichr(5543) + unich... | ValueError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/tests/test_adjlist.py/TestAdjlist.test_unicode |
4,623 | def test_latin1_error(self):
G = nx.Graph()
try: # Python 3.x
name1 = chr(2344) + chr(123) + chr(6543)
name2 = chr(5543) + chr(1543) + chr(324)
except __HOLE__: # Python 2.6+
name1 = unichr(2344) + unichr(123) + unichr(6543)
name2 = unichr(5543) + ... | ValueError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/tests/test_adjlist.py/TestAdjlist.test_latin1_error |
4,624 | def test_latin1(self):
G = nx.Graph()
try: # Python 3.x
blurb = chr(1245) # just to trigger the exception
name1 = 'Bj' + chr(246) + 'rk'
name2 = chr(220) + 'ber'
except __HOLE__: # Python 2.6+
name1 = 'Bj' + unichr(246) + 'rk'
name2 = u... | ValueError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/readwrite/tests/test_adjlist.py/TestAdjlist.test_latin1 |
4,625 | def db_command(self, cmd, dbname):
# try without auth first if server allows it (i.e. version >= 3.0.0)
if self.try_on_auth_failures():
need_auth = False
else:
need_auth = self.command_needs_auth(dbname, cmd)
log_verbose("Server '%s': DB Command requested on db %s... | RuntimeError | dataset/ETHPy150Open mongolab/mongoctl/mongoctl/objects/server.py/Server.db_command |
4,626 | def needs_to_auth(self, dbname):
"""
Determines if the server needs to authenticate to the database.
NOTE: we stopped depending on is_auth() since its only a configuration
and may not be accurate
"""
log_debug("Checking if server '%s' needs to auth on db '%s'...." %
... | RuntimeError | dataset/ETHPy150Open mongolab/mongoctl/mongoctl/objects/server.py/Server.needs_to_auth |
4,627 | def get_status(self, admin=False):
status = {}
## check if the server is online
try:
ping(self.get_mongo_client())
status['connection'] = True
# grab status summary if it was specified + if i am not an arbiter
if admin:
server_summ... | RuntimeError | dataset/ETHPy150Open mongolab/mongoctl/mongoctl/objects/server.py/Server.get_status |
4,628 | def get_rs_config(self):
rs_conf = None
try:
if self.version_greater_than_3_0():
rs_conf = self.db_command(SON([('replSetGetConfig', 1)]), "admin")["config"]
else:
rs_conf = self.get_db('local')['system.replset'].find_one()
except (Excepti... | RuntimeError | dataset/ETHPy150Open mongolab/mongoctl/mongoctl/objects/server.py/Server.get_rs_config |
4,629 | def save(self, *args, **kwargs):
if not self.pk:
try:
# Get the last slide order of the list
last_slide = list(self.plugin.slides_list)[-1]
self.order = last_slide.order + 1
except __HOLE__:
self.order = 1
return sup... | IndexError | dataset/ETHPy150Open ionyse/ionyweb/ionyweb/plugin_app/plugin_slideshow/models.py/Slide.save |
4,630 | def read(fname):
try:
return open(os.path.join(os.path.dirname(__file__), fname)).read()
except __HOLE__:
return '' | IOError | dataset/ETHPy150Open bitmazk/cmsplugin-image-gallery/setup.py/read |
4,631 | def test_reading_and_writing_to_file_like_objects(self):
"""
Tests reading and writing to and from file like objects.
"""
# Create some random document.
document = ProvDocument()
document.entity(EX2_NS["test"])
objects = [io.BytesIO, io.StringIO]
Registr... | NotImplementedError | dataset/ETHPy150Open trungdong/prov/prov/tests/test_extras.py/TestExtras.test_reading_and_writing_to_file_like_objects |
4,632 | @cached_property
def max_w(self):
try:
max_w = int(self.request.GET.get('max_w')) or None
except (TypeError, __HOLE__):
pass
else:
orig_w = getattr(self.orig_image, 'width', None) or 0
if not orig_w or max_w < orig_w:
return max... | ValueError | dataset/ETHPy150Open theatlantic/django-cropduster/cropduster/standalone/views.py/CropDusterStandaloneIndex.max_w |
4,633 | def _url(self, endpoint, path=None):
"""The complete URL we will end up querying. Depending on the
endpoint we pass in this will result in different URL's with
different prefixes.
:param endpoint: The PuppetDB API endpoint we want to query.
:type endpoint: :obj:`string`
... | KeyError | dataset/ETHPy150Open voxpupuli/pypuppetdb/pypuppetdb/api/__init__.py/BaseAPI._url |
4,634 | def nodes(self, unreported=2, with_status=False, **kwargs):
"""Query for nodes by either name or query. If both aren't
provided this will return a list of all nodes. This method
also fetches the nodes status and event counts of the latest
report from puppetdb.
:param with_status... | KeyError | dataset/ETHPy150Open voxpupuli/pypuppetdb/pypuppetdb/api/__init__.py/BaseAPI.nodes |
4,635 | def UpdateIndexYaml(self, openfile=open):
"""Update index.yaml.
Args:
openfile: Used for dependency injection.
We only ever write to index.yaml if either:
- it doesn't exist yet; or
- it contains an 'AUTOGENERATED' comment.
All indexes *before* the AUTOGENERATED comment will be written
... | IOError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_index.py/IndexYamlUpdater.UpdateIndexYaml |
4,636 | def SetupIndexes(app_id, root_path):
"""Ensure that the set of existing composite indexes matches index.yaml.
Note: this is similar to the algorithm used by the admin console for
the same purpose.
Args:
app_id: Application ID being served.
root_path: Path to the root of the application.
"""
index_... | IOError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_index.py/SetupIndexes |
4,637 | def filter_metadata(self, queryset, value):
try:
value = json.loads(value)
except __HOLE__:
raise GenericAPIException(400, 'metadata must be valid JSON.')
for name, values in value.items():
if not isinstance(values, list):
values = [values]
... | ValueError | dataset/ETHPy150Open mozilla/kitsune/kitsune/questions/api.py/QuestionFilter.filter_metadata |
4,638 | @require('numpy')
@not_implemented_for('directed')
def laplacian_matrix(G, nodelist=None, weight='weight'):
"""Return the Laplacian matrix of G.
The graph Laplacian is the matrix L = D - A, where
A is the adjacency matrix and D is the diagonal matrix of node degrees.
Parameters
----------
G : ... | KeyError | dataset/ETHPy150Open gkno/gkno_launcher/src/networkx/linalg/laplacianmatrix.py/laplacian_matrix |
4,639 | def init ( self, parent ):
""" Finishes initializing the editor by creating the underlying toolkit
widget.
"""
factory = self.factory
self._editor = editor = PythonEditor( parent,
show_line_numbers = factory.show_line_numbers )
s... | AttributeError | dataset/ETHPy150Open enthought/traitsui/traitsui/wx/code_editor.py/SourceEditor.init |
4,640 | def expr(self, model, data, ** kwargs):
"""
Returns a theano expression for the cost function.
Returns a symbolic expression for a cost function applied to the
minibatch of data.
Optionally, may return None. This represents that the cost function
is intractable but may b... | NotImplementedError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/costs/cost.py/Cost.expr |
4,641 | def get_gradients(self, model, data, ** kwargs):
"""
Provides the gradients of the cost function with respect to the model
parameters.
These are not necessarily those obtained by theano.tensor.grad
--you may wish to use approximate or even intentionally incorrect
gradien... | TypeError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/costs/cost.py/Cost.get_gradients |
4,642 | @functools.wraps(Cost.get_monitoring_channels)
def get_monitoring_channels(self, model, data, ** kwargs):
self.get_data_specs(model)[0].validate(data)
rval = OrderedDict()
composite_specs, mapping = self.get_composite_specs_and_mapping(model)
nested_data = mapping.nest(data)
... | TypeError | dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/costs/cost.py/SumOfCosts.get_monitoring_channels |
4,643 | def safe_repr(value):
"""Hopefully pretty robust repr equivalent."""
# this is pretty horrible but should always return *something*
try:
return pydoc.text.repr(value)
except KeyboardInterrupt:
raise
except:
try:
return repr(value)
except KeyboardInterrupt:... | KeyboardInterrupt | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/format_stack.py/safe_repr |
4,644 | def _fixed_getframes(etb, context=1, tb_offset=0):
LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
# If the error is at the console, don't build any context, since it would
# otherwise produce 5 blank lines printed out (there is no f... | IndexError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/format_stack.py/_fixed_getframes |
4,645 | def format_records(records): # , print_globals=False):
# Loop over all records printing context and info
frames = []
abspath = os.path.abspath
for frame, file, lnum, func, lines, index in records:
try:
file = file and abspath(file) or '?'
except OSError:
# if fi... | UnicodeDecodeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/format_stack.py/format_records |
4,646 | def format_exc(etype, evalue, etb, context=5, tb_offset=0):
""" Return a nice text document describing the traceback.
Parameters
-----------
etype, evalue, etb: as returned by sys.exc_info
context: number of lines of the source file to plot
tb_offset: the number of stack fra... | AttributeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/externals/joblib/format_stack.py/format_exc |
4,647 | def __getattr__(self, name):
try:
return self[name]
except __HOLE__:
raise AttributeError(name) | KeyError | dataset/ETHPy150Open arokem/python-matlab-bridge/tools/gh_api.py/Obj.__getattr__ |
4,648 | def read_manifest(self):
"""Read the manifest file (named by 'self.manifest') and use it to
fill in 'self.filelist', the list of files to include in the source
distribution.
"""
log.info("reading manifest file '%s'", self.manifest)
manifest = open(self.manifest, 'rbU')
... | UnicodeDecodeError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/setuptools/command/sdist.py/sdist.read_manifest |
4,649 | def test_openFDs(self):
"""
File descriptors returned by L{_listOpenFDs} are mostly open.
This test assumes that zero-legth writes fail with EBADF on closed
file descriptors.
"""
for fd in process._listOpenFDs():
try:
fcntl.fcntl(fd, fcntl.F_G... | IOError | dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/internet/test/test_posixprocess.py/FileDescriptorTests.test_openFDs |
4,650 | def removeMicroconsensusDownloadCallback(self, callback):
try:
self._consensus_download_callbacks.remove(callback)
except __HOLE__:
msg = ("MicroconsensusManager got request to remove callback "
"{} but has no reference to this function."
.fo... | KeyError | dataset/ETHPy150Open nskinkel/oppy/oppy/netstatus/microconsensusmanager.py/MicroconsensusManager.removeMicroconsensusDownloadCallback |
4,651 | def null_or_int(value):
try:
return int(value)
except __HOLE__:
return None | TypeError | dataset/ETHPy150Open kvesteri/wtforms-components/wtforms_components/utils.py/null_or_int |
4,652 | @csrf_exempt
def login(request):
"""
Authenticates given 'username' and 'password_hash' against user in database.
"""
if request.method != 'POST':
r = HttpResponse('Invalid method. Only POST method accepted.', status=405)
r['Allow'] = 'POST'
return r
try:
in_json... | ValueError | dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/auth.py/login |
4,653 | @method_accepts(TypeError,
compnames=(str, list, tuple),
index=(int, NoneType),
check=bool)
def add(self, compnames, index=None, check=False):
"""
add(self, compnames, index=None, check=False)
Add new component(s) to the end of the ... | AttributeError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/workflow.py/Workflow.add |
4,654 | def remove(self, compname):
"""Remove a component from the workflow by name. Do not report an
error if the specified component is not found.
"""
if not isinstance(compname, basestring):
msg = "Components must be removed by name from a workflow."
raise TypeError(ms... | ValueError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.main/src/openmdao/main/workflow.py/Workflow.remove |
4,655 | def print_extended_help(self, filename=None):
old_suppress_help = {}
for group in self.option_groups:
try:
old_suppress_help[group] = group.suppress_help
group.suppress_help = False
except __HOLE__ as e:
old_suppress_help[group] = N... | AttributeError | dataset/ETHPy150Open prestodb/presto-admin/prestoadmin/util/parser.py/LoggingOptionParser.print_extended_help |
4,656 | def parse(self, format=None, tz_in=None, tz_out=None):
# 'unix'
if format == "unix":
return str(time.time()).split('.')[0]
# anything else
dt = self.date_gen(tz_in, tz_out)
text = self.date_format(dt, format)
# Fix potential unicode/codepage issues
i... | UnicodeDecodeError | dataset/ETHPy150Open FichteFoll/InsertDate/format_date/__init__.py/FormatDate.parse |
4,657 | def date_gen(self, tz_in=None, tz_out=None):
"""Generates the according datetime object using given parameters"""
# Check parameters and gather tzinfo data (and raise a few exceptions)
if tz_in is None:
tz_in = self.default['tz_in']
if tz_in == "local":
tz_in = s... | AttributeError | dataset/ETHPy150Open FichteFoll/InsertDate/format_date/__init__.py/FormatDate.date_gen |
4,658 | @staticmethod
def translate_to_python(h):
try:
return PersistentHash(h)
except (__HOLE__, ValueError):
return None | TypeError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/persistent_archive/common.py/PersistentHash.translate_to_python |
4,659 | def compute(self):
if self.has_input('value') == self.has_input('hash'):
raise ModuleError(self, "Set either 'value' or 'hash'")
if self.has_input('value'):
self._hash = self.get_input('value')._hash
else:
try:
self._set_hash(self.get_input('ha... | ValueError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/persistent_archive/common.py/PersistentHash.compute |
4,660 | @utils.allow_tableset_proxy
def bins(self, column_name, count=10, start=None, end=None):
"""
Generates (approximately) evenly sized bins for the values in a column.
Bins may not be perfectly even if the spread of the data does not divide
evenly, but all values will always be included in some bin.
T... | IndexError | dataset/ETHPy150Open wireservice/agate/agate/table/bins.py/bins |
4,661 | def main():
import sys
import getopt
try:
opts, args = getopt.getopt(sys.argv[1:], 'td')
except getopt.error, msg:
sys.stdout = sys.stderr
print msg
print "usage: quopri [-t | -d] [file] ..."
print "-t: quote tabs"
print "-d: decode; default encode"
... | IOError | dataset/ETHPy150Open LarsMichelsen/pmatic/ccu_pkg/python/lib/python2.7/quopri.py/main |
4,662 | def parse_post(self, required_keys=None, optional_keys=None):
"""
Clean and validate POSTed JSON data by defining sets of required and
optional keys.
"""
if request.headers.get('content-type') == 'application/json':
data = request.data
elif 'data' not in reque... | ValueError | dataset/ETHPy150Open coleifer/scout/scout.py/RequestValidator.parse_post |
4,663 | def __import_vars(self, env_file):
with open(env_file, "r") as f:
for line in f:
try:
key, val = line.strip().split('=', 1)
key = key.lstrip('export ')
except __HOLE__: # Take care of blank or comment lines
... | ValueError | dataset/ETHPy150Open grauwoelfchen/flask-dotenv/flask_dotenv.py/DotEnv.__import_vars |
4,664 | def eval(self, keys):
"""
Examples:
Specify type literal for key.
>>> env.eval({MAIL_PORT: int})
"""
for k, v in keys.items():
if k in self.app.config:
try:
val = ast.literal_eval(self.app.config[k])
... | ValueError | dataset/ETHPy150Open grauwoelfchen/flask-dotenv/flask_dotenv.py/DotEnv.eval |
4,665 | def validate_yes_no(answer):
VALIDATION_TABLE = {'y':True, 'n':False, 'yes':True, 'no':True, 'Y':True, 'N':False}
try:
return VALIDATION_TABLE[answer]
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open cidadania/ecidadania-ng/src/apps/managecommands/management/commands/resource_addnewapp/_commons.py/validate_yes_no |
4,666 | def enable_logging(hass, verbose=False, daemon=False, log_rotate_days=None):
"""Setup the logging."""
if not daemon:
logging.basicConfig(level=logging.INFO)
fmt = ("%(log_color)s%(asctime)s %(levelname)s (%(threadName)s) "
"[%(name)s] %(message)s%(reset)s")
try:
... | ImportError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/bootstrap.py/enable_logging |
4,667 | def save_as(self, version):
"""the save action for houdini environment
"""
if not version:
return
from stalker import Version
assert isinstance(version, Version)
# get the current version, and store it as the parent of the new version
current_version... | OSError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/houdini.py/Houdini.save_as |
4,668 | @classmethod
def set_environment_variable(cls, var, value):
"""sets environment var
:param str var: The name of the var
:param value: The value of the variable
"""
os.environ[var] = value
try:
hou.allowEnvironmentVariableToOverwriteVariable(var, True)
... | AttributeError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/houdini.py/Houdini.set_environment_variable |
4,669 | def set_render_filename(self, version):
"""sets the render file name
"""
output_filename = \
'{version.absolute_path}/Outputs/`$OS`/' \
'{version.task.project.code}_{version.nice_name}_' \
'v{version.version_number:03d}.$F4.exr'
output_filename = \
... | OSError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/houdini.py/Houdini.set_render_filename |
4,670 | def _read(self):
"""reads the history file to a buffer
"""
try:
history_file = open(self._history_file_full_path)
except __HOLE__:
self._buffer = []
return
self._buffer = history_file.readlines()
# strip all the lines
self._bu... | IOError | dataset/ETHPy150Open eoyilmaz/anima/anima/env/houdini.py/FileHistory._read |
4,671 | def _str2time(day, mon, yr, hr, min, sec, tz):
# translate month name to number
# month numbers start with 1 (January)
try:
mon = MONTHS_LOWER.index(mon.lower())+1
except ValueError:
# maybe it's already a number
try:
imon = int(mon)
except __HOLE__:
... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/_str2time |
4,672 | def request_port(request):
host = request.get_host()
i = host.find(':')
if i >= 0:
port = host[i+1:]
try:
int(port)
except __HOLE__:
_debug("nonnumeric port: '%s'", port)
return None
else:
port = DEFAULT_HTTP_PORT
return port
# Cha... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/request_port |
4,673 | def set_ok_port(self, cookie, request):
if cookie.port_specified:
req_port = request_port(request)
if req_port is None:
req_port = "80"
else:
req_port = str(req_port)
for p in cookie.port.split(","):
try:
... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/DefaultCookiePolicy.set_ok_port |
4,674 | def deepvalues(mapping):
"""Iterates over nested mapping, depth-first, in sorted order by key."""
values = vals_sorted_by_key(mapping)
for obj in values:
mapping = False
try:
obj.items
except __HOLE__:
pass
else:
mapping = True
... | AttributeError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/deepvalues |
4,675 | def _normalized_cookie_tuples(self, attrs_set):
"""Return list of tuples containing normalised cookie information.
attrs_set is the list of lists of key,value pairs extracted from
the Set-Cookie or Set-Cookie2 headers.
Tuples are name, value, standard, rest, where name and value are th... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/CookieJar._normalized_cookie_tuples |
4,676 | def _cookie_from_cookie_tuple(self, tup, request):
# standard is dict of standard cookie-attributes, rest is dict of the
# rest of them
name, value, standard, rest = tup
domain = standard.get("domain", Absent)
path = standard.get("path", Absent)
port = standard.get("port... | KeyError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/CookieJar._cookie_from_cookie_tuple |
4,677 | def revert(self, filename=None,
ignore_discard=False, ignore_expires=False):
"""Clear all cookies and reload cookies from a saved file.
Raises LoadError (or IOError) if reversion is not successful; the
object's state will not be altered if this happens.
"""
if fi... | IOError | dataset/ETHPy150Open babble/babble/include/jython/Lib/cookielib.py/FileCookieJar.revert |
4,678 | def _parseHeaderValue(self, header_value):
"""
Parse out a complex header value (such as Content-Type, with a value
like "text/html; charset=utf-8") into a main value and a dictionary of
extra information (in this case, 'text/html' and {'charset': 'utf8'}).
"""
values = h... | ValueError | dataset/ETHPy150Open necaris/python3-openid/openid/fetchers.py/Urllib2Fetcher._parseHeaderValue |
4,679 | def _parseHeaders(self, header_file):
header_file.seek(0)
# Remove the status line from the beginning of the input
unused_http_status_line = header_file.readline().lower()
if unused_http_status_line.startswith(b'http/1.1 100 '):
unused_http_status_line = header_file.readline... | ValueError | dataset/ETHPy150Open necaris/python3-openid/openid/fetchers.py/CurlHTTPFetcher._parseHeaders |
4,680 | def fetch(self, url, body=None, headers=None):
"""Perform an HTTP request
@raises Exception: Any exception that can be raised by httplib2
@see: C{L{HTTPFetcher.fetch}}
"""
if body:
method = 'POST'
else:
method = 'GET'
if headers is None:... | KeyError | dataset/ETHPy150Open necaris/python3-openid/openid/fetchers.py/HTTPLib2Fetcher.fetch |
4,681 | def parse_config_h(fp, g=None):
"""Parse a config.h-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
if g is None:
g = {}
define_rx = re.compile("#define ([A-... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/sysconfig.py/parse_config_h |
4,682 | def parse_makefile(fn, g=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
from distutils.text_file import TextFile
fp = TextFile(fn, strip_... | ValueError | dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/sysconfig.py/parse_makefile |
4,683 | def _init_posix():
"""Initialize the module as appropriate for POSIX systems."""
g = {}
# load the installed Makefile:
try:
filename = get_makefile_filename()
parse_makefile(filename, g)
except __HOLE__, msg:
my_msg = "invalid Python installation: unable to open %s" % filenam... | IOError | dataset/ETHPy150Open babble/babble/include/jython/Lib/distutils/sysconfig.py/_init_posix |
4,684 | def multiple_action_transactions(self, args):
action = None
# TODO: catch that we don't mix in requisiton and stock report keywords in the same multi-action message?
_args = iter(args)
def next():
return _args.next()
found_product_for_action = True
while T... | StopIteration | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/commtrack/sms.py/StockReportParser.multiple_action_transactions |
4,685 | def looks_like_prod_code(self, code):
try:
int(code)
return False
except __HOLE__:
return True | ValueError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/commtrack/sms.py/StockReportParser.looks_like_prod_code |
4,686 | def looks_like_prod_code(self, code):
"""
Special for EWS, this version doesn't consider "10.20"
as an invalid quantity.
"""
try:
float(code)
return False
except __HOLE__:
return True | ValueError | dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/commtrack/sms.py/StockAndReceiptParser.looks_like_prod_code |
4,687 | def can_import(name):
"""Attempt to __import__ the specified package/module, returning
True when succeeding, otherwise False"""
try:
__import__(name)
return True
except __HOLE__:
return False | ImportError | dataset/ETHPy150Open Pylons/pylons/pylons/commands.py/can_import |
4,688 | def is_minimal_template(package, fail_fast=False):
"""Determine if the specified Pylons project (package) uses the
Pylons Minimal Template.
fail_fast causes ImportErrors encountered during detection to be
raised.
"""
minimal_template = False
try:
# Check if PACKAGE.lib.base exists
... | ImportError | dataset/ETHPy150Open Pylons/pylons/pylons/commands.py/is_minimal_template |
4,689 | def command(self):
"""Main command to create a new shell"""
self.verbose = 3
if len(self.args) == 0:
# Assume the .ini file is ./development.ini
config_file = 'development.ini'
if not os.path.isfile(config_file):
raise BadCommand('%sError: CONF... | ImportError | dataset/ETHPy150Open Pylons/pylons/pylons/commands.py/ShellCommand.command |
4,690 | def _get_start_shift(self, shift):
if shift == '':
return 0
time_formats = ['%Y-%m-%d %H:%M:%S',
'%Y-%m-%d %H:%M',
'%H:%M:%S',
'%H:%M']
for time_format in time_formats:
try:
date = d... | TypeError | dataset/ETHPy150Open Blazemeter/taurus/bzt/modules/provisioning.py/Local._get_start_shift |
4,691 | def parse_date(string_date):
"""
Parse the given date as one of the following
* Git internal format: timestamp offset
* RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
* ISO 8601 2005-04-07T22:13:13
The T can be a space as well
:return: Tuple(int(timestamp_UTC), int(offset))... | ValueError | dataset/ETHPy150Open gitpython-developers/GitPython/git/objects/util.py/parse_date |
4,692 | def memoize(f):
arg_cache = {}
def _new_f(arg):
cache_it = True
try:
cached = arg_cache.get(arg, None)
if cached is not None:
return cached
except __HOLE__:
cache_it = False
uncached = f(arg)
if cache_it:
arg... | TypeError | dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/lib/bebop/util.py/memoize |
4,693 | def test_AptInstaller():
from rosdep2.platforms.debian import AptInstaller
@patch.object(AptInstaller, 'get_packages_to_install')
def test(mock_method):
installer = AptInstaller()
mock_method.return_value = []
assert [] == installer.get_install_command(['fake'])
mock_method... | AssertionError | dataset/ETHPy150Open ros-infrastructure/rosdep/test/test_rosdep_debian.py/test_AptInstaller |
4,694 | def handle(self, *args, **options):
username = options.get(self.UserModel.USERNAME_FIELD, None)
interactive = options.get('interactive')
verbosity = int(options.get('verbosity', 1))
database = options.get('database')
# If not provided, create the user with an unusable password
... | KeyboardInterrupt | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Django-1.6.10/django/contrib/auth/management/commands/createsuperuser.py/Command.handle |
4,695 | def __init__(self, *args, **kwargs):
try:
self.base_fields['image_file'].initial = kwargs['instance'].image.pk
except (__HOLE__, KeyError):
self.base_fields['image_file'].initial = None
self.base_fields['image_file'].widget = AdminFileWidget(ManyToOneRel(FilerImageField, ... | AttributeError | dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/bootstrap3/image.py/ImageFormMixin.__init__ |
4,696 | @classmethod
def get_identifier(cls, obj):
identifier = super(BootstrapImagePlugin, cls).get_identifier(obj)
try:
content = force_text(obj.image)
except __HOLE__:
content = _("No Image")
return format_html('{0}{1}', identifier, content) | AttributeError | dataset/ETHPy150Open jrief/djangocms-cascade/cmsplugin_cascade/bootstrap3/image.py/BootstrapImagePlugin.get_identifier |
4,697 | def _zerorpc_args(self):
try:
args_spec = self._functor._zerorpc_args()
except AttributeError:
try:
args_spec = inspect.getargspec(self._functor)
except TypeError:
try:
args_spec = inspect.getargspec(self._functor.__... | AttributeError | dataset/ETHPy150Open 0rpc/zerorpc-python/zerorpc/decorators.py/DecoratorBase._zerorpc_args |
4,698 | def tearDown(self):
try:
os.unlink(self.cfg_file)
except __HOLE__:
pass | OSError | dataset/ETHPy150Open ganeti/ganeti/test/py/ganeti.config_unittest.py/TestConfigRunner.tearDown |
4,699 | def make_log_graph(repos, revs):
"""Generate graph information for the given revisions.
Returns a tuple `(threads, vertices, columns)`, where:
* `threads`: List of paint command lists `[(type, column, line)]`, where
`type` is either 0 for "move to" or 1 for "line to", and `column` and
`line... | StopIteration | dataset/ETHPy150Open edgewall/trac/trac/versioncontrol/web_ui/util.py/make_log_graph |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.