Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,600 | def _add_details(self, info):
for (k, v) in six.iteritems(info):
try:
if k == 'requirements':
v = self._add_requirements_details(v)
setattr(self, k, v)
self._info[k] = v
except __HOLE__:
# In this case we... | AttributeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/Artifact._add_details |
5,601 | def _add_details(self, info):
for (k, v) in six.iteritems(info):
try:
if k == 'artifacts':
v = self._add_artifact_details(v)
elif k == 'services':
v = self._add_services_details(v)
setattr(self, k, v)
... | AttributeError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/Plan._add_details |
5,602 | def list(self, **kwargs):
kwargs = self._filter_kwargs(kwargs)
kwargs.setdefault("headers", kwargs.get("headers", {}))
kwargs['headers']['Content-Type'] = 'x-application/yaml'
resp = self.client.get(
self.build_url(base_url="/v1", **kwargs), **kwargs)
try:
... | ValueError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/PlanManager.list |
5,603 | def create(self, plan, **kwargs):
kwargs = self._filter_kwargs(kwargs)
kwargs['data'] = plan
kwargs.setdefault("headers", kwargs.get("headers", {}))
kwargs['headers']['Content-Type'] = 'x-application/yaml'
try:
resp = self.client.post(
self.build_url(b... | ValueError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/PlanManager.create |
5,604 | def _get(self, url, response_key=None):
kwargs = {'headers': {}}
kwargs['headers']['Content-Type'] = 'x-application/yaml'
resp = self.client.get(url, **kwargs)
try:
resp_plan = yamlutils.load(resp.content)
except __HOLE__ as e:
raise exc.CommandException(m... | ValueError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/PlanManager._get |
5,605 | def update(self, plan, **kwargs):
kwargs = self._filter_kwargs(kwargs)
kwargs['data'] = plan
kwargs.setdefault("headers", kwargs.get("headers", {}))
kwargs['headers']['Content-Type'] = 'x-application/yaml'
resp = self.client.put(self.build_url(base_url="/v1", **kwargs),
... | ValueError | dataset/ETHPy150Open openstack/python-solumclient/solumclient/v1/plan.py/PlanManager.update |
5,606 | def is_duplicate_page(link):
try:
ConfiguratorPage.objects.get(link=link)
return True
except (ConfiguratorPage.DoesNotExist, __HOLE__):
return False | AssertionError | dataset/ETHPy150Open marineam/nagcat/railroad/railroad/permalink/views.py/is_duplicate_page |
5,607 | @conf
def cmd_and_log(self, cmd, kw):
Logs.debug('runner: %s\n' % cmd)
if self.log:
self.log.write('%s\n' % cmd)
try:
p = Utils.pproc.Popen(cmd, stdout=Utils.pproc.PIPE, stderr=Utils.pproc.PIPE, shell=True)
(out, err) = p.communicate()
except __HOLE__, e:
self.log.write('error %r' % e)
self.fatal(str(e))... | OSError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/config_c.py/cmd_and_log |
5,608 | @conf
def validate_c(self, kw):
"""validate the parameters for the test method"""
if not 'env' in kw:
kw['env'] = self.env.copy()
env = kw['env']
if not 'compiler' in kw:
kw['compiler'] = 'cc'
if env['CXX_NAME'] and Task.TaskBase.classes.get('cxx', None):
kw['compiler'] = 'cxx'
if not self.env['CXX']:... | AttributeError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/config_c.py/validate_c |
5,609 | @conf
def run_c_code(self, *k, **kw):
test_f_name = kw['compile_filename']
k = 0
while k < 10000:
# make certain to use a fresh folder - necessary for win32
dir = os.path.join(self.blddir, '.conf_check_%d' % k)
# if the folder already exists, remove it
try:
shutil.rmtree(dir)
except __HOLE__:
pass
... | OSError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/config_c.py/run_c_code |
5,610 | @conf
def is_defined(self, key):
defines = self.env[DEFINES]
if not defines:
return False
try:
value = defines[key]
except __HOLE__:
return False
else:
return value != UNDEFINED | KeyError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/config_c.py/is_defined |
5,611 | @conf
def get_define(self, define):
"get the value of a previously stored define"
try: return self.env[DEFINES][define]
except __HOLE__: return None | KeyError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/config_c.py/get_define |
5,612 | def wrap_code(self, routine, helpers=[]):
workdir = self.filepath or tempfile.mkdtemp("_sympy_compile")
if not os.access(workdir, os.F_OK):
os.mkdir(workdir)
oldwork = os.getcwd()
os.chdir(workdir)
try:
sys.path.append(workdir)
self._generate_... | OSError | dataset/ETHPy150Open sympy/sympy/sympy/utilities/autowrap.py/CodeWrapper.wrap_code |
5,613 | def AnalyzeFileObject(self, file_object):
"""Retrieves the format specification.
Args:
file_object: a file-like object (instance of file_io.FileIO).
Returns:
The type indicator if the file-like object contains a supported format
or None otherwise.
"""
tsk_image_object = tsk_image... | IOError | dataset/ETHPy150Open log2timeline/dfvfs/dfvfs/analyzer/tsk_partition_analyzer_helper.py/TSKPartitionAnalyzerHelper.AnalyzeFileObject |
5,614 | def load_manifest(filename):
rv = {}
try:
with open(filename) as f:
for line in f:
if line[:1] == '@':
rv[line.strip()] = None
continue
line = line.strip().split('=', 1)
if len(line) == 2:
... | IOError | dataset/ETHPy150Open lektor/lektor/lektor/packages.py/load_manifest |
5,615 | def list_local_packages(path):
"""Lists all local packages below a path that could be installed."""
rv = []
try:
for filename in os.listdir(path):
if os.path.isfile(os.path.join(path, filename, 'setup.py')):
rv.append('@' + filename)
except __HOLE__:
pass
... | OSError | dataset/ETHPy150Open lektor/lektor/lektor/packages.py/list_local_packages |
5,616 | def update_cache(package_root, remote_packages, local_package_path,
refresh=False):
"""Updates the package cache at package_root for the given dictionary
of packages as well as packages in the given local package path.
"""
requires_wipe = False
if refresh:
click.echo('Force ... | OSError | dataset/ETHPy150Open lektor/lektor/lektor/packages.py/update_cache |
5,617 | def wipe_package_cache(env):
"""Wipes the entire package cache."""
package_root = env.project.get_package_cache_path()
try:
shutil.rmtree(package_root)
except (__HOLE__, IOError):
pass | OSError | dataset/ETHPy150Open lektor/lektor/lektor/packages.py/wipe_package_cache |
5,618 | def is_installed(name):
ret = exec_cmd("/usr/bin/dpkg-query -l '{0}'".format(name))
if ret['returncode'] != 0:
return False
# There's no way to use return code of any of the dpkg-query options.
# Instead we use the "state" column of dpkg-query -l
# So programmaticaly here:
# 1. Get stdo... | IndexError | dataset/ETHPy150Open comodit/synapse-agent/synapse/resources/packages-plugin/apt.py/is_installed |
5,619 | def InsertPhoto(self, album_or_uri, photo, filename_or_handle,
content_type='image/jpeg'):
"""Add a PhotoEntry
Needs authentication, see self.ClientLogin()
Arguments:
album_or_uri: AlbumFeed or uri of the album where the photo should go
photo: PhotoEntry to add
filename_or_handle: A file-l... | ValueError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/photos/service.py/PhotosService.InsertPhoto |
5,620 | def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle,
content_type = 'image/jpeg'):
"""Update a photo's binary data.
Needs authentication, see self.ClientLogin()
Arguments:
photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a
`edit-media' uri pointing to... | ValueError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/photos/service.py/PhotosService.UpdatePhotoBlob |
5,621 | def Delete(self, object_or_uri, *args, **kwargs):
"""Delete an object.
Re-implementing the GDataService.Delete method, to add some
convenience.
Arguments:
object_or_uri: Any object that has a GetEditLink() method that
returns a link, or a uri to that object.
Returns:
? or GooglePhot... | AttributeError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/photos/service.py/PhotosService.Delete |
5,622 | def __init__(self, class_name, bases, namespace):
self.errors = []
self.filename = None
try:
self._checks.append(self())
except __HOLE__:
self._checks = [] | AttributeError | dataset/ETHPy150Open nbessi/openerp-conventions/common_checker/base_checker.py/BaseCheckerMeta.__init__ |
5,623 | def load_plugin(self, plugin_name):
""" Loads a single plugin given its name """
if not plugin_name in __all__:
raise KeyError("Plugin " + plugin_name + " not found")
try:
plugin = self.__plugins[plugin_name]
except __HOLE__:
# Load the plugin only if ... | KeyError | dataset/ETHPy150Open nacx/kahuna/kahuna/pluginmanager.py/PluginManager.load_plugin |
5,624 | def call(self, plugin_name, command_name, args):
""" Encapsulate the call into a context already loaded. """
try:
plugin = self.load_plugin(plugin_name)
except KeyError:
# Plugin not found, pring generic help
self.help_all()
if not command_name:
... | KeyError | dataset/ETHPy150Open nacx/kahuna/kahuna/pluginmanager.py/PluginManager.call |
5,625 | def find_credentials():
"""
Look in the current environment for Twilio credentails
"""
try:
account = os.environ["TWILIO_ACCOUNT_SID"]
token = os.environ["TWILIO_AUTH_TOKEN"]
return account, token
except __HOLE__:
return None, None | KeyError | dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/twilio/rest/__init__.py/find_credentials |
5,626 | def serialize(self, data, content_type):
try:
return json.dumps(data)
except __HOLE__:
pass
return json.dumps(to_primitive(data)) | TypeError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/network/quantum/client.py/JSONSerializer.serialize |
5,627 | def do_request(self, method, action, body=None,
headers=None, params=None):
"""Connects to the server and issues a request.
Returns the result data, or raises an appropriate exception if
HTTP status code is not 2xx
:param method: HTTP method ("GET", "POST", "PUT", etc... | IOError | dataset/ETHPy150Open nii-cloud/dodai-compute/nova/network/quantum/client.py/Client.do_request |
5,628 | def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more.
This simply calls :meth:`consume_next` until there are no
more to consume.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
... | StopIteration | dataset/ETHPy150Open GoogleCloudPlatform/gcloud-python/gcloud/bigtable/row_data.py/PartialRowsData.consume_all |
5,629 | def parse(seq):
"""Sequence(Token) -> object"""
const = lambda x: lambda _: x
tokval = lambda x: x.value
toktype = lambda t: some(lambda x: x.type == t) >> tokval
op = lambda s: a(Token(u'Op', s)) >> tokval
op_ = lambda s: skip(op(s))
n = lambda s: a(Token(u'Name', s)) >> tokval
def mak... | ValueError | dataset/ETHPy150Open vlasovskikh/funcparserlib/funcparserlib/tests/json.py/parse |
5,630 | def update_price_estimate_on_resource_spl_change(sender, instance, created=False, **kwargs):
try:
# XXX: drop support of IaaS app
is_changed = not created and instance.service_project_link_id != instance._old_values['service_project_link']
except __HOLE__:
is_changed = False
if is_c... | AttributeError | dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/cost_tracking/handlers.py/update_price_estimate_on_resource_spl_change |
5,631 | def decode(self, obj, *args, **kwargs):
if not kwargs.get('recurse', False):
obj = super(JSONDecoder, self).decode(obj, *args, **kwargs)
if isinstance(obj, list):
for i in six.moves.xrange(len(obj)):
item = obj[i]
if self._is_recursive(item):
... | ValueError | dataset/ETHPy150Open derek-schaefer/django-json-field/json_field/fields.py/JSONDecoder.decode |
5,632 | @wsgi.action('os-getVNCConsole')
def get_vnc_console(self, req, id, body):
"""Get vnc connection information to access a server."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown, get_vnc_console below will cope
console_type = b... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/consoles.py/ConsolesController.get_vnc_console |
5,633 | @wsgi.action('os-getSPICEConsole')
def get_spice_console(self, req, id, body):
"""Get spice connection information to access a server."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown, get_spice_console below will cope
console_... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/consoles.py/ConsolesController.get_spice_console |
5,634 | @wsgi.action('os-getRDPConsole')
def get_rdp_console(self, req, id, body):
"""Get text console output."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown, get_rdp_console below will cope
console_type = body['os-getRDPConsole'].ge... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/consoles.py/ConsolesController.get_rdp_console |
5,635 | @wsgi.action('os-getSerialConsole')
def get_serial_console(self, req, id, body):
"""Get connection to a serial console."""
context = req.environ['nova.context']
authorize(context)
# If type is not supplied or unknown get_serial_console below will cope
console_type = body['os... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/consoles.py/ConsolesController.get_serial_console |
5,636 | def __setattr__(self, prop, value):
# Add validity check for self.change
if (prop == 'change' and Resource.CHANGE_TYPES and
value is not None and not value in Resource.CHANGE_TYPES):
raise ChangeTypeError(value)
else:
try:
object.__setattr__(se... | AttributeError | dataset/ETHPy150Open resync/resync/resync/resource.py/Resource.__setattr__ |
5,637 | def seek(self, pos, whence=0):
"""Change stream position.
Change the stream position to byte offset offset. offset is
interpreted relative to the position indicated by whence. Values
for whence are:
* 0 -- start of stream (the default); offset should be zero or positive
... | AttributeError | dataset/ETHPy150Open PyTables/PyTables/tables/nodes/filenode.py/RawPyTablesIO.seek |
5,638 | def __init__(self, node, h5file, **kwargs):
if node is not None:
# Open an existing node and get its version.
self._check_attributes(node)
self._version = node.attrs.NODE_TYPE_VERSION
elif h5file is not None:
# Check for allowed keyword arguments,
... | RuntimeError | dataset/ETHPy150Open PyTables/PyTables/tables/nodes/filenode.py/RAFileNode.__init__ |
5,639 | def expand_to_semantic_unit(string, startIndex, endIndex):
symbols = "([{)]}"
breakSymbols = ",;=&|\n"
lookBackBreakSymbols = breakSymbols + "([{"
lookForwardBreakSymbols = breakSymbols + ")]}"
symbolsRe = re.compile(r'(['+re.escape(symbols)+re.escape(breakSymbols)+'])')
counterparts = {
"(":")",
"... | NameError | dataset/ETHPy150Open aronwoost/sublime-expand-region/expand_to_semantic_unit.py/expand_to_semantic_unit |
5,640 | def get_target(self, addon_short_name):
try:
return [addon for addon in self.target_addons if addon.name == addon_short_name][0]
except __HOLE__:
return None | IndexError | dataset/ETHPy150Open CenterForOpenScience/osf.io/website/archiver/model.py/ArchiveJob.get_target |
5,641 | def logistic_regression_path(X, y, pos_class=None, Cs=10, fit_intercept=True,
max_iter=100, tol=1e-4, verbose=0,
solver='lbfgs', coef=None, copy=False,
class_weight=None, dual=False, penalty='l2',
interce... | TypeError | dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/linear_model/logistic.py/logistic_regression_path |
5,642 | def _import_speedups():
try:
from simplejson import _speedups
return _speedups.encode_basestring_ascii, _speedups.make_encoder
except __HOLE__:
return None, None | ImportError | dataset/ETHPy150Open kennethreitz/tablib/tablib/packages/omnijson/packages/simplejson/encoder.py/_import_speedups |
5,643 | def py_encode_basestring_ascii(s):
"""Return an ASCII-only JSON representation of a Python string
"""
if isinstance(s, str) and HAS_UTF8.search(s) is not None:
s = s.decode('utf-8')
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except __HOL... | KeyError | dataset/ETHPy150Open kennethreitz/tablib/tablib/packages/omnijson/packages/simplejson/encoder.py/py_encode_basestring_ascii |
5,644 | def run(self, edit):
# You can change PLUGIN_VERSION according to your needs.
region = self.view.find("^#define\s+(?:PLUGIN_)?VERSION\s+\"\d{1,2}\.\d{1,2}\.\d{1,3}\"", 0)
if region != None:
strLine = self.view.substr(region)
rIndex1 = strLine.rfind(".")
rIndex2 = strLine.rfind("\"")
sBuild = st... | ValueError | dataset/ETHPy150Open austinwagner/sublime-sourcepawn/sm_version_auto_increment.py/VerIncCommand.run |
5,645 | def publishToNewObserver(observer, eventDict, textFromEventDict):
"""
Publish an old-style (L{twisted.python.log}) event to a new-style
(L{twisted.logger}) observer.
@note: It's possible that a new-style event was sent to a
L{LegacyLogObserverWrapper}, and may now be getting sent back to a
... | KeyError | dataset/ETHPy150Open twisted/twisted/twisted/logger/_legacy.py/publishToNewObserver |
5,646 | def kill_members(members, sig, hosts=nodes):
for member in sorted(members):
try:
if ha_tools_debug:
print('killing %s' % member)
proc = hosts[member]['proc']
# Not sure if cygwin makes sense here...
if sys.platform in ('win32', 'cygwin'):
... | OSError | dataset/ETHPy150Open mongodb/motor/test/high_availability/ha_tools.py/kill_members |
5,647 | def wait_for(proc, port_num):
trys = 0
while proc.poll() is None and trys < 160:
trys += 1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
try:
s.connect((hostname, port_num))
return True
except (__HOLE__, socket.error):
... | IOError | dataset/ETHPy150Open mongodb/motor/test/high_availability/ha_tools.py/wait_for |
5,648 | def start_replica_set(members, auth=False, fresh=True):
global cur_port, key_file
if fresh:
if os.path.exists(dbpath):
try:
shutil.rmtree(dbpath)
except OSError:
pass
try:
os.makedirs(dbpath)
except __HOLE__ as e:
... | OSError | dataset/ETHPy150Open mongodb/motor/test/high_availability/ha_tools.py/start_replica_set |
5,649 | def get_hidden_members():
# Both 'hidden' and 'slaveDelay'
secondaries = get_secondaries()
readers = get_hosts() + get_passives()
for member in readers:
try:
secondaries.remove(member)
except __HOLE__:
# Skip primary
pass
return secondaries | KeyError | dataset/ETHPy150Open mongodb/motor/test/high_availability/ha_tools.py/get_hidden_members |
5,650 | def sync_table(model):
"""
Inspects the model and creates / updates the corresponding table and columns.
Any User Defined Types used in the table are implicitly synchronized.
This function can only add fields that are not part of the primary key.
Note that the attributes removed from the model ar... | KeyError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/management.py/sync_table |
5,651 | def _update_options(model):
"""Updates the table options for the given model if necessary.
:param model: The model to update.
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool
"""
log.debug("Checking %s for option differences", model)
model... | KeyError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/management.py/_update_options |
5,652 | def drop_table(model):
"""
Drops the table indicated by the model, if it exists.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard... | KeyError | dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/management.py/drop_table |
5,653 | @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/service_plugins/cisco_router_plugin.py/CiscoRouterPlugin._core_plugin |
5,654 | def test_package_import__semantics(self):
# Generate a couple of broken modules to try importing.
# ...try loading the module when there's a SyntaxError
self.rewrite_file('for')
try: __import__(self.module_name)
except SyntaxError: pass
else: raise RuntimeError('Failed ... | NameError | dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_pkgimport.py/TestImport.test_package_import__semantics |
5,655 | @classmethod
def from_path(cls, path, extension_required=False):
"""Locates the project for a path."""
path = os.path.abspath(path)
if os.path.isfile(path) and (not extension_required or
path.endswith('.lektorproject')):
return cls.from_file(p... | OSError | dataset/ETHPy150Open lektor/lektor-archive/lektor/project.py/Project.from_path |
5,656 | def number(self, num):
"""Parse a string containing a label or number into an address.
"""
try:
if num.startswith('$'):
# hexadecimal
return self._constrain(int(num[1:], 16))
elif num.startswith('+'):
# decimal
... | ValueError | dataset/ETHPy150Open mnaberez/py65/py65/utils/addressing.py/AddressParser.number |
5,657 | def load_template_source(self, template_name, template_dirs=None):
filepath = self.get_template_path(template_name, template_dirs)
try:
with io.open(filepath, encoding=self.engine.file_charset) as fp:
return fp.read(), filepath
except __HOLE__:
raise Templ... | IOError | dataset/ETHPy150Open allegro/ralph/src/ralph/lib/template/loaders.py/AppTemplateLoader.load_template_source |
5,658 | def handle_short_request():
"""
Handle short requests such as passing keystrokes to the application
or sending the initial html page. If returns True, then this
function recognised and handled a short request, and the calling
script should immediately exit.
web_display.set_preferences(..) shou... | OSError | dataset/ETHPy150Open AnyMesh/anyMesh-Python/example/urwid/web_display.py/handle_short_request |
5,659 | def daemonize( errfile ):
"""
Detach process and become a daemon.
"""
pid = os.fork()
if pid:
os._exit(0)
os.setsid()
signal.signal(signal.SIGHUP, signal.SIG_IGN)
os.umask(0)
pid = os.fork()
if pid:
os._exit(0)
os.chdir("/")
for fd in range(0,20):
... | OSError | dataset/ETHPy150Open AnyMesh/anyMesh-Python/example/urwid/web_display.py/daemonize |
5,660 | def lookup(self, line, column):
try:
# Let's hope for a direct match first
return self.index[(line, column)]
except __HOLE__:
pass
# Figure out which line to search through
line_index = self.line_index[line]
# Find the closest column token
... | KeyError | dataset/ETHPy150Open lavrton/sublime-better-typescript/sourcemap/objects.py/SourceMapIndex.lookup |
5,661 | def validate(self, request):
""" Checks a request for proper authentication details.
Returns a tuple of ``(access_token, error_response_arguments)``, which are
designed to be passed to the :py:meth:`make_error_response` method.
For example, to restrict access to a given endpoint:
.. code-block:: ... | ValueError | dataset/ETHPy150Open Locu/djoauth2/djoauth2/access_token.py/AccessTokenAuthenticator.validate |
5,662 | def get(self, asset_name):
"""Serve out the contents of a file to self.response.
Args:
asset_name: The name of the static asset to serve. Must be in ASSETS_PATH.
"""
with self._asset_name_to_path_lock:
if self._asset_name_to_path is None:
self._initialize_asset_map()
if asset_n... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/tools/devappserver2/admin/static_file_handler.py/StaticFileHandler.get |
5,663 | def __call__(self, environ, start_response):
"""Respond to a request when called in the usual WSGI way."""
path_info = environ.get('PATH_INFO', '')
full_path = self._full_path(path_info)
if not self._is_under_root(full_path):
return self.not_found(environ, start_response)
... | OSError | dataset/ETHPy150Open cloudera/hue/tools/ace-editor/static.py/Cling.__call__ |
5,664 | def iter_and_close(file_like, block_size):
"""Yield file contents by block then close the file."""
while 1:
try:
block = file_like.read(block_size)
if block: yield block
else: raise StopIteration
except __HOLE__, si:
file_like.close()
r... | StopIteration | dataset/ETHPy150Open cloudera/hue/tools/ace-editor/static.py/iter_and_close |
5,665 | def command():
usage = "%prog [--help] [-d DIR] [-l [HOST][:PORT]] [-p GLOB[,GLOB...]]"
parser = OptionParser(usage=usage, version="static 0.3.6")
parser.add_option("-d", "--dir", dest="rootdir", default=".",
help="Root directory to serve. Defaults to '.' .", metavar="DIR")
parser.add_option("-l... | KeyboardInterrupt | dataset/ETHPy150Open cloudera/hue/tools/ace-editor/static.py/command |
5,666 | def safe_fork(self):
try:
return os.fork()
except __HOLE__, e:
if e.errno == errno.EWOULDBLOCK:
time.sleep(5)
self.safe_fork() | OSError | dataset/ETHPy150Open cyberdelia/peafowl/peafowl/runner.py/ProcessHelper.safe_fork |
5,667 | def is_running(self):
if not self.pid_file:
return False
try:
pid_file = open(self.pid_file, 'r')
pid = int(pid_file.read())
pid_file.close()
if pid == 0:
return False
except __HOLE__, e:
return False
... | IOError | dataset/ETHPy150Open cyberdelia/peafowl/peafowl/runner.py/ProcessHelper.is_running |
5,668 | def __getattr__(self, attr):
try:
return self._items[attr]
except __HOLE__:
raise AttributeError, attr | KeyError | dataset/ETHPy150Open tjguk/winsys/winsys/experimental/change_journal.py/Data.__getattr__ |
5,669 | def define_field(conn, table, field, pks):
"Determine field type, default value, references, etc."
f = {}
ref = references(conn, table, field['column_name'])
if ref:
f.update(ref)
elif field['column_default'] and \
field['column_default'].startswith("nextval") and \
field... | ValueError | dataset/ETHPy150Open uwdata/termite-data-server/web2py/scripts/extract_pgsql_models.py/define_field |
5,670 | def prompt_for_ip():
"""
Prompt the user to enter an IP address or "quit" to terminate the sample.
Any IP address the user enters is validated using the ipaddress module. If
the user entered an IP address the IP address string is returned, otherwise
None is returned.
"""
ip = None
while... | ValueError | dataset/ETHPy150Open ibm-security-intelligence/api-samples/siem/09_GetOffensesForIp.py/prompt_for_ip |
5,671 | @require_POST
def add_tag(request):
response = {'status': -1, 'message': ''}
try:
validstatus = valid_project(name=request.POST['name'])
if validstatus:
tag = DocumentTag.objects.create_tag(request.user, request.POST['name'])
response['name'] = request.POST['name']
response['id'] = tag.id... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/api.py/add_tag |
5,672 | @require_POST
def tag(request):
response = {'status': -1, 'message': ''}
request_json = json.loads(request.POST['data'])
try:
tag = DocumentTag.objects.tag(request.user, request_json['doc_id'], request_json.get('tag'), request_json.get('tag_id'))
response['tag_id'] = tag.id
response['status'] = 0
e... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/api.py/tag |
5,673 | @require_POST
def update_tags(request):
response = {'status': -1, 'message': ''}
request_json = json.loads(request.POST['data'])
try:
doc = DocumentTag.objects.update_tags(request.user, request_json['doc_id'], request_json['tag_ids'])
response['doc'] = massage_doc_for_json(doc, request.user)
response... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/api.py/update_tags |
5,674 | @require_POST
def remove_tag(request):
response = {'status': -1, 'message': _('Error')}
try:
DocumentTag.objects.delete_tag(request.POST['tag_id'], request.user)
response['message'] = _('Project removed!')
response['status'] = 0
except __HOLE__, e:
response['message'] = _('Form is missing %s fiel... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/api.py/remove_tag |
5,675 | @require_POST
def update_permissions(request):
response = {'status': -1, 'message': _('Error')}
data = json.loads(request.POST['data'])
doc_id = request.POST['doc_id']
try:
doc = Document.objects.get_doc_for_writing(doc_id, request.user)
doc.sync_permissions(data)
response['message'] = _('Permissi... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/src/desktop/api.py/update_permissions |
5,676 | @react.nosync
@react.input
def plot(plot):
""" The Bokeh plot object to display. In JS, this signal
provides the corresponding backbone model.
"""
try:
from bokeh.models import Plot
except __HOLE__:
from bokeh.models import PlotObject as Plot
... | ImportError | dataset/ETHPy150Open zoofIO/flexx/flexx/ui/widgets/_bokeh.py/BokehWidget.plot |
5,677 | def _build_line_mappings(self, start, finish):
forward = {}
backward = {}
# Get information about blank lines: The git diff porcelain format
# (which we use for everything else) doesn't distinguish between
# additions and removals, so this is a very dirty hack to get around
... | StopIteration | dataset/ETHPy150Open georgebrock/git-browse/gitbrowse/git.py/GitFileHistory._build_line_mappings |
5,678 | def _sign(secret, to_sign):
def portable_bytes(s):
try:
return bytes(s, 'utf-8')
except __HOLE__:
return bytes(s)
return _encode(hmac.new(portable_bytes(secret), portable_bytes(to_sign), hashlib.sha256).digest()) | TypeError | dataset/ETHPy150Open firebase/firebase-token-generator-python/firebase_token_generator.py/_sign |
5,679 | def closed(self, code, reason):
self.closed_code, self.closed_reason = code, reason
if not (self.closed_code == 1000 or getattr(self.stream.closing, 'code', None) == 1000):
try:
error = json.loads(self.closed_reason)
raise DXJobLogStreamingException("Error wh... | KeyError | dataset/ETHPy150Open dnanexus/dx-toolkit/src/python/dxpy/utils/job_log_client.py/DXJobLogStreamClient.closed |
5,680 | def _unpickle_method(func_name, obj, cls):
"""
Author: Steven Bethard
http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
"""
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except __HOLE__:
pass
else:
... | KeyError | dataset/ETHPy150Open neuropoly/spinalcordtoolbox/dev/straightening/sct_straighten_spinalcord_LargeFOVOutput.py/_unpickle_method |
5,681 | def worker_landmarks_curved(self, arguments_worker):
try:
iz = arguments_worker[0]
iz_curved, x_centerline_deriv, y_centerline_deriv, z_centerline_deriv, x_centerline_fit, y_centerline_fit, \
z_centerline = arguments_worker[1]
temp_results = []
i... | KeyboardInterrupt | dataset/ETHPy150Open neuropoly/spinalcordtoolbox/dev/straightening/sct_straighten_spinalcord_LargeFOVOutput.py/SpinalCordStraightener.worker_landmarks_curved |
5,682 | def straighten(self):
# Initialization
fname_anat = self.input_filename
fname_centerline = self.centerline_filename
fname_output = self.output_filename
gapxy = self.gapxy
gapz = self.gapz
padding = self.padding
leftright_width = self.leftright_width
... | KeyboardInterrupt | dataset/ETHPy150Open neuropoly/spinalcordtoolbox/dev/straightening/sct_straighten_spinalcord_LargeFOVOutput.py/SpinalCordStraightener.straighten |
5,683 | def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
# Parse the tokem
try:
ts_b36, hash = token.split("-")
except __HOLE__:
return False
try:
ts = base36_to_int(ts_b36)
... | ValueError | dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/auth/tokens.py/PasswordResetTokenGenerator.check_token |
5,684 | def read(self):
try:
retval = self.queue.popleft()
if self.cr.balance < 0:
self.cr.send(retval)
if isinstance(retval, bomb):
retval.raise_()
return retval
except __HOLE__:
pass
return self.cr.receive() | IndexError | dataset/ETHPy150Open benoitc/flower/flower/net/udp.py/UDPConn.read |
5,685 | def check_flakes():
try:
from pyflakes.scripts.pyflakes import main as main_pyflakes
except ImportError:
print("pyflakes not installed. Did you run pip install -r requirements_tests.txt or python develop.py --install-basic-requirements?", file=sys.stderr)
return -1
stdout = sys.stdo... | SystemExit | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/develop.py/check_flakes |
5,686 | def deploy_testdb(options):
from weblab.admin.deploy import insert_required_initial_data, populate_weblab_tests, generate_create_database, insert_required_initial_coord_data
import weblab.db.model as Model
import weblab.core.coordinator.sql.model as CoordinatorModel
import voodoo.sessions.db_lock_data ... | ImportError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/develop.py/deploy_testdb |
5,687 | def run_query(self, query):
try:
json_data = None
error = None
query = query.strip()
script = os.path.join(self.configuration["path"], query.split(" ")[0])
if not os.path.exists(script):
return None, "Script '%s' not found in script d... | KeyboardInterrupt | dataset/ETHPy150Open getredash/redash/redash/query_runner/script.py/Script.run_query |
5,688 | def hdfs_connect(host='localhost', port=50070, protocol='webhdfs',
use_https='default', auth_mechanism='NOSASL',
verify=True, **kwds):
"""
Connect to HDFS
Parameters
----------
host : string, Host name of the HDFS NameNode
port : int, NameNode's WebHDFS port (d... | ImportError | dataset/ETHPy150Open cloudera/ibis/ibis/__init__.py/hdfs_connect |
5,689 | def _extract(d, k, default=_NoDefault):
"""Get an item from a dictionary, and remove it from the dictionary."""
try:
retval = d[k]
except __HOLE__:
if default is _NoDefault:
raise
return default
del d[k]
return retval
# Generic cipher test case | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pycrypto-2.6.1/lib/Crypto/SelfTest/Cipher/common.py/_extract |
5,690 | def decode(self, s):
try:
return json.loads(s)
except __HOLE__ as e:
self.logger.error(str(e))
self.logger.error(s.strip())
raise errors.IgnoreObject(e) | ValueError | dataset/ETHPy150Open zmap/ztag/ztag/decoders/decoders.py/JSONDecoder.decode |
5,691 | def combineDicts(master,new):
"""
instead of a dict of dicts of arbitrary depth, use a dict of tuples to store.
"""
for (keysequence, valuesequence) in flatten(new):
try:
master[keysequence] = map(sum,zip(master[keysequence],valuesequence))
except __HOLE__:
maste... | KeyError | dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/MetaWorm.py/combineDicts |
5,692 | def setDefaults(self):
for specialKey in ["database","host"]:
try:
if isinstance(self.outside_dictionary[specialKey],basestring):
#coerce strings to list:
self.outside_dictionary[specialKey] = [self.outside_dictionary[specialKey]]
e... | KeyError | dataset/ETHPy150Open Bookworm-project/BookwormDB/bookwormDB/MetaWorm.py/MetaQuery.setDefaults |
5,693 | def cmd_options(cmd):
os.environ["_ARGCOMPLETE_IFS"] = "\n"
os.environ["_ARGCOMPLETE_WORDBREAKS"] = os.environ.get(
"COMP_WORDBREAKS", "")
os.environ["_ARGCOMPLETE"] = "2"
try:
mod = importlib.import_module(
".{0}".format(cmd), package="mesos.cli.cmds")
except __HOLE__:
... | ImportError | dataset/ETHPy150Open mesosphere/mesos-cli/mesos/cli/cmds/completion.py/cmd_options |
5,694 | def read(self, filename):
"""Read and parse single EditorConfig file"""
try:
fp = open(filename, encoding='utf-8')
except __HOLE__:
return
self._read(fp, filename)
fp.close() | IOError | dataset/ETHPy150Open editorconfig/editorconfig-vim/plugin/editorconfig-core-py/editorconfig/ini.py/EditorConfigParser.read |
5,695 | def stop(self):
"""
Cleans up the process
"""
if self._log:
self._log.close()
self._log = None
#If its dead dont worry
if self.process is None:
return
#Tell the Server to properly die in case
try:
if self.pr... | OSError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/selenium/webdriver/phantomjs/service.py/Service.stop |
5,696 | def install_request_logger(app, single_threaded, logger, *unlogged_prefixes):
def make_context(**kwargs):
location = request.path
if request.query_string:
location += "?" + request.query_string
return dict(
uuid = g.uuid,
method = request.method[:4],
... | ValueError | dataset/ETHPy150Open fusic-com/flask-todo/utils/flaskutils/__init__.py/install_request_logger |
5,697 | def copytree_exists(src, dst, symlinks=False,
skip_files=DEFAULT_SKIP_FILES):
if not os.path.exists(src):
return
names = os.listdir(src)
if not os.path.exists(dst):
os.mkdir(dst)
errors = []
for name in names:
srcname = os.path.join(src, name)
if ... | IOError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/util.py/copytree_exists |
5,698 | def copy_exists(srcname, dstname, symlinks=False):
if not os.path.exists(srcname):
return
errors = []
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
else:
shutil.copyfile(srcname, dstname)
... | IOError | dataset/ETHPy150Open anandology/pyjamas/pyjs/src/pyjs/util.py/copy_exists |
5,699 | @request_user_has_resource_db_permission(permission_type=PermissionType.API_KEY_VIEW)
@jsexpose(arg_types=[str])
def get_one(self, api_key_id_or_key):
"""
List api keys.
Handle:
GET /apikeys/1
"""
api_key_db = None
try:
api_key... | ValidationError | dataset/ETHPy150Open StackStorm/st2/st2api/st2api/controllers/v1/auth.py/ApiKeyController.get_one |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.