Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
1,100 | def get_inet_num(search_term):
"""
Get intetnums for a domain
:param search_term: keywork without dots, no domains are allowed. domain.com -> invalid |---| domain -> valid
:type search_term: str
:return: iterable with IP/CIDR notation or None
:rtype: list(str) | None
"""
# Disable request logging
request... | KeyError | dataset/ETHPy150Open cr0hn/enteletaor/enteletaor_lib/libs/contrib/inetnum.py/get_inet_num |
1,101 | def __init__(self, title='Plugin Editor', default_path=None, parent=None):
QDockWidget.__init__(self, title, parent)
self.setupUi()
self.thread_manager = ThreadManager(self)
try:
self.rope_project = codeeditor.get_rope_project()
except (__HOLE__, AttributeError): # ... | IOError | dataset/ETHPy150Open rproepp/spykeviewer/spykeviewer/ui/plugin_editor_dock.py/PluginEditorDock.__init__ |
1,102 | def _setup_editor(self):
font = QFont('Some font that does not exist')
font.setStyleHint(font.TypeWriter, font.PreferDefault)
editor = codeeditor.CodeEditor(self)
try:
editor.setup_editor(
linenumbers=True, language='py',
scrollflagarea=False,
... | TypeError | dataset/ETHPy150Open rproepp/spykeviewer/spykeviewer/ui/plugin_editor_dock.py/PluginEditorDock._setup_editor |
1,103 | def save_file(self, editor, force_dialog=False):
""" Save the file from an editor object.
:param editor: The editor for which the while should be saved.
:param bool force_dialog: If True, a "Save as..." dialog will be
shown even if a file name is associated with the editor.
... | IOError | dataset/ETHPy150Open rproepp/spykeviewer/spykeviewer/ui/plugin_editor_dock.py/PluginEditorDock.save_file |
1,104 | def check_package(self, package, package_dir):
"""Check namespace packages' __init__ for declare_namespace"""
try:
return self.packages_checked[package]
except __HOLE__:
pass
init_py = orig.build_py.check_package(self, package, package_dir)
self.packages_... | KeyError | dataset/ETHPy150Open chalasr/Flask-P2P/venv/lib/python2.7/site-packages/setuptools/command/build_py.py/build_py.check_package |
1,105 | def get_rc_exc(rc):
rc = int(rc)
try: return rc_exc_cache[rc]
except __HOLE__: pass
name = "ErrorReturnCode_%d" % rc
exc = type(name, (ErrorReturnCode,), {})
rc_exc_cache[rc] = exc
return exc | KeyError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/packages/pbs.py/get_rc_exc |
1,106 | def _format_arg(self, arg):
if IS_PY3:
arg = str(arg)
else:
try:
arg = unicode(arg, DEFAULT_ENCODING).encode(DEFAULT_ENCODING)
except __HOLE__:
arg = unicode(arg).encode(DEFAULT_ENCODING)
if self._partial:
escaped =... | TypeError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/packages/pbs.py/Command._format_arg |
1,107 | def bake(self, *args, **kwargs):
fn = Command(self._path)
fn._partial = True
call_args, kwargs = self._extract_call_args(kwargs)
pruned_call_args = call_args
for k,v in Command.call_args.items():
try:
if pruned_call_args[k] == v:
... | KeyError | dataset/ETHPy150Open chrippa/livestreamer/src/livestreamer/packages/pbs.py/Command.bake |
1,108 | def crawl():
"""
Initialize all crawlers (and indexers).
Start the:
1. GitHub crawler, :class:`crawler.GitHubCrawler`.
2. Bitbucket crawler, :class:`crawler.BitbucketCrawler`.
3. Git indexer, :class:`bitshift.crawler.indexer.GitIndexer`.
"""
_configure_logging()
time.sleep(5)
... | KeyboardInterrupt | dataset/ETHPy150Open earwig/bitshift/bitshift/crawler/crawl.py/crawl |
1,109 | def get_champions_by_id(ids):
"""
Gets a bunch of champions by ID
Args:
ids (list<int>): the IDs of the champions to get
Returns:
list<Champion>: the requested champions
"""
champions = {champ.id: champ for champ in get_champions()}
results = []
for id_ in ids:
... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_champions_by_id |
1,110 | def get_champions_by_name(names):
"""
Gets a bunch of champions by name
Args:
names (list<str>): the names of the champions to get
Returns:
list<Champion>: the requested champions
"""
indices = {names[i]: i for i in range(len(names))}
champions = get_champions()
result... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_champions_by_name |
1,111 | def get_items(ids=None):
"""
Gets a bunch of items (or all of them)
Args:
ids (list<int>): the IDs of the items to get (or None to get all items) (default None)
Returns:
list<Item>: the items
"""
if ids is not None:
items = {item.id: item for item in get_items()}
... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_items |
1,112 | def get_masteries(ids=None):
"""
Gets a bunch of masteries (or all of them)
Args:
ids (list<int>): the IDs of the masteries to get (or None to get all masteries) (default None)
Returns:
list<Mastery>: the masteries
"""
if ids is not None:
masteries = {mastery.id: master... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_masteries |
1,113 | def get_runes(ids=None):
"""
Gets a bunch of runes (or all of them)
Args:
ids (list<int>): the IDs of the runes to get (or None to get all runes) (default None)
Returns:
list<Rune>: the runes
"""
if ids is not None:
runes = {rune.id: rune for rune in get_runes()}
... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_runes |
1,114 | def get_summoner_spells(ids=None):
"""
Gets a bunch of summoner spells (or all of them)
Args:
ids (list<int>): the IDs of the summoner spells to get (or None to get all summoner spells) (default None)
Returns:
list<SummonerSpell>: the summoner spells
"""
if ids is not None:
... | KeyError | dataset/ETHPy150Open meraki-analytics/cassiopeia/cassiopeia/core/staticdataapi.py/get_summoner_spells |
1,115 | def run(self, module_config):
if hasattr(self, "__submodules__"):
try:
self.__submodules__[module_config.sub_action]['action'](module_config)
except __HOLE__:
self.__submodules__["default"]['action'](module_config)
else:
raise NotImplem... | KeyError | dataset/ETHPy150Open cr0hn/enteletaor/enteletaor_lib/modules/__init__.py/IModule.run |
1,116 | def find_modules():
"""
Find modules and return a dict module instances.
:return: dict with modules instaces as format: dict(str: IModule)
:rtype: dict(str: IModule)
"""
import os
import os.path
import inspect
base_dir = os.path.abspath(os.path.dirname(__file__))
# Modules fo... | ImportError | dataset/ETHPy150Open cr0hn/enteletaor/enteletaor_lib/modules/__init__.py/find_modules |
1,117 | def get_task_from_tree_view(self, tree_view):
"""returns the task object from the given QTreeView
"""
task = None
selection_model = tree_view.selectionModel()
indexes = selection_model.selectedIndexes()
if indexes:
current_index = indexes[0]
ite... | AttributeError | dataset/ETHPy150Open eoyilmaz/anima/anima/ui/version_mover.py/VersionMover.get_task_from_tree_view |
1,118 | def copy_versions(self):
"""copies versions from one task to another
"""
# get from task
from_task = self.get_task_from_tree_view(self.from_task_tree_view)
# get logged in user
logged_in_user = self.get_logged_in_user()
if not from_task:
QtGui.QMessa... | OSError | dataset/ETHPy150Open eoyilmaz/anima/anima/ui/version_mover.py/VersionMover.copy_versions |
1,119 | def destroy_index(self, dirname):
if exists(dirname):
try:
rmtree(dirname)
except __HOLE__, e:
pass | OSError | dataset/ETHPy150Open dokipen/whoosh/tests/test_indexing.py/TestIndexing.destroy_index |
1,120 | def perform_clustering(self,kwargs):
"""
Does the actual clustering.
"""
cutoff = kwargs["cutoff"]
try:
max_clusters = kwargs["max_clusters"]
except __HOLE__:
max_clusters = sys.maxint
nodes = range(self.condensed_matrix.row_length)
... | KeyError | dataset/ETHPy150Open victor-gil-sepulveda/pyProCT/pyproct/clustering/algorithms/gromos/gromosAlgorithm.py/GromosAlgorithm.perform_clustering |
1,121 | def process(self):
(opts, args) = getopts()
chkopts(opts)
self.up_progress(10)
dev_list = comma_split(opts.dev)
if len(dev_list) < 2:
# TRANSLATORS:
# bondingするためのdeviceが少ないです
raise KssCommandOptException('ERROR: Small device for bonding. -... | ValueError | dataset/ETHPy150Open karesansui/karesansui/bin/add_bonding.py/AddBonding.process |
1,122 | def __init__(self, counts=None, calledfuncs=None, infile=None,
callers=None, outfile=None):
self.counts = counts
if self.counts is None:
self.counts = {}
self.counter = self.counts.copy() # map (filename, lineno) to count
self.calledfuncs = calledfuncs
... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/trace.py/CoverageResults.__init__ |
1,123 | def write_results(self, show_missing=True, summary=False, coverdir=None):
"""
@param coverdir
"""
if self.calledfuncs:
print
print "functions called:"
calls = self.calledfuncs.keys()
calls.sort()
for filename, modulename, funcna... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/trace.py/CoverageResults.write_results |
1,124 | def write_results_file(self, path, lines, lnotab, lines_hit):
"""Return a coverage results file in path."""
try:
outfile = open(path, "w")
except __HOLE__, err:
print >> sys.stderr, ("trace: Could not open %r for writing: %s"
"- skipping... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/trace.py/CoverageResults.write_results_file |
1,125 | def find_executable_linenos(filename):
"""Return dict where keys are line numbers in the line number table."""
try:
prog = open(filename, "rU").read()
except __HOLE__, err:
print >> sys.stderr, ("Not printing coverage data for %r: %s"
% (filename, err))
... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/trace.py/find_executable_linenos |
1,126 | def main(argv=None):
import getopt
if argv is None:
argv = sys.argv
try:
opts, prog_argv = getopt.getopt(argv[1:], "tcrRf:d:msC:lTg",
["help", "version", "trace", "count",
"report", "no-report", "summary",
... | IOError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/trace.py/main |
1,127 | def _get_deploy(self, app=None, env=None, number=None, deploy_id=None):
if deploy_id:
return Deploy.query.get(deploy_id)
try:
app = App.query.filter(App.name == app)[0]
except __HOLE__:
return None
try:
return Deploy.query.filter(
... | IndexError | dataset/ETHPy150Open getsentry/freight/freight/api/deploy_details.py/DeployMixin._get_deploy |
1,128 | def load_model_class(model_path):
"""
Load by import a class by a string path like:
'module.models.MyModel'.
This mechanism allows extension and customization of
the Entry model class.
"""
dot = model_path.rindex('.')
module_name = model_path[:dot]
class_name = model_path[dot + 1:]
... | ImportError | dataset/ETHPy150Open Fantomas42/django-blog-zinnia/zinnia/models_bases/__init__.py/load_model_class |
1,129 | def spyLCMTraffic():
lc = lcm.LCM()
lc.subscribe('.+', onLCMMessage)
try:
while True:
lc.handle()
except __HOLE__:
pass
print
print
printLCMCatalog() | KeyboardInterrupt | dataset/ETHPy150Open RobotLocomotion/director/src/python/director/lcmspy.py/spyLCMTraffic |
1,130 | def clean_slug(self):
# Ensure slug is not an integer value for Event.get_by_ident
data = self.cleaned_data['slug']
try:
int(data)
except __HOLE__:
pass
else:
raise forms.ValidationError("Slug must not be an integer-value.")
return da... | ValueError | dataset/ETHPy150Open swcarpentry/amy/workshops/forms.py/EventForm.clean_slug |
1,131 | def _parse_orcid_work(self, work):
if not work:
return {}
biblio = {}
# logger.debug(u"%20s parsing orcid work" % (self.provider_name))
try:
if work["work-citation"]["work-citation-type"].lower()=="bibtex":
biblio = self.bibtex_parser.parse(work[... | KeyError | dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/orcid.py/Orcid._parse_orcid_work |
1,132 | def _extract_members(self, page, query_string=None):
if 'orcid-profile' not in page:
raise ProviderContentMalformedError("Content does not contain expected text")
data = provider._load_json(page)
members = []
try:
orcid_works = data["orcid-profile"]["orcid-activi... | KeyError | dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/orcid.py/Orcid._extract_members |
1,133 | def member_items(self,
query_string,
provider_url_template=None,
cache_enabled=True):
logger.debug(u"%s getting member_items for %s" % (self.provider_name, query_string))
if not provider_url_template:
provider_url_template = self.member_items_url_temp... | AttributeError | dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/orcid.py/Orcid.member_items |
1,134 | def _get_server_version_info(self, connection):
dbapi_con = connection.connection
version = []
r = re.compile('[.\-]')
for n in r.split(dbapi_con.getinfo(self.dbapi.SQL_DBMS_VER)):
try:
version.append(int(n))
except __HOLE__:
versio... | ValueError | dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/sqlalchemy/connectors/pyodbc.py/PyODBCConnector._get_server_version_info |
1,135 | def _get_node(template, context=Context(), name='subject', block_lookups={}):
try:
return _iter_nodes(template, context, name, block_lookups)
except __HOLE__:
context.template = template.template
return _iter_nodes(template.template, context, name, block_lookups) | TypeError | dataset/ETHPy150Open BradWhittington/django-templated-email/templated_email/utils.py/_get_node |
1,136 | def exists(self, remote_path):
"""
Validate whether a remote file or directory exists.
:param remote_path: Path to remote file.
:type remote_path: ``str``
:rtype: ``bool``
"""
try:
self.sftp.lstat(remote_path).st_mode
except __HOLE__:
... | IOError | dataset/ETHPy150Open StackStorm/st2/st2actions/st2actions/runners/ssh/paramiko_ssh.py/ParamikoSSHClient.exists |
1,137 | def parse_bytes(header):
"""
Parse a Range header into (bytes, list_of_ranges). Note that the
ranges are *inclusive* (like in HTTP, not like in Python
typically).
Will return None if the header is invalid
"""
if not header:
raise TypeError(
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob_0_9/webob/byterange.py/Range.parse_bytes |
1,138 | def parse(cls, value):
"""
Parse the header. May return None if it cannot parse.
"""
if value is None:
return None
value = value.strip()
if not value.startswith('bytes '):
# Unparseable
return None
value = value[len('bytes '):]... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/webob_0_9/webob/byterange.py/ContentRange.parse |
1,139 | def ingest( self ):
NAME = [ "Grayscale" ]
# for each channel
for x in range(self.channel):
# label by RGB Channel
self.label ( x+1, NAME[x] )
# for each slice
for sl in range(self.startslice , self.endslice+1, self.batchsz):
imarray = np.zeros ( [self.batchsz... | IOError | dataset/ETHPy150Open neurodata/ndstore/ingest/raju/rajuchannel.py/RajuIngest.ingest |
1,140 | @override_settings(STATICFILES_STORAGE='tests.tests.test_storage.PipelineNoPathStorage')
@pipeline_settings(JS_COMPRESSOR=None, CSS_COMPRESSOR=None, COMPILERS=['tests.tests.test_storage.DummyCSSCompiler'])
def test_post_process_no_path(self):
"""
Test post_process with a storage that doesn't imp... | NotImplementedError | dataset/ETHPy150Open jazzband/django-pipeline/tests/tests/test_storage.py/StorageTest.test_post_process_no_path |
1,141 | @utils.enforce_id_param
def get_stream_urls(self, song_id):
"""Returns a list of urls that point to a streamable version of this song.
If you just need the audio and are ok with gmusicapi doing the download,
consider using :func:`get_stream_audio` instead.
This abstracts away the di... | KeyError | dataset/ETHPy150Open simon-weber/gmusicapi/gmusicapi/clients/webclient.py/Webclient.get_stream_urls |
1,142 | def __delitem__(self, header):
try:
del self._headers[header.lower()]
except __HOLE__:
pass | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/http/__init__.py/HttpResponse.__delitem__ |
1,143 | def getTranslation(language):
global g_Translations
if language not in g_Translations:
filename = os.path.join(sys.path[0], 'assets', 'locales', language, 'plexconnect.mo')
try:
fp = open(filename, 'rb')
g_Translations[language] = gettext.GNUTranslations(fp)
f... | IOError | dataset/ETHPy150Open iBaa/PlexConnect/Localize.py/getTranslation |
1,144 | @auth.s3_requires_membership(1)
def sms_modem_channel():
"""
RESTful CRUD controller for modem channels
- appears in the administration menu
Multiple Modems can be configured to receive Inbound Messages
"""
try:
import serial
except __HOLE__:
session.error = T("P... | ImportError | dataset/ETHPy150Open sahana/eden/controllers/msg.py/sms_modem_channel |
1,145 | def twitter_search():
"""
RESTful CRUD controller to add keywords
for Twitter Search
"""
tablename = "msg_twitter_search"
table = s3db[tablename]
table.is_processed.writable = False
table.is_searched.writable = False
table.is_processed.readable = False
table.is_searched.r... | AttributeError | dataset/ETHPy150Open sahana/eden/controllers/msg.py/twitter_search |
1,146 | def expiration_datetime(self):
"""Return provider session live seconds. Returns a timedelta ready to
use with session.set_expiry().
If provider returns a timestamp instead of session seconds to live, the
timedelta is inferred from current time (using UTC timezone). None is
retur... | ValueError | dataset/ETHPy150Open omab/python-social-auth/social/storage/base.py/UserMixin.expiration_datetime |
1,147 | def wsgibase(environ, responder):
"""
this is the gluon wsgi application. the first function called when a page
is requested (static or dynamic). it can be called by paste.httpserver
or by apache mod_wsgi.
- fills request with info
- the environment variables, replacing '.' with '_'
-... | TypeError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/main.py/wsgibase |
1,148 | def appfactory(wsgiapp=wsgibase,
logfilename='httpserver.log',
profiler_dir=None,
profilerfilename=None):
"""
generates a wsgi application that does logging and profiling and calls
wsgibase
.. function:: gluon.main.appfactory(
[wsgiapp=wsgibase
... | IOError | dataset/ETHPy150Open uwdata/termite-visualizations/web2py/gluon/main.py/appfactory |
1,149 | def connect_url(self, url, connect_args={}):
"""Connect to a database using an SqlAlchemy URL.
Args:
url: An SqlAlchemy-style DB connection URL.
connect_args: extra argument to be passed to the underlying
DB-API driver.
Returns:
True... | ImportError | dataset/ETHPy150Open jaysw/ipydb/ipydb/plugin.py/SqlPlugin.connect_url |
1,150 | @uri.setter
def uri(self, value):
try:
self._uri = value.encode("ascii")
except __HOLE__:
raise ValueError("uri value must be an ascii string")
except AttributeError:
raise TypeError("uri value must be a str type") | UnicodeDecodeError | dataset/ETHPy150Open javgh/greenaddress-pos-tools/nfc/ndef/uri_record.py/UriRecord.uri |
1,151 | def create(self, req, body):
"""Creates a new instance event."""
context = req.environ['nova.context']
authorize(context, action='create')
response_events = []
accepted_events = []
accepted_instances = set()
instances = {}
result = 200
body_event... | KeyError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/api/openstack/compute/legacy_v2/contrib/server_external_events.py/ServerExternalEventsController.create |
1,152 | def has_perm(self, user_obj, perm, obj=None):
"""
This method checks if the user_obj has perm on obj. Returns True or False
Looks for the rule with the code_name = perm and the content_type of the obj
If it exists returns the value of obj.field_name or obj.field_name() in case
th... | AttributeError | dataset/ETHPy150Open maraujop/django-rules/django_rules/backends.py/ObjectPermissionBackend.has_perm |
1,153 | def looks_like_ip(maybe_ip):
"""Does the given str look like an IP address?"""
if not maybe_ip[0].isdigit():
return False
try:
socket.inet_aton(maybe_ip)
return True
except (__HOLE__, UnicodeError):
if IP_RE.match(maybe_ip):
return True
except socket.erro... | AttributeError | dataset/ETHPy150Open john-kurkowski/tldextract/tldextract/remote.py/looks_like_ip |
1,154 | def _verify_third_party_invite(self, event, auth_events):
"""
Validates that the invite event is authorized by a previous third-party invite.
Checks that the public key, and keyserver, match those in the third party invite,
and that the invite event has a signature issued using that pub... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/api/auth.py/Auth._verify_third_party_invite |
1,155 | @defer.inlineCallbacks
def get_user_by_req(self, request, allow_guest=False):
""" Get a registered user's ID.
Args:
request - An HTTP request with an access_token query parameter.
Returns:
tuple of:
UserID (str)
Access token ID (str)
... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/api/auth.py/Auth.get_user_by_req |
1,156 | @defer.inlineCallbacks
def get_user_from_macaroon(self, macaroon_str):
try:
macaroon = pymacaroons.Macaroon.deserialize(macaroon_str)
self.validate_macaroon(macaroon, "access", False)
user_prefix = "user_id = "
user = None
guest = False
... | ValueError | dataset/ETHPy150Open matrix-org/synapse/synapse/api/auth.py/Auth.get_user_from_macaroon |
1,157 | @defer.inlineCallbacks
def get_appservice_by_req(self, request):
try:
token = request.args["access_token"][0]
service = yield self.store.get_app_service_by_token(token)
if not service:
logger.warn("Unrecognised appservice access token: %s" % (token,))
... | KeyError | dataset/ETHPy150Open matrix-org/synapse/synapse/api/auth.py/Auth.get_appservice_by_req |
1,158 | def error_check(code):
if code == 0:
return
else:
error_string = "code {0}: {1}".format(code, error_buffer.value.decode())
try:
raise _ERRORS[code - 1](error_string)
except __HOLE__:
raise DrmaaException(error_string)
# da vedere: NO_RUSAGE, NO_MORE_ELEME... | IndexError | dataset/ETHPy150Open pygridtools/drmaa-python/drmaa/errors.py/error_check |
1,159 | def _check_content(self, content):
try:
po = polib.pofile(content)
except __HOLE__, e:
logger.warning("Parse error: %s" % e, exc_info=True)
raise PoParseError(unicode(e))
# If file is empty, the method hangs so we should bail out.
if not content:
... | IOError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/resources/formats/pofile.py/GettextHandler._check_content |
1,160 | def _parse(self, is_source, lang_rules):
"""
Parse a PO file and create a stringset with all PO entries in the file.
"""
if lang_rules:
nplural = len(lang_rules)
else:
nplural = self.language.get_pluralrules_numbers()
if not hasattr(self, '_po'):
... | IOError | dataset/ETHPy150Open rvanlaar/easy-transifex/src/transifex/transifex/resources/formats/pofile.py/GettextHandler._parse |
1,161 | def items_for_result(cl, result, form):
"""
Generates the actual list of data.
"""
first = True
pk = cl.lookup_opts.pk.attname
for field_name in cl.list_display:
row_class = ''
try:
f, attr, value = lookup_field(field_name, result, cl.model_admin)
except (__HO... | AttributeError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.2/django/contrib/admin/templatetags/admin_list.py/items_for_result |
1,162 | def _load_urllib(self, filename, kwargs):
'''(internal) Loading a network file. First download it, save it to a
temporary file, and pass it to _load_local().'''
if PY2:
import urllib2 as urllib_request
def gettype(info):
return info.gettype()
else... | ImportError | dataset/ETHPy150Open kivy/kivy/kivy/loader.py/LoaderBase._load_urllib |
1,163 | def _update(self, *largs):
'''(internal) Check if a data is loaded, and pass to the client.'''
# want to start it ?
if self._start_wanted:
if not self._running:
self.start()
self._start_wanted = False
# in pause mode, don't unqueue anything.
... | IndexError | dataset/ETHPy150Open kivy/kivy/kivy/loader.py/LoaderBase._update |
1,164 | def validate(self):
"""Explicitly validate all the fields."""
for name, field in self:
try:
field.validate_for_object(self)
except __HOLE__ as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
... | ValidationError | dataset/ETHPy150Open beregond/jsonmodels/jsonmodels/models.py/Base.validate |
1,165 | def __repr__(self):
try:
txt = six.text_type(self)
except __HOLE__:
txt = ''
return '<{name}: {text}>'.format(
name=self.__class__.__name__,
text=txt,
) | TypeError | dataset/ETHPy150Open beregond/jsonmodels/jsonmodels/models.py/Base.__repr__ |
1,166 | def __setattr__(self, name, value):
try:
return super(Base, self).__setattr__(name, value)
except __HOLE__ as error:
raise ValidationError(
"Error for field '{name}'.".format(name=name),
error
) | ValidationError | dataset/ETHPy150Open beregond/jsonmodels/jsonmodels/models.py/Base.__setattr__ |
1,167 | def execute(self, arbiter, props):
if 'name' in props:
watcher = self._get_watcher(arbiter, props['name'])
if 'process' in props:
try:
return {
"process": props['process'],
"info": watcher.process_info(pr... | KeyError | dataset/ETHPy150Open circus-tent/circus/circus/commands/stats.py/Stats.execute |
1,168 | def emit_java_headers(target, source, env):
"""Create and return lists of Java stub header files that will
be created from a set of class files.
"""
class_suffix = env.get('JAVACLASSSUFFIX', '.class')
classdir = env.get('JAVACLASSDIR')
if not classdir:
try:
s = source[0]
... | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/javah.py/emit_java_headers |
1,169 | def JavaHOutFlagGenerator(target, source, env, for_signature):
try:
t = target[0]
except (__HOLE__, IndexError, TypeError):
t = target
try:
return '-d ' + str(t.attributes.java_lookupdir)
except AttributeError:
return '-o ' + str(t) | AttributeError | dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/javah.py/JavaHOutFlagGenerator |
1,170 | def UpdatePackageInfo(self, pkginfo):
"""Updates an existing PackageInfo entity."""
unattended_install = self.request.get('unattended_install', None)
if unattended_install is not None:
unattended_install = unattended_install == 'on'
unattended_uninstall = self.request.get('unattended_uninstall', ... | ValueError | dataset/ETHPy150Open google/simian/src/simian/mac/admin/package.py/Package.UpdatePackageInfo |
1,171 | def process_view(self, request, callback, callback_args, callback_kwargs):
if getattr(request, 'csrf_processing_done', False):
return None
try:
csrf_token = _sanitize_token(
request.COOKIES[settings.CSRF_COOKIE_NAME])
# Use same token next time
... | KeyError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/middleware/csrf.py/CsrfViewMiddleware.process_view |
1,172 | def shell(self, argstr, exitcodes=(0,)):
orig = sys.stdout
orig_stderr = sys.stderr
try:
sys.stdout = six.StringIO()
sys.stderr = six.StringIO()
_shell = shell.ClimateShell()
_shell.initialize_app(argstr.split())
except __HOLE__:
... | SystemExit | dataset/ETHPy150Open openstack/python-blazarclient/climateclient/tests/test_shell.py/ClimateShellTestCase.shell |
1,173 | def to_python(self, value):
if isinstance(value, six.string_types):
try:
return json.loads(value, **self.load_kwargs)
except __HOLE__:
raise ValidationError(_("Enter valid JSON"))
return value | ValueError | dataset/ETHPy150Open bradjasper/django-jsonfield/jsonfield/fields.py/JSONFormFieldBase.to_python |
1,174 | def clean(self, value):
if not value and not self.required:
return None
# Trap cleaning errors & bubble them up as JSON errors
try:
return super(JSONFormFieldBase, self).clean(value)
except __HOLE__:
raise ValidationError(_("Enter valid JSON")) | TypeError | dataset/ETHPy150Open bradjasper/django-jsonfield/jsonfield/fields.py/JSONFormFieldBase.clean |
1,175 | def pre_init(self, value, obj):
"""Convert a string value to JSON only if it needs to be deserialized.
SubfieldBase metaclass has been modified to call this method instead of
to_python so that we can check the obj state and determine if it needs to be
deserialized"""
try:
... | ValueError | dataset/ETHPy150Open bradjasper/django-jsonfield/jsonfield/fields.py/JSONFieldBase.pre_init |
1,176 | @pytest.mark.skipif(not version(), reason="No KAFKA_VERSION set")
@pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4'])
def test_end_to_end(kafka_broker, compression):
if compression == 'lz4':
# LZ4 requires 0.8.2
if version() < (0, 8, 2):
return
# LZ4 python ... | StopIteration | dataset/ETHPy150Open dpkp/kafka-python/test/test_producer.py/test_end_to_end |
1,177 | def load_template(self, template_name, template_dirs=None):
key = template_name
if template_dirs:
# If template directories were specified, use a hash to differentiate
key = '-'.join([template_name, hashlib.sha1('|'.join(template_dirs)).hexdigest()])
if settings.DEBUG or... | NotImplementedError | dataset/ETHPy150Open syrusakbary/pyjade/pyjade/ext/django/loader.py/Loader.load_template |
1,178 | def setUp(self):
os.chdir(os.path.split(os.path.abspath(__file__))[0])
try:
os.remove('app1.db')
os.remove('app2.db')
except OSError:
pass
try:
shutil.rmtree('migrations')
except __HOLE__:
pass | OSError | dataset/ETHPy150Open miguelgrinberg/Flask-Migrate/tests/test_multidb_migrate.py/TestMigrate.setUp |
1,179 | def tearDown(self):
try:
os.remove('app1.db')
os.remove('app2.db')
except __HOLE__:
pass
try:
shutil.rmtree('migrations')
except OSError:
pass | OSError | dataset/ETHPy150Open miguelgrinberg/Flask-Migrate/tests/test_multidb_migrate.py/TestMigrate.tearDown |
1,180 | def get_message(self, command=None):
try:
if command is not None and self._Messages[command]:
_msg = __import__(
self._Messages[command],
globals(),
locals(),
[command]
)
... | KeyError | dataset/ETHPy150Open mogui/pyorient/pyorient/orient.py/OrientDB.get_message |
1,181 | def _action_has_highlight(actions):
for action in actions:
try:
if action.get("set_tweak", None) == "highlight":
return action.get("value", True)
except __HOLE__:
pass
return False | AttributeError | dataset/ETHPy150Open matrix-org/synapse/synapse/handlers/sync.py/_action_has_highlight |
1,182 | def add_one_time_default(self, field, field_def):
# OK, they want to pick their own one-time default. Who are we to refuse?
print(" ? Please enter Python code for your one-off default value.")
print(" ? The datetime module is available, so you can do e.g. datetime.date.today()")
while Tr... | NameError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/South-1.0.2/south/creator/actions.py/_NullIssuesField.add_one_time_default |
1,183 | def ReadData(self, source):
"""Parses source option and reads appropriate data source.
Args:
source: Source of Appstats data. Either filename if being read from
a file or MEMCACHE if being read from memcache.
Returns:
errormessage: An error message to display to the user if an error occ... | IOError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/ext/analytics/main.py/StatsPage.ReadData |
1,184 | @staticmethod
def _safeID(*args, **kwargs):
instanceID = (args, tuple( sorted( kwargs.items() ) ))
try:
hash(instanceID)
return instanceID
except __HOLE__:
return hash(_pickle.dumps(instanceID)) | TypeError | dataset/ETHPy150Open OrbitzWorldwide/droned/romeo/lib/romeo/entity.py/ParameterizedSingleton._safeID |
1,185 | @staticmethod
def deserialize(buffer, decode='pickle'):
"""This method is used only by the Journal service to reconstruct
serialized objects by calling the custom ``construct(state)``
method of their class.
@param buffer (a ``.read()``-supporting file-like object)
... | TypeError | dataset/ETHPy150Open OrbitzWorldwide/droned/romeo/lib/romeo/entity.py/Entity.deserialize |
1,186 | @classmethod
def for_domain(cls, dom):
'''Get job info for the domain
Query the libvirt job info for the domain (ie progress
of migration, or snapshot operation)
Returns: a DomainJobInfo instance
'''
if cls._have_job_stats:
try:
stats = ... | AttributeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/DomainJobInfo.for_domain |
1,187 | def _dispatch_events(self):
"""Wait for & dispatch events from native thread
Blocks until native thread indicates some events
are ready. Then dispatches all queued events.
"""
# Wait to be notified that there are some
# events pending
try:
_c = self.... | ValueError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/Host._dispatch_events |
1,188 | def _init_events_pipe(self):
"""Create a self-pipe for the native thread to synchronize on.
This code is taken from the eventlet tpool module, under terms
of the Apache License v2.0.
"""
self._event_queue = native_Queue.Queue()
try:
rpipe, wpipe = os.pipe()
... | NotImplementedError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/Host._init_events_pipe |
1,189 | def _get_new_connection(self):
# call with _wrapped_conn_lock held
LOG.debug('Connecting to libvirt: %s', self._uri)
wrapped_conn = None
try:
wrapped_conn = self._connect(self._uri, self._read_only)
finally:
# Enabling the compute service, in case it was ... | TypeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/Host._get_new_connection |
1,190 | def list_instance_domains(self, only_running=True, only_guests=True):
"""Get a list of libvirt.Domain objects for nova instances
:param only_running: True to only return running instances
:param only_guests: True to filter out any host domain (eg Dom-0)
Query libvirt to a get a list of... | AttributeError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/Host.list_instance_domains |
1,191 | def is_cpu_control_policy_capable(self):
"""Returns whether kernel configuration CGROUP_SCHED is enabled
CONFIG_CGROUP_SCHED may be disabled in some kernel configs to
improve scheduler latency.
"""
try:
with open("/proc/self/mounts", "r") as fd:
for l... | IOError | dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/virt/libvirt/host.py/Host.is_cpu_control_policy_capable |
1,192 | def safe_initialisation(custom_command="", comm=None, nprocs=1):
"""
Wrapper around the init function to handle errors
KeyWord Arguments
-----------------
custom_command : str
testing purposes
comm : MPI.Intracomm
object that helps communicating between the processes
nprocs ... | KeyError | dataset/ETHPy150Open baudren/montepython_public/montepython/run.py/safe_initialisation |
1,193 | def __init__(self, *args, **kwargs):
super(CustomPayloadParser, self).__init__(*args, **kwargs)
# Remove some built-in tags that we don't want to expose.
# There are no built-in filters we have to worry about.
for tag_name in self.BLACKLISTED_TAGS:
try:
del s... | KeyError | dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/notifications/webhooks.py/CustomPayloadParser.__init__ |
1,194 | def _info_slots(t):
try:
for line in t.talk_raw(CMD_CLUSTER_NODES).split('\n'):
if len(line) == 0 or 'fail' in line or 'myself' not in line:
continue
node = ClusterNode(*line.split(' '))
return {
'node_id': node.node_id,
'sl... | ValueError | dataset/ETHPy150Open HunanTV/redis-ctl/daemonutils/stats_models.py/_info_slots |
1,195 | def with_ascendants_for_slug(self, slug, **kwargs):
"""
Given a slug, returns a list of pages from ascendants to
descendants, that form the parent/child page relationships
for that slug. The main concern is to do this in a single
database query rather than querying the database f... | IndexError | dataset/ETHPy150Open stephenmcd/mezzanine/mezzanine/pages/managers.py/PageManager.with_ascendants_for_slug |
1,196 | def test_basic_json(self):
"""Test the basic JSON project creation with only the required fields"""
# dataset format = (dataset_name, [ximagesz, yimagesz, zimagesz], [[xvoxel, yvoxel, zvoxel], [xoffset, yoffset, zoffset], timerange, scalinglevels, scaling)
dataset = (p.dataset, [2000,2000,30], [1.0,1.0... | AssertionError | dataset/ETHPy150Open neurodata/ndstore/test/test_json.py/Test_Project_Json.test_basic_json |
1,197 | def jump(dir):
w = vim.current.window
check_history(w)
history = list(w.vars[VHIST])
bufnr = vim.current.buffer.number
now = time()
lastbuf = w.vars.get(VLAST, None)
if not lastbuf or (bufnr == lastbuf[0] and
now - lastbuf[1] > vim.vars['vial_bufhist_timeout']):
... | ValueError | dataset/ETHPy150Open baverman/vial/vial/plugins/bufhist/plugin.py/jump |
1,198 | def reopen(self, path='', prefix='', midfix=''):
"""
Close and then open log files on path if given otherwise self.path
Use ha in log file name if given
"""
self.close()
if path:
self.path = path
if prefix:
self.prefix = prefix
i... | IOError | dataset/ETHPy150Open ioflo/ioflo/ioflo/aio/wiring.py/WireLog.reopen |
1,199 | def reduce_nums(val_1, val_2, val_op):
"""apply arithmetic rules and try to return an integer result"""
#print val_1, val_2, val_op
# now perform the operation, make certain a and b are numeric
try: a = 0 + val_1
except TypeError: a = int(val_1)
try: b = 0 + val_2
except __HOLE__: b = int(val_2)
d = val... | TypeError | dataset/ETHPy150Open appcelerator-archive/poc-nodejs-desktop/Resources/nodejs/builds/linux/node/lib/node/wafadmin/Tools/preproc.py/reduce_nums |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.