Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
0 | def run(self):
"""
Called when the process intializes.
"""
logger.info('started worker')
FULL_NAMESPACE = settings.FULL_NAMESPACE
MINI_NAMESPACE = settings.MINI_NAMESPACE
MAX_RESOLUTION = settings.MAX_RESOLUTION
full_uniques = FULL_NAMESPACE + 'unique_met... | NotImplementedError | dataset/ETHPy150Open etsy/skyline/src/horizon/worker.py/Worker.run |
1 | def create_entropies(vmx, m):
try:
default_signature = vmx.get_method_signature(m, predef_sign = DEFAULT_SIGNATURE).get_string()
l = [ default_signature,
entropy( vmx.get_method_signature(m, "L4", { "L4" : { "arguments" : ["Landroid"] } } ).get_string() ),
entropy( vmx.ge... | KeyError | dataset/ETHPy150Open androguard/androguard/androguard/core/data/data.py/create_entropies |
2 | def new_id(self, i, l):
try:
return l[i]
except __HOLE__:
l[i] = len(l)
return l[i] | KeyError | dataset/ETHPy150Open androguard/androguard/androguard/core/data/data.py/DexViewer.new_id |
3 | @property
def storage_path(self):
try:
conan_user_home = os.getenv("CONAN_USER_HOME")
if conan_user_home:
storage = self.storage["path"]
if storage[:2] == "~/":
storage = storage[2:]
result = os.path.join(conan_user_... | KeyError | dataset/ETHPy150Open conan-io/conan/conans/client/conf/__init__.py/ConanClientConfigParser.storage_path |
4 | def run_tests(tests, test_input, timeout = 60, waittime = 0.1):
"""
Runs all the tests given by directly executing them. If they return
with a non-zero exit code, it adds them to the dictionary returned.
Keyword arguments:
tests -- a list of paths to executable test files
test_input -- ... | IOError | dataset/ETHPy150Open gosquadron/squadron/squadron/tests.py/run_tests |
5 | def git_version():
def _minimal_ext_cmd(cmd):
# construct minimal environment
env = {}
for k in ['SYSTEMROOT', 'PATH']:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env['LANGUAGE'] = 'C'
env['LA... | OSError | dataset/ETHPy150Open dnlcrl/PyFunt/setup.py/git_version |
6 | def setup_package():
# Rewrite the version file every time
write_version_py()
cmdclass = {}
# Figure out whether to add ``*_requires = ['numpy']``.
# We don't want to do that unconditionally, because we risk updating
# an installed numpy which fails too often. Just if it's not installed, we
... | ImportError | dataset/ETHPy150Open dnlcrl/PyFunt/setup.py/setup_package |
7 | def exclude(self, excludes):
"""Takes a list of node names and removes all nodes and their
successors from the graph.
:param excludes: list of node names
:type excludes: list of string
"""
if not excludes:
return
if not isinstance(excludes, (list, tup... | KeyError | dataset/ETHPy150Open thasso/pyjip/jip/pipelines.py/Pipeline.exclude |
8 | def download(uri, filename=None, headers=None, redirect_limit=5, **kwargs):
""" Get a remote resource and save the content to a local file. If a local
file already exists at the download destination, the modification time of
that file is sent in the request headers as the `If-Modified-Since` value
to pe... | OSError | dataset/ETHPy150Open nigelsmall/py2neo/py2neo/packages/httpstream/__init__.py/download |
9 | def ReadFile(filename, logger=None):
"""Read the contents of the file.
An optional logger can be specified to emit messages to your favorite logging
stream. If specified, then no exception is raised. This is external so that it
can be used by third-party applications.
Arguments:
filename: (unicode) The ... | IOError | dataset/ETHPy150Open google/yapf/yapf/yapflib/yapf_api.py/ReadFile |
10 | @view(path=r'^themes/?$')
def index(request):
order = request.GET.get('order', '')
if not order in ['downloads', 'date']:
order = 'downloads'
nameFilter = request.GET.get('filter', '')
try:
page = int(request.GET.get('page', '1'))
except __HOLE__:
page = 1
themes, page,... | ValueError | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/views/themes.py/index |
11 | def payment_successful_handler(sender, **kwargs):
if sender.payment_status == "Completed":
try:
token = ShoppingToken.objects.get(value=sender.invoice)
token.payed = True
token.save()
except __HOLE__:
pass | ObjectDoesNotExist | dataset/ETHPy150Open y-a-r-g/idea-color-themes/backend/views/themes.py/payment_successful_handler |
12 | def test_numparser_strict():
parsenumber = numparser(strict=True)
assert parsenumber('1') == 1
assert parsenumber('1.0') == 1.0
assert parsenumber(str(maxint + 1)) == maxint + 1
assert parsenumber('3+4j') == 3 + 4j
try:
parsenumber('aaa')
except __HOLE__:
pass # expected
... | ValueError | dataset/ETHPy150Open alimanfoo/petl/petl/test/util/test_parsers.py/test_numparser_strict |
13 | def test_laxparsers():
p1 = datetimeparser('%Y-%m-%dT%H:%M:%S')
try:
p1('2002-12-25 00:00:00')
except ValueError:
pass
else:
assert False, 'expected exception'
p2 = datetimeparser('%Y-%m-%dT%H:%M:%S', strict=False)
try:
v = p2('2002-12-25 00:00:00')
except _... | ValueError | dataset/ETHPy150Open alimanfoo/petl/petl/test/util/test_parsers.py/test_laxparsers |
14 | def logout(self, request):
try:
request.user.auth_token.delete()
except (__HOLE__, ObjectDoesNotExist):
pass
logout(request)
return Response({"success": _("Successfully logged out.")},
status=status.HTTP_200_OK) | AttributeError | dataset/ETHPy150Open Tivix/django-rest-auth/rest_auth/views.py/LogoutView.logout |
15 | def search_external_subtitles(path, directory=None):
"""Search for external subtitles from a video `path` and their associated language.
Unless `directory` is provided, search will be made in the same directory as the video file.
:param str path: path to the video.
:param str directory: directory to s... | ValueError | dataset/ETHPy150Open Diaoul/subliminal/subliminal/video.py/search_external_subtitles |
16 | def scan_videos(path, subtitles=True, embedded_subtitles=True, subtitles_dir=None):
"""Scan `path` for videos and their subtitles.
:param str path: existing directory path to scan.
:param bool subtitles: scan for subtitles with the same name.
:param bool embedded_subtitles: scan for embedded subtitles.... | ValueError | dataset/ETHPy150Open Diaoul/subliminal/subliminal/video.py/scan_videos |
17 | def _ParseQueueYaml(self):
"""Loads the queue.yaml file and parses it.
Returns:
None if queue.yaml doesn't exist, otherwise a queueinfo.QueueEntry object
populated from the queue.yaml.
"""
if hasattr(self, 'queue_yaml_parser'):
return self.queue_yaml_parser(self._root_path)
if... | OSError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/taskqueue/taskqueue_stub.py/TaskQueueServiceStub._ParseQueueYaml |
18 | def add_image_info_cb(self, viewer, channel, image_info):
"""Almost the same as add_image_info(), except that the image
may not be loaded in memory.
"""
chname = channel.name
name = image_info.name
self.logger.debug("name=%s" % (name))
# Updates of any extant inf... | KeyError | dataset/ETHPy150Open ejeschke/ginga/ginga/misc/plugins/Contents.py/Contents.add_image_info_cb |
19 | def asm(chrom, start, end, bamfilename, reffile, kmersize, tmpdir, mutid='null', debug=False):
bamfile = pysam.Samfile(bamfilename,'rb')
matefile = pysam.Samfile(bamfilename,'rb')
readpairs = {}
nreads = 0
ndisc = 0 # track discordant reads
rquals = []
mquals = []
for read in bamfil... | ValueError | dataset/ETHPy150Open adamewing/bamsurgeon/bamsurgeon/asmregion.py/asm |
20 | def circuit_built(self, circuit):
"""ICircuitListener API"""
# older tor versions will have empty build_flags
if 'ONEHOP_TUNNEL' in circuit.build_flags:
return
if circuit.purpose == 'GENERAL':
if len(circuit.path) > 0:
if circuit.path[0] not in se... | KeyError | dataset/ETHPy150Open meejah/txtorcon/examples/circuit_failure_rates.py/CircuitFailureWatcher.circuit_built |
21 | def circuit_failed(self, circuit, kw):
"""ICircuitListener API"""
if kw['REASON'] != 'MEASUREMENT_EXPIRED':
return
# older tor versions will have empty build_flags
if 'ONEHOP_TUNNEL' in circuit.build_flags:
return
if circuit.purpose == 'GENERAL':
... | KeyError | dataset/ETHPy150Open meejah/txtorcon/examples/circuit_failure_rates.py/CircuitFailureWatcher.circuit_failed |
22 | @nif_blueprint.route('/', methods=['POST', 'GET'])
def home():
try:
params = get_params(request)
algo = params.get("algorithm", None)
specific_params = current_app.senpy.parameters(algo)
logger.debug(
"Specific params: %s", json.dumps(specific_params, indent=4))
p... | ValueError | dataset/ETHPy150Open gsi-upm/senpy/senpy/blueprints.py/home |
23 | def automoderate(instance, user):
'''
Auto moderates given model instance on user. Returns moderation status:
0 - Rejected
1 - Approved
'''
try:
status = instance.moderated_object.automoderate(user)
except __HOLE__:
msg = "%s has been registered with Moderation." % instance._... | AttributeError | dataset/ETHPy150Open dominno/django-moderation/moderation/helpers.py/automoderate |
24 | def import_moderator(app):
'''
Import moderator module and register all models it contains with moderation
'''
from django.utils.importlib import import_module
import imp
try:
app_path = import_module(app).__path__
except __HOLE__:
return None
try:
imp.find_modu... | AttributeError | dataset/ETHPy150Open dominno/django-moderation/moderation/helpers.py/import_moderator |
25 | def parse_request(self):
"""Parse a request (internal).
The request should be stored in self.raw_requestline; the results
are in self.command, self.path, self.request_version and
self.headers.
Return True for success, False for failure; on failure, an
error is sent back... | IndexError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/BaseHTTPRequestHandler.parse_request |
26 | def send_error(self, code, message=None):
"""Send and log an error reply.
Arguments are the error code, and a detailed message.
The detailed message defaults to the short entry matching the
response code.
This sends an error response (so it must be called before any
out... | KeyError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/BaseHTTPRequestHandler.send_error |
27 | def send_head(self):
"""Common code for GET and HEAD commands.
This sends the response code and MIME headers.
Return value is either a file object (which has to be copied
to the outputfile by the caller unless the command was HEAD,
and must be closed by the caller under all cir... | IOError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/SimpleHTTPRequestHandler.send_head |
28 | def nobody_uid():
"""Internal routine to get nobody's uid"""
global nobody
if nobody:
return nobody
try:
import pwd
except __HOLE__:
return -1
try:
nobody = pwd.getpwnam('nobody')[2]
except KeyError:
nobody = 1 + max(x[2] for x in pwd.getpwall())
r... | ImportError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/nobody_uid |
29 | def run_cgi(self):
"""Execute a CGI script."""
path = self.path
dir, rest = self.cgi_info
i = path.find('/', len(dir) + 1)
while i >= 0:
nextdir = path[:i]
nextrest = path[i+1:]
scriptdir = self.translate_path(nextdir)
if os.path.... | ValueError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/CGIHTTPRequestHandler.run_cgi |
30 | def test(HandlerClass = BaseHTTPRequestHandler,
ServerClass = HTTPServer, protocol="HTTP/1.0", port=8000):
"""Test the HTTP request handler class.
This runs an HTTP server on port 8000 (or the first command line
argument).
"""
server_address = ('', port)
HandlerClass.protocol_version... | KeyboardInterrupt | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/future/backports/http/server.py/test |
31 | def get_object_from_identifier(identifier, valid=None):
""" Helper function to resolve an item identifier
into a model instance.
Raises StoreException if the identifier is invalid
or the requested Model could not be found
Raises <Model>.DoesNotExist if the object lookup fails
... | ValueError | dataset/ETHPy150Open klipstein/dojango/dojango/data/modelstore/utils.py/get_object_from_identifier |
32 | def get_fields_and_servicemethods(bases, attrs, include_bases=True):
""" This function was pilfered (and slightly modified) from django/forms/forms.py
See the original function for doc and comments.
"""
fields = [ (field_name, attrs.pop(field_name)) for \
field_name, obj in attrs.items() if ... | AttributeError | dataset/ETHPy150Open klipstein/dojango/dojango/data/modelstore/utils.py/get_fields_and_servicemethods |
33 | def GetCaParameters(settings, ca_id=0, omit_server_private_key=False):
"""Get ca/cert parameters for CA named ca_id.
Note, subtle: If no ca_id value is supplied, the default value from
settings.CA_ID is used for the ca_id. This value might make the chosen
parameters be NOT from the defaults (no prefix on the ... | AttributeError | dataset/ETHPy150Open google/simian/src/simian/auth/util.py/GetCaParameters |
34 | def setup_config(config_dir):
""" Setup configuration directory. """
config_dir = os.path.abspath(config_dir)
if not os.path.isdir(config_dir):
try:
os.mkdir(config_dir)
except OSError as err:
print('Polyglot could not create configuration directory.')
pri... | OSError | dataset/ETHPy150Open UniversalDevicesInc/Polyglot/polyglot/__main__.py/setup_config |
35 | def run_ginkgo():
parser = argparse.ArgumentParser(prog="ginkgo", add_help=False)
parser.add_argument("-v", "--version",
action="version", version="%(prog)s {}".format(ginkgo.__version__))
parser.add_argument("-h", "--help", action="store_true", help="""
show program's help text and exit
... | RuntimeError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/run_ginkgo |
36 | def run_ginkgoctl():
parser = argparse.ArgumentParser(prog="ginkgoctl")
parser.add_argument("-v", "--version",
action="version", version="%(prog)s {}".format(ginkgo.__version__))
parser.add_argument("-p", "--pid", help="""
pid or pidfile to use instead of target
""".strip())
pars... | RuntimeError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/run_ginkgoctl |
37 | def load_class(class_path):
if '.' not in class_path:
raise RuntimeError("Invalid class path")
module_name, class_name = class_path.rsplit('.', 1)
try:
try:
module = runpy.run_module(module_name)
except ImportError:
module = runpy.run_module(module_name + ".__... | KeyError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/load_class |
38 | def resolve_target(target):
if target.endswith('.py'):
if os.path.exists(target):
config = ginkgo.settings.load_file(target)
try:
return config['service']
except __HOLE__:
raise RuntimeError(
"Configuration does not spec... | KeyError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/resolve_target |
39 | def start(self, target, daemonize=True):
print "Starting process with {}...".format(target)
app = setup_process(target, daemonize)
try:
app.serve_forever()
except __HOLE__:
pass
finally:
app.stop() | KeyboardInterrupt | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface.start |
40 | def _validate(self, pid):
try:
os.kill(pid, 0)
return pid
except (__HOLE__, TypeError):
print "Process is NOT running." | OSError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface._validate |
41 | def logtail(self, target):
try:
app = setup_process(target)
app.logger.tail_log()
except __HOLE__:
pass | KeyboardInterrupt | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/ControlInterface.logtail |
42 | def do_reload(self):
try:
self.config.reload_file()
self.logger.load_config()
except __HOLE__, e:
logger.warn(e) | RuntimeError | dataset/ETHPy150Open progrium/ginkgo/ginkgo/runner.py/Process.do_reload |
43 | def make_all(self, profiler=None, input_storage=None,
output_storage=None, storage_map=None):
# can't import at toplevel because of circular import TODO:
# don't do this ugly hacky way of setting the
# filter_checks_isfinite
from theano.tensor import TensorType # to set... | NotImplementedError | dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/compile/debugmode.py/_Linker.make_all |
44 | def GenerateOutput(target_list, target_dicts, data, params):
user_config = params.get('generator_flags', {}).get('config', None)
if user_config:
GenerateOutputForConfig(target_list, target_dicts, data,
params, user_config)
else:
config_names = target_dicts[target_list[0]]['conf... | KeyboardInterrupt | dataset/ETHPy150Open francelabs/datafari/debian7/elk/kibana/node/lib/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/cmake.py/GenerateOutput |
45 | @staticmethod
def load(path, name, cluster):
"""
Load a node from from the path on disk to the config files, the node name and the
cluster the node is part of.
"""
node_path = os.path.join(path, name)
filename = os.path.join(node_path, 'node.conf')
with open(f... | KeyError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.load |
46 | def print_process_output(self, name, proc, verbose=False):
try:
stderr = proc.communicate()[1]
except __HOLE__:
stderr = ''
if len(stderr) > 1:
print_("[%s ERROR] %s" % (name, stderr.strip()))
# This will return when exprs are found or it timeouts | ValueError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.print_process_output |
47 | def stress(self, stress_options=None, capture_output=False, whitelist=False,**kwargs):
if stress_options is None:
stress_options = []
else:
stress_options = stress_options[:]
stress = common.get_stress_bin(self.get_install_dir())
if self.cluster.cassandra_version... | KeyboardInterrupt | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.stress |
48 | def shuffle(self, cmd):
cdir = self.get_install_dir()
shuffle = common.join_bin(cdir, 'bin', 'cassandra-shuffle')
host = self.address()
args = [shuffle, '-h', host, '-p', str(self.jmx_port)] + [cmd]
try:
subprocess.call(args)
except __HOLE__:
pass | KeyboardInterrupt | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.shuffle |
49 | def __update_status(self):
if self.pid is None:
if self.status == Status.UP or self.status == Status.DECOMMISSIONED:
self.status = Status.DOWN
return
old_status = self.status
# os.kill on windows doesn't allow us to ping a process
if common.is_wi... | OSError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.__update_status |
50 | def _find_pid_on_windows(self):
found = False
try:
import psutil
found = psutil.pid_exists(self.pid)
except __HOLE__:
print_("WARN: psutil not installed. Pid tracking functionality will suffer. See README for details.")
cmd = 'tasklist /fi "PID eq ... | ImportError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node._find_pid_on_windows |
51 | def _update_pid(self, process):
pidfile = os.path.join(self.get_path(), 'cassandra.pid')
start = time.time()
while not (os.path.isfile(pidfile) and os.stat(pidfile).st_size > 0):
if (time.time() - start > 30.0):
print_("Timed out waiting for pidfile to be filled (cur... | IOError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node._update_pid |
52 | def pause(self):
try:
import psutil
p = psutil.Process(self.pid)
p.suspend()
except __HOLE__:
if common.is_win():
print_("WARN: psutil not installed. Pause functionality will not work properly on Windows.")
else:
... | ImportError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.pause |
53 | def resume(self):
try:
import psutil
p = psutil.Process(self.pid)
p.resume()
except __HOLE__:
if common.is_win():
print_("WARN: psutil not installed. Resume functionality will not work properly on Windows.")
else:
... | ImportError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/Node.resume |
54 | def _get_load_from_info_output(info):
load_lines = [s for s in info.split('\n')
if s.startswith('Load')]
if not len(load_lines) == 1:
msg = ('Expected output from `nodetool info` to contain exactly 1 '
'line starting with "Load". Found:\n') + info
raise RuntimeEr... | KeyError | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/_get_load_from_info_output |
55 | def _grep_log_for_errors(log):
matchings = []
it = iter(log.splitlines())
for line in it:
is_error_line = ('ERROR' in line
and 'DEBUG' not in line.split('ERROR')[0])
if is_error_line:
matchings.append([line])
try:
it, peeker = ... | StopIteration | dataset/ETHPy150Open pcmanus/ccm/ccmlib/node.py/_grep_log_for_errors |
56 | def _get__data_sources_names(self):
names = []
for name in self.data_sources:
try:
self.data_sources[name] + 1
names.append(name)
except __HOLE__:
pass
names.sort()
return names
# Dictionnary mapping the views | TypeError | dataset/ETHPy150Open enthought/mayavi/mayavi/tools/data_wizards/data_source_wizard.py/DataSourceWizard._get__data_sources_names |
57 | def _findNode(self, nodeId):
try:
return self.getDispatchTree().nodes[int(nodeId)]
except __HOLE__:
raise NodeNotFoundError(nodeId) | KeyError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodesResource._findNode |
58 | def iterOnCommands(self):
"""
Cancel each command in a node hierarchy (command is given by a generator on the node)
Each command might be blocked by network pb (or machine swapping) but asynchronous mecanism will
allow other request to be treated between each command cancelation.
... | StopIteration | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodeStatusResource.iterOnCommands |
59 | def put(self, nodeId):
data = self.getBodyAsJSON()
try:
paused = data['paused']
except __HOLE__:
raise Http400('Missing entry: "paused".')
except TypeError:
raise Http400('Missing entry: "paused".')
else:
nodeId = int(nodeId)
... | KeyError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodePausedResource.put |
60 | def put(self, nodeId):
'''
| Put a new value for the maxAttempt attribute of a task node
| The new maxAttempt value is taken from request body, for instance : "{ maxAttempt : 10 }"
:param nodeId: id of the task node to update
'''
# Get task object
try:
... | KeyError | dataset/ETHPy150Open mikrosimage/OpenRenderManagement/src/octopus/dispatcher/webservice/nodes.py/NodeMaxAttemptResource.put |
61 | def __getattr__(self, key):
try:
return self[key]
except __HOLE__:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key) | KeyError | dataset/ETHPy150Open michaelliao/transwarp/transwarp/utils.py/Dict.__getattr__ |
62 | def test_options_without_type(self):
query = self.session.query(self.Character.name).filter(
match({self.Character.name: 0.5, self.Character.info['race']: 0.9},
'Trillian',
options={'boost': 10.0})
)
err = None
try:
str(query)
... | ValueError | dataset/ETHPy150Open crate/crate-python/src/crate/client/sqlalchemy/tests/match_test.py/SqlAlchemyMatchTest.test_options_without_type |
63 | def conv_TimeField(self, model, field, kwargs):
def time_only(obj):
try:
return obj.time()
except __HOLE__:
return obj
kwargs['filters'].append(time_only)
return f.DateTimeField(widget=form.DateTimePickerWidget(),
... | AttributeError | dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_TimeField |
64 | def conv_DateTimeField(self, model, field, kwargs):
def time_only(obj):
try:
return obj.time()
except __HOLE__:
return obj
kwargs['filters'].append(time_only)
return f.DateTimeField(widget=form.DateTimePickerWidget(),
... | AttributeError | dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_DateTimeField |
65 | def conv_DateField(self, model, field, kwargs):
def time_only(obj):
try:
return obj.date()
except __HOLE__:
return obj
kwargs['filters'].append(time_only)
return f.DateField(widget=form.DatePickerWidget(), **kwargs) | AttributeError | dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_DateField |
66 | def conv_USStateField(self, model, field, kwargs):
try:
from django.contrib.localflavor.us.us_states import STATE_CHOICES
except __HOLE__:
STATE_CHOICES = []
return f.SelectField(choices=STATE_CHOICES, **kwargs) | ImportError | dataset/ETHPy150Open syrusakbary/Flask-SuperAdmin/flask_superadmin/model/backends/django/orm.py/AdminModelConverter.conv_USStateField |
67 | def refresh(self):
"""
Refresh the screen.
"""
super(_CursesScreen, self).refresh()
try:
sys.stdout.flush()
except __HOLE__:
pass | IOError | dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_CursesScreen.refresh |
68 | def _print_at(self, text, x, y):
"""
Print string at the required location.
:param text: The text string to print.
:param x: The x coordinate
:param y: The Y coordinate
"""
# Move the cursor if necessary
msg = ""
... | IOError | dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_CursesScreen._print_at |
69 | def refresh(self):
"""
Refresh the screen.
"""
# Flush screen buffer to get all updates after doing the common
# processing. Exact timing of the signal can interrupt the
# flush, raising an EINTR IOError, which we can safely ignore.
su... | IOError | dataset/ETHPy150Open peterbrittain/asciimatics/asciimatics/screen.py/_BlessedScreen.refresh |
70 | def get_order_for_user_or_404(user, number):
try:
return queryset_orders_for_user(user).get(number=number)
except __HOLE__:
raise Http404() | ObjectDoesNotExist | dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/get_order_for_user_or_404 |
71 | def handle_line_action(self, request, order, action):
if action not in self.line_actions:
return self.reload_page(error=_("Invalid action"))
# Load requested lines
line_ids = request.POST.getlist('selected_line')
if len(line_ids) == 0:
return self.reload_page(err... | ValueError | dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/OrderDetailView.handle_line_action |
72 | def delete_note(self, request, order):
try:
note = order.notes.get(id=request.POST.get('note_id', None))
except __HOLE__:
messages.error(request, _("Note cannot be deleted"))
else:
messages.info(request, _("Note deleted"))
note.delete()
ret... | ObjectDoesNotExist | dataset/ETHPy150Open django-oscar/django-oscar/src/oscar/apps/dashboard/orders/views.py/OrderDetailView.delete_note |
73 | def _populate_port_ha_information(self, context, port, router_id, hags,
user_router_id, modified_interfaces):
subnet_id = port['fixed_ips'][0]['subnet_id']
try:
hag = hags[subnet_id]
except __HOLE__:
# Oops, the subnet_id was not foun... | KeyError | dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/db/l3/ha_db.py/HA_db_mixin._populate_port_ha_information |
74 | @gen_test
def test_websocket_handler_bad_token(self):
"""
A bad token should returns a 401 during a websocket connect
"""
token = 'A'*32
url = 'ws://127.0.0.1:{0}/hook/{1}'.format(self.get_http_port(), token)
request = HTTPRequest(url, headers={'Origin': 'http://exam... | HTTPError | dataset/ETHPy150Open saltstack/salt/tests/unit/netapi/rest_tornado/test_handlers.py/TestWebsocketSaltAPIHandler.test_websocket_handler_bad_token |
75 | @gen_test
def test_cors_origin_single(self):
self._app.mod_opts['cors_origin'] = 'http://example.com'
response = yield self.http_client.fetch(self.get_url('/login'),
method='POST',
body=urlencode(self.au... | HTTPError | dataset/ETHPy150Open saltstack/salt/tests/unit/netapi/rest_tornado/test_handlers.py/TestWebsocketSaltAPIHandler.test_cors_origin_single |
76 | @workflow
def operation_mapping3(ctx, value, **_):
def expect_error(func):
try:
func('test.operation', kwargs={
'value': value
}).get()
except __HOLE__, e:
assert 'Duplicate' in e.message
node1 = list(ctx.get_node('node1').instances)[0]
no... | RuntimeError | dataset/ETHPy150Open cloudify-cosmo/cloudify-manager/tests/mock_plugins/mock_workflows/workflows.py/operation_mapping3 |
77 | def is_superuser_staff_or_in_translators_group(user):
if not getattr(settings, 'ROSETTA_REQUIRES_AUTH', True):
return True
try:
if not user.is_authenticated():
return False
elif user.is_superuser and user.is_staff:
return True
else:
return user... | AttributeError | dataset/ETHPy150Open mbi/django-rosetta/rosetta/access.py/is_superuser_staff_or_in_translators_group |
78 | def can_translate_language(user, langid):
try:
if not rosetta_settings.ROSETTA_LANGUAGE_GROUPS:
return can_translate(user)
elif not user.is_authenticated():
return False
elif user.is_superuser and user.is_staff:
return True
else:
return... | AttributeError | dataset/ETHPy150Open mbi/django-rosetta/rosetta/access.py/can_translate_language |
79 | def create_authn_response(self, identity, in_response_to, destination,
sp_entity_id, name_id_policy=None, userid=None,
name_id=None, authn=None, issuer=None,
sign_response=None, sign_assertion=None,
e... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.create_authn_response |
80 | def create_assertion_id_request_response(self, assertion_id, sign=False,
**kwargs):
"""
:param assertion_id:
:param sign:
:return:
"""
try:
(assertion, to_sign) = self.session_db.get_assertion(assertion_id)
... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.create_assertion_id_request_response |
81 | def clean_out_user(self, name_id):
"""
Remove all authentication statements that belongs to a user identified
by a NameID instance
:param name_id: NameID instance
:return: The local identifier for the user
"""
lid = self.ident.find_local_id(name_id)
logg... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/server.py/Server.clean_out_user |
82 | def cpu_count():
'''
Returns the number of CPUs in the system
'''
if sys.platform == 'win32':
try:
num = int(os.environ['NUMBER_OF_PROCESSORS'])
except (ValueError, KeyError):
num = 0
elif 'bsd' in sys.platform or sys.platform == 'darwin':
comm = '/sbi... | ValueError | dataset/ETHPy150Open benoitc/flower/flower/util.py/cpu_count |
83 | def extract_text(escaped_html_str):
notes = xml.sax.saxutils.unescape(escaped_html_str)
try:
from PyQt4 import QtGui
except __HOLE__:
return str(notes)
else:
fragment = QtGui.QTextDocumentFragment.fromHtml(notes)
return str(fragment.toPlainText())
# The queries are old a... | ImportError | dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/query/__init__.py/extract_text |
84 | @defer.inlineCallbacks
def on_PUT(self, request, txn_id):
try:
defer.returnValue(
self.txns.get_client_transaction(request, txn_id)
)
except __HOLE__:
pass
response = yield self.on_POST(request)
self.txns.store_client_transaction(... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomCreateRestServlet.on_PUT |
85 | @defer.inlineCallbacks
def on_PUT(self, request, room_id, event_type, txn_id):
try:
defer.returnValue(
self.txns.get_client_transaction(request, txn_id)
)
except __HOLE__:
pass
response = yield self.on_POST(request, room_id, event_type, tx... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomSendEventRestServlet.on_PUT |
86 | @defer.inlineCallbacks
def on_PUT(self, request, room_identifier, txn_id):
try:
defer.returnValue(
self.txns.get_client_transaction(request, txn_id)
)
except __HOLE__:
pass
response = yield self.on_POST(request, room_identifier, txn_id)
... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/JoinRoomAliasServlet.on_PUT |
87 | @defer.inlineCallbacks
def on_PUT(self, request, room_id, membership_action, txn_id):
try:
defer.returnValue(
self.txns.get_client_transaction(request, txn_id)
)
except __HOLE__:
pass
response = yield self.on_POST(
request, roo... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomMembershipRestServlet.on_PUT |
88 | @defer.inlineCallbacks
def on_PUT(self, request, room_id, event_id, txn_id):
try:
defer.returnValue(
self.txns.get_client_transaction(request, txn_id)
)
except __HOLE__:
pass
response = yield self.on_POST(request, room_id, event_id, txn_id... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/rest/client/v1/room.py/RoomRedactEventRestServlet.on_PUT |
89 | def get_connection(self, address):
try:
return self.connections[address]
except __HOLE__:
return None | KeyError | dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.get_connection |
90 | def get_or_connect(self, address, authenticator=None):
if address in self.connections:
return ImmediateFuture(self.connections[address])
else:
with self._new_connection_mutex:
if address in self._pending_connections:
return self._pending_connec... | KeyError | dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.get_or_connect |
91 | def close_connection(self, address, cause):
try:
connection = self.connections[address]
connection.close(cause)
except __HOLE__:
logging.warn("No connection with %s was found to close.", address)
return False | KeyError | dataset/ETHPy150Open hazelcast/hazelcast-python-client/hazelcast/connection.py/ConnectionManager.close_connection |
92 | def _inner_acquire(self, blocking, timeout):
# make sure our election parent node exists
if not self.assured_path:
self._ensure_path()
node = None
if self.create_tried:
node = self._find_node()
else:
self.create_tried = True
if not no... | ValueError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/kazoo-2.0/kazoo/recipe/lock.py/Lock._inner_acquire |
93 | def _ensure_path(self):
result = self.client.ensure_path(self.path)
self.assured_path = True
if result is True:
# node did already exist
data, _ = self.client.get(self.path)
try:
leases = int(data.decode('utf-8'))
except (ValueError... | TypeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/kazoo-2.0/kazoo/recipe/lock.py/Semaphore._ensure_path |
94 | def get_partition_names(self, model):
current = model._partition_manager.current_partition_key
next = model._partition_manager.next_partition_key
current_only = self.options.get('current_only')
next_only = self.options.get('next_only')
if current_only and next_only:
... | IndexError | dataset/ETHPy150Open danfairs/django-parting/parting/management/commands/ensure_partition.py/Command.get_partition_names |
95 | def get_model(self):
try:
model = self.args[0]
except IndexError:
raise CommandError(u'Please supply at least one partitioned model')
try:
module_name, model_name = model.rsplit('.', 1)
except ValueError:
raise CommandError('Bad model name... | AttributeError | dataset/ETHPy150Open danfairs/django-parting/parting/management/commands/ensure_partition.py/Command.get_model |
96 | @logging_level.setter
def logging_level(self, value):
if value is None:
value = self._default_logging_level
if type(value) is str:
try:
level = _levelNames[value.upper()]
except KeyError:
raise ValueError('Unrecognized logging level... | ValueError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.logging_level |
97 | @property
def search_results_info(self):
""" Returns the search results info for this command invocation or None.
The search results info object is created from the search results info
file associated with the command invocation. Splunk does not pass the
location of this file by def... | ValueError | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.search_results_info |
98 | def process(self, args=argv, input_file=stdin, output_file=stdout):
""" Processes search results as specified by command arguments.
:param args: Sequence of command arguments
:param input_file: Pipeline input file
:param output_file: Pipeline output file
"""
self.logger... | SystemExit | dataset/ETHPy150Open hvandenb/splunk-elasticsearch/search-elasticsearch/bin/splunklib/searchcommands/search_command.py/SearchCommand.process |
99 | def create_transformer_classes(transformer_spec, config_globals, increment_id):
"""Create an importer and exporter class from a transformer spec.
Args:
transformer_spec: A bulkloader_parser.TransformerEntry.
config_globals: Dict to use to reference globals for code in the config.
increment_id: Method I... | NameError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/bulkload/bulkloader_config.py/create_transformer_classes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.