Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
5,000 | def _process_road_rxmsg(self, msg, sender):
'''
Send to the right queue
msg is the message body dict
sender is the unique name of the remote estate that sent the message
'''
try:
s_estate, s_yard, s_share = msg['route']['src']
d_estate, d_yard, d_s... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/daemons/flo/core.py/SaltRaetRouterMinion._process_road_rxmsg |
5,001 | def _process_lane_rxmsg(self, msg, sender):
'''
Send uxd messages tot he right queue or forward them to the correct
yard etc.
msg is message body dict
sender is unique name of remote that sent the message
'''
try:
s_estate, s_yard, s_share = msg['rou... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/daemons/flo/core.py/SaltRaetRouterMinion._process_lane_rxmsg |
5,002 | def _send_presence(self, msg):
'''
Forward an presence message to all subscribed yards
Presence message has a route
'''
y_name = msg['route']['src'][1]
if y_name not in self.lane_stack.value.nameRemotes: # subscriber not a remote
pass # drop msg don't answer... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/daemons/flo/core.py/SaltRaetPresenter._send_presence |
5,003 | def _remove_ssh_client(p):
try:
_ssh_clients.remove(p)
except __HOLE__:
pass | ValueError | dataset/ETHPy150Open esrlabs/git-repo/git_command.py/_remove_ssh_client |
5,004 | def terminate_ssh_clients():
global _ssh_clients
for p in _ssh_clients:
try:
os.kill(p.pid, SIGTERM)
p.wait()
except __HOLE__:
pass
_ssh_clients = [] | OSError | dataset/ETHPy150Open esrlabs/git-repo/git_command.py/terminate_ssh_clients |
5,005 | def sort_feed_items(items, order):
"""Return feed items, sorted according to sortFeedItems."""
if order == 'asInFeed':
return items
(key, reverse) = _sort_arguments(order)
try:
sitems = sorted(items, key=key, reverse=reverse)
except __HOLE__:
# feedparser normalizes required ... | KeyError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/RSS/plugin.py/sort_feed_items |
5,006 | def getCommandMethod(self, command):
try:
return self.__parent.getCommandMethod(command)
except __HOLE__:
return self.get_feed(command[0]).get_command(self) | AttributeError | dataset/ETHPy150Open ProgVal/Limnoria/plugins/RSS/plugin.py/RSS.getCommandMethod |
5,007 | def app_loop(args, log):
pulsar_app = _app(args, log)
sleep = True
while sleep:
try:
time.sleep(5)
except __HOLE__:
sleep = False
except SystemExit:
sleep = False
except Exception:
pass
try:
pulsar_app.shutdown()
... | KeyboardInterrupt | dataset/ETHPy150Open galaxyproject/pulsar/pulsar/main.py/app_loop |
5,008 | def __init__(self):
self.config_home = os.path.join(click.get_app_dir('OpenConnect Helper'))
self.config_file = os.path.join(self.config_home, 'profiles.toml')
fn = self.config_file
try:
with open(fn) as f:
self.config = toml.load(f)
except __HOLE__ a... | IOError | dataset/ETHPy150Open mitsuhiko/osx-openconnect-helper/openconnect_helper.py/ProfileManager.__init__ |
5,009 | def save(self):
fn = self.config_file
try:
os.makedirs(self.config_home)
except __HOLE__:
pass
with open(fn, 'w') as f:
return toml.dump(self.config, f) | OSError | dataset/ETHPy150Open mitsuhiko/osx-openconnect-helper/openconnect_helper.py/ProfileManager.save |
5,010 | def connect(self, name, cert_check=True):
profile = self.get_profile(name)
if profile is None:
raise click.UsageError('The profile "%s" does not exist.' % name)
kwargs = {}
stdin = None
password = self.get_keychain_password(name)
rsa_token = self.get_rsa_toke... | KeyboardInterrupt | dataset/ETHPy150Open mitsuhiko/osx-openconnect-helper/openconnect_helper.py/ProfileManager.connect |
5,011 | def validate_fingerprint(ctx, param, value):
if value is not None:
fingerprint = value.replace(':', '').strip().upper()
try:
if len(fingerprint.decode('hex')) != 20:
raise ValueError()
except (TypeError, __HOLE__):
raise click.BadParameter('Invalid SHA... | ValueError | dataset/ETHPy150Open mitsuhiko/osx-openconnect-helper/openconnect_helper.py/validate_fingerprint |
5,012 | def _incrdecr_async(self, key, is_negative, delta, namespace=None,
initial_value=None, rpc=None):
"""Async version of _incrdecr().
Returns:
A UserRPC instance whose get_result() method returns the same
kind of value as _incrdecr() returns.
"""
if not isinstance(delta, (int, ... | TypeError | dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/memcache/__init__.py/Client._incrdecr_async |
5,013 | def dates(self, xpath):
result = []
for value in self.strings(xpath):
if 'T' in value:
if value.endswith('Z'):
value = value[:-1] + ' UTC'
fmt = '%Y-%m-%dT%H:%M:%S %Z'
else:
fmt = '%Y-%m-%dT%H:%M:%S'
... | ValueError | dataset/ETHPy150Open infrae/moai/moai/utils.py/XPath.dates |
5,014 | def Collect(self):
"""Collects the stats."""
user, system = self.proc.cpu_times()
percent = self.proc.cpu_percent()
self.cpu_samples.append((rdfvalue.RDFDatetime().Now(),
user, system, percent))
# Keep stats for one hour.
self.cpu_samples = self.cpu_samples[-3600 / ... | NotImplementedError | dataset/ETHPy150Open google/grr/grr/client/client_stats.py/ClientStatsCollector.Collect |
5,015 | def PrintIOSample(self):
try:
return str(self.proc.io_counters())
except (NotImplementedError, __HOLE__):
return "Not available on this platform." | AttributeError | dataset/ETHPy150Open google/grr/grr/client/client_stats.py/ClientStatsCollector.PrintIOSample |
5,016 | def get_field_info(self, field):
"""
Given an instance of a serializer field, return a dictionary
of metadata about it.
"""
field_info = OrderedDict()
serializer = field.parent
if isinstance(field, serializers.ManyRelatedField):
field_info['type'] = s... | KeyError | dataset/ETHPy150Open django-json-api/django-rest-framework-json-api/rest_framework_json_api/metadata.py/JSONAPIMetadata.get_field_info |
5,017 | def bind_key_hold(self, method, key, modifiers=0):
"""Bind a method to a key at runtime to be invoked when the key is
held down, this replaces any existing key hold binding for this key.
To unbind the key entirely, pass ``None`` for method.
"""
if method is not None:
self._key_hold_map[key, modifiers & sel... | KeyError | dataset/ETHPy150Open caseman/grease/grease/controls.py/KeyControls.bind_key_hold |
5,018 | def bind_key_press(self, method, key, modifiers=0):
"""Bind a method to a key at runtime to be invoked when the key is initially
pressed, this replaces any existing key hold binding for this key. To unbind
the key entirely, pass ``None`` for method.
"""
if method is not None:
self._key_press_map[key, modif... | KeyError | dataset/ETHPy150Open caseman/grease/grease/controls.py/KeyControls.bind_key_press |
5,019 | def bind_key_release(self, method, key, modifiers=0):
"""Bind a method to a key at runtime to be invoked when the key is releaseed,
this replaces any existing key hold binding for this key. To unbind
the key entirely, pass ``None`` for method.
"""
if method is not None:
self._key_release_map[key, modifiers... | KeyError | dataset/ETHPy150Open caseman/grease/grease/controls.py/KeyControls.bind_key_release |
5,020 | @base.post_async('/cmd/exec')
def node_exec_command(request):
t = Talker(request.form['host'], int(request.form['port']))
try:
r = t.talk(*json.loads(request.form['cmd']))
except __HOLE__ as e:
r = None if e.message == 'No reply' else ('-ERROR: ' + e.message)
except ReplyError as e:
... | ValueError | dataset/ETHPy150Open HunanTV/redis-ctl/handlers/commands.py/node_exec_command |
5,021 | def symbol(ident, bp=0):
'''
Gets (and create if not exists) as named symbol.
Optionally, you can specify a binding power (bp) value, which will be used
to control operator presedence; the higher the value, the tighter a token
binds to the tokens that follow.
'''
try:
s = SYMBOLS[id... | KeyError | dataset/ETHPy150Open tehmaze/nagios-cli/nagios_cli/filters/parser.py/symbol |
5,022 | @classmethod
def reader(cls, program, **scope):
scope.update({
'None': None, 'null': None,
'True': True, 'true': True,
'False': False, 'false': False,
'empty': '',
})
for kind, value in tokenize(program):
#print (kind, value),
... | IndexError | dataset/ETHPy150Open tehmaze/nagios-cli/nagios_cli/filters/parser.py/Parser.reader |
5,023 | def has_win32com():
"""
Run this to determine if the local machine has win32com, and if it
does, include additional tests.
"""
if not sys.platform.startswith('win32'):
return False
try:
mod = __import__('win32com')
except __HOLE__:
return False
return True | ImportError | dataset/ETHPy150Open balanced/status.balancedpayments.com/venv/lib/python2.7/site-packages/distribute-0.6.34-py2.7.egg/setuptools/tests/test_sandbox.py/has_win32com |
5,024 | def create_commit_message(repo):
message = messages.CommitMessage()
try:
commit = repo.head.commit
except ValueError:
raise NoGitHeadError('On initial commit, no HEAD yet.')
try:
repo.git.diff('--quiet')
has_unstaged_changes = False
except git.exc.GitCommandError:
... | TypeError | dataset/ETHPy150Open grow/grow/grow/deployments/utils.py/create_commit_message |
5,025 | def default(self, obj):
"""Convert Home Assistant objects.
Hand other objects to the original method.
"""
if isinstance(obj, datetime):
return obj.isoformat()
elif hasattr(obj, 'as_dict'):
return obj.as_dict()
try:
return json.JSONEnc... | TypeError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/remote.py/JSONEncoder.default |
5,026 | def get_event_listeners(api):
"""List of events that is being listened for."""
try:
req = api(METHOD_GET, URL_API_EVENTS)
return req.json() if req.status_code == 200 else {}
except (HomeAssistantError, __HOLE__):
# ValueError if req.json() can't parse the json
_LOGGER.excep... | ValueError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/remote.py/get_event_listeners |
5,027 | def get_state(api, entity_id):
"""Query given API for state of entity_id."""
try:
req = api(METHOD_GET, URL_API_STATES_ENTITY.format(entity_id))
# req.status_code == 422 if entity does not exist
return ha.State.from_dict(req.json()) \
if req.status_code == 200 else None
... | ValueError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/remote.py/get_state |
5,028 | def get_states(api):
"""Query given API for all states."""
try:
req = api(METHOD_GET,
URL_API_STATES)
return [ha.State.from_dict(item) for
item in req.json()]
except (HomeAssistantError, __HOLE__, AttributeError):
# ValueError if req.json() can't p... | ValueError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/remote.py/get_states |
5,029 | def get_services(api):
"""Return a list of dicts.
Each dict has a string "domain" and a list of strings "services".
"""
try:
req = api(METHOD_GET, URL_API_SERVICES)
return req.json() if req.status_code == 200 else {}
except (HomeAssistantError, __HOLE__):
# ValueError if r... | ValueError | dataset/ETHPy150Open home-assistant/home-assistant/homeassistant/remote.py/get_services |
5,030 | def handle(self, *app_labels, **options):
format = options['format']
indent = options['indent']
using = options['database']
excludes = options['exclude']
output = options['output']
show_traceback = options['traceback']
use_natural_foreign_keys = options['use_natur... | ValueError | dataset/ETHPy150Open django/django/django/core/management/commands/dumpdata.py/Command.handle |
5,031 | def test_find_and_modify_with_sort(self):
c = self.db.test
c.drop()
for j in range(5):
c.insert({'j': j, 'i': 0})
sort = {'j': DESCENDING}
self.assertEqual(4, c.find_and_modify({},
{'$inc': {'i': 1}},
... | ImportError | dataset/ETHPy150Open mongodb/mongo-python-driver/test/test_legacy_api.py/TestLegacy.test_find_and_modify_with_sort |
5,032 | def __new__(cls):
try:
return cls._instance
except __HOLE__:
cls._instance = tzinfo.__new__(UTCTimeZone)
return cls._instance | AttributeError | dataset/ETHPy150Open rsms/smisk/lib/smisk/util/DateTime.py/UTCTimeZone.__new__ |
5,033 | def Delete(self, queue, tasks, mutation_pool=None):
"""Removes the tasks from the queue.
Note that tasks can already have been removed. It is not an error
to re-delete an already deleted task.
Args:
queue: A queue to clear.
tasks: A list of tasks to remove. Tasks may be Task() instances
... | AttributeError | dataset/ETHPy150Open google/grr/grr/lib/queue_manager.py/QueueManager.Delete |
5,034 | def build_Add(self, o):
real, imag = map(self.build_Const, o.getChildren())
try:
real = float(real)
except __HOLE__:
raise UnknownType('Add')
if not isinstance(imag, complex) or imag.real != 0.0:
raise UnknownType('Add')
return real+imag | TypeError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Builder.build_Add |
5,035 | def _interpolate(self, key, value):
try:
# do we already have an interpolation engine?
engine = self._interpolation_engine
except __HOLE__:
# not yet: first time running _interpolate(), so pick the engine
name = self.main.interpolation
if name ... | AttributeError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Section._interpolate |
5,036 | def get(self, key, default=None):
"""A version of ``get`` that doesn't bypass string interpolation."""
try:
return self[key]
except __HOLE__:
return default | KeyError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Section.get |
5,037 | def pop(self, key, default=MISSING):
"""
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
If key is not found, d is returned if given, otherwise KeyError is raised'
"""
try:
val = self[key]
except __HOLE__:
if default is... | KeyError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Section.pop |
5,038 | def setdefault(self, key, default=None):
"""A version of setdefault that sets sequence if appropriate."""
try:
return self[key]
except __HOLE__:
self[key] = default
return self[key] | KeyError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Section.setdefault |
5,039 | def as_bool(self, key):
"""
Accepts a key as input. The corresponding value must be a string or
the objects (``True`` or 1) or (``False`` or 0). We allow 0 and 1 to
retain compatibility with Python 2.2.
If the string is one of ``True``, ``On``, ``Yes``, or ``1`` it retu... | KeyError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/Section.as_bool |
5,040 | def _handle_configspec(self, configspec):
"""Parse the configspec."""
# FIXME: Should we check that the configspec was created with the
# correct settings ? (i.e. ``list_values=False``)
if not isinstance(configspec, ConfigObj):
try:
configspec = Config... | IOError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/ConfigObj._handle_configspec |
5,041 | def validate(self, validator, preserve_errors=False, copy=False,
section=None):
"""
Test the ConfigObj against a configspec.
It uses the ``validator`` object from *validate.py*.
To run ``validate`` on the current ConfigObj, call: ::
... | AttributeError | dataset/ETHPy150Open boakley/robotframework-workbench/rwb/lib/configobj.py/ConfigObj.validate |
5,042 | def interact(self, ps1="shparse> ", ps2="more> "):
try:
while 1:
line = raw_input(ps1)
if not line:
continue
line += "\n" # add newline to force callback
while self.feed(line):
line = raw_input(ps... | KeyboardInterrupt | dataset/ETHPy150Open kdart/pycopia/core/pycopia/shparser.py/ShellParser.interact |
5,043 | def is_numeric(val):
try:
float(val)
return True
except __HOLE__:
return False | ValueError | dataset/ETHPy150Open adambullmer/sublime_docblockr_python/parsers/parser.py/is_numeric |
5,044 | def tearDown(self):
# We have to remove all the files from the real FS. Doing the same for the
# fake FS is optional, but doing it is an extra sanity check.
os.chdir(tempfile.gettempdir())
try:
rev_files = self._created_files[:]
rev_files.reverse()
for... | OSError | dataset/ETHPy150Open jmcgeheeiv/pyfakefs/fake_filesystem_vs_real_test.py/FakeFilesystemVsRealTest.tearDown |
5,045 | def _GetErrno(self, raised_error):
try:
return (raised_error and raised_error.errno) or None
except __HOLE__:
return None | AttributeError | dataset/ETHPy150Open jmcgeheeiv/pyfakefs/fake_filesystem_vs_real_test.py/FakeFilesystemVsRealTest._GetErrno |
5,046 | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
'''We train over mini-batches and evaluate periodically.'''
iteration = 0
while True:
if not iteration % self.config.test_frequency and test_set:
try:
self.test(iteration, ... | KeyboardInterrupt | dataset/ETHPy150Open zomux/deepy/deepy/trainers/customize_trainer.py/CustomizeTrainer.train |
5,047 | def scan_modules(self):
"""Loads the python modules specified in the JIP configuration.
This will register any functions and classes decorated with
one of the JIP decorators.
"""
if self.__scanned:
return
path = getenv("JIP_MODULES", "")
log.debug("Sca... | ImportError | dataset/ETHPy150Open thasso/pyjip/jip/tools.py/Scanner.scan_modules |
5,048 | def run(self, tool, stdin=None, stdout=None):
"""Execute this block
"""
import subprocess
import jip
# write template to named temp file and run with interpreter
script_file = jip.create_temp_file()
try:
script_file.write(self.render(tool))
... | OSError | dataset/ETHPy150Open thasso/pyjip/jip/tools.py/Block.run |
5,049 | def check_file(self, option_name):
"""Delegates to the options check name function
:param option_name: the name of the option
"""
try:
self.options[option_name].check_file()
except __HOLE__ as e:
self.validation_error(str(e)) | ValueError | dataset/ETHPy150Open thasso/pyjip/jip/tools.py/Tool.check_file |
5,050 | def main(args=None, get_subs_fn=None):
get_subs_fn = get_subs_fn or get_subs
_place_template_files = True
_process_template_files = True
package_path = os.getcwd()
if args is not None:
package_path = args.package_path or os.getcwd()
_place_template_files = args.place_template_files
... | KeyboardInterrupt | dataset/ETHPy150Open ros-infrastructure/bloom/bloom/generators/rpm/generate_cmd.py/main |
5,051 | def __getdict(self, key):
ret = self.get(key)
try:
ret = json.loads(ret)
except __HOLE__: # The value was not JSON encoded :-)
raise Exception('"%s" was not JSON encoded as expected (%s).' % (key, str(ret)))
return ret | ValueError | dataset/ETHPy150Open klipstein/dojango/dojango/decorators.py/__getdict |
5,052 | def __prepare_json_ret(request, ret, callback_param_name=None, use_iframe=False):
if ret==False:
ret = {'success':False}
elif ret==None: # Sometimes there is no return.
ret = {}
# Add the 'ret'=True, since it was obviously no set yet and we got valid data, no exception.
func_name = None
... | AttributeError | dataset/ETHPy150Open klipstein/dojango/dojango/decorators.py/__prepare_json_ret |
5,053 | def _on_model_change(self, form, model, is_created):
"""
Compatibility helper.
"""
try:
self.on_model_change(form, model, is_created)
except __HOLE__:
msg = ('%s.on_model_change() now accepts third ' +
'parameter is_created. Please u... | TypeError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/model/base.py/BaseModelView._on_model_change |
5,054 | def _export_tablib(self, export_type, return_url):
"""
Exports a variety of formats using the tablib library.
"""
if tablib is None:
flash(gettext('Tablib dependency not installed.'))
return redirect(return_url)
filename = self.get_export_name(export_... | AttributeError | dataset/ETHPy150Open flask-admin/flask-admin/flask_admin/model/base.py/BaseModelView._export_tablib |
5,055 | def test_defer_connect(self):
import socket
for db in self.databases:
d = db.copy()
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(d['unix_socket'])
except __HOLE__:
sock = socket.create_conne... | KeyError | dataset/ETHPy150Open PyMySQL/PyMySQL/pymysql/tests/test_connection.py/TestConnection.test_defer_connect |
5,056 | @task(rate_limit='600/m', ignore_result=True)
def redo_ranks(run_id):
from brabeion import badges
logger = redo_ranks.get_logger()
try:
user_run = Run.objects.get(pk=run_id)
except Run.DoesNotExist:
logger.error("[R- /U- /M- ] Run not found (pk={0}).".format(run_id))
return False
map_obj = user_run.map
if... | IndexError | dataset/ETHPy150Open chaosk/teerace/teerace/race/tasks.py/redo_ranks |
5,057 | def __getattr__(self, attr):
try:
return self.INDEXES.get(attr)
except __HOLE__:
raise AttributeError(attr) | TypeError | dataset/ETHPy150Open chaosk/teerace/teerace/race/tasks.py/index_factory.__getattr__ |
5,058 | @task(ignore_result=True)
def retrieve_map_details(map_id):
"""
WARNING!
This task is CPU/(and highly) RAM expensive.
Checks for presence of specified tiles, counts some of them
and at the end takes a beautiful photo of the map.
Thanks for your help, erdbeere!
"""
logger = retrieve_map_details.get_logger()
... | IndexError | dataset/ETHPy150Open chaosk/teerace/teerace/race/tasks.py/retrieve_map_details |
5,059 | @pytest.fixture(scope='module')
def ctx(sqlctx, people):
try:
df = sqlctx.createDataFrame(people)
except __HOLE__:
schema = sqlctx.inferSchema(people)
schema.registerTempTable('t')
schema.registerTempTable('t2')
else:
df2 = sqlctx.createDataFrame(people)
sqlct... | AttributeError | dataset/ETHPy150Open blaze/odo/odo/backends/tests/test_sparksql.py/ctx |
5,060 | def wait_until_start():
while True:
try:
results = urlopen(EXAMPLE_APP)
if results.code == 404:
raise Exception('%s returned unexpected 404' % EXAMPLE_APP)
break
except __HOLE__:
pass | IOError | dataset/ETHPy150Open cobrateam/splinter/run_tests.py/wait_until_start |
5,061 | def wait_until_stop():
while True:
try:
results = urlopen(EXAMPLE_APP)
if results.code == 404:
break
except __HOLE__:
break | IOError | dataset/ETHPy150Open cobrateam/splinter/run_tests.py/wait_until_stop |
5,062 | def lmode(inlist):
"""
Returns a list of the modal (most common) score(s) in the passed
list. If there is more than one such score, all are returned. The
bin-count for the mode(s) is also returned.
Usage: lmode(inlist)
Returns: bin-count for mode(s), a list of modal value(s)
"""
scores = pstats.... | ValueError | dataset/ETHPy150Open radlab/sparrow/src/main/python/third_party/stats.py/lmode |
5,063 | def get_contents(self, origin):
"""
Returns the contents of template at origin.
"""
try:
with io.open(origin.name, encoding=self.engine.file_charset) as fp:
return fp.read()
except __HOLE__ as e:
if e.errno == errno.ENOENT:
... | IOError | dataset/ETHPy150Open tethysplatform/tethys/tethys_apps/template_loaders.py/TethysAppsTemplateLoader.get_contents |
5,064 | def hits_numpy(G,normalized=True):
"""Return HITS hubs and authorities values for nodes.
The HITS algorithm computes two numbers for a node.
Authorities estimates the node value based on the incoming links.
Hubs estimates the node value based on outgoing links.
Parameters
----------
G : gr... | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_analysis/hits_alg.py/hits_numpy |
5,065 | def hits_scipy(G,max_iter=100,tol=1.0e-6,normalized=True):
"""Return HITS hubs and authorities values for nodes.
The HITS algorithm computes two numbers for a node.
Authorities estimates the node value based on the incoming links.
Hubs estimates the node value based on outgoing links.
Parameters
... | ImportError | dataset/ETHPy150Open networkx/networkx/networkx/algorithms/link_analysis/hits_alg.py/hits_scipy |
5,066 | def _generate_path(self, path, attr, wildcard_key, raiseerr=True):
if raiseerr and not path.has_entity:
if isinstance(path, TokenRegistry):
raise sa_exc.ArgumentError(
"Wildcard token cannot be followed by another entity")
else:
raise s... | AttributeError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/sqlalchemy/orm/strategy_options.py/Load._generate_path |
5,067 | def get_context_data(self, **kwargs):
context = super(SettingsTextView, self).get_context_data(**kwargs)
try:
context['nodes'] = serializers.serialize('python', NodeSettings.objects.all())
context['settings'] = serializers.serialize('python', OpenstackSettings.objects.all())
... | IndexError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/config/views.py/SettingsTextView.get_context_data |
5,068 | def get_context_data(self, **kwargs):
context = super(SettingsView, self).get_context_data(**kwargs)
context['cluster_form'] = ClusterSettingsForm()
context['ucsm_form'] = UCSMSettingsForm()
context['os_form'] = OSSettingsForm()
context['network_form'] = NetworkSettingsForm
... | IndexError | dataset/ETHPy150Open Havate/havate-openstack/proto-build/gui/horizon/Horizon_GUI/config/views.py/SettingsView.get_context_data |
5,069 | def visit_output(self, node):
mode, rest = self.get_arg_rest(node)
modes = [x.strip() for x in mode.split(',')]
for mode in modes:
try:
handler_name = self.mod.output_handlers[mode.lower()]
except __HOLE__:
self.error('Unknown output mode: %r. Expected one of %r.'%(
mode, self.mod.output_handlers... | KeyError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Document.py/Document.visit_output |
5,070 | def gen_descriptions(self, ats, use_attr_header = 1):
if not ats:
return
tab = self.sortup_aspects(ats)
for typ, li in tab:
try:
try:
gen_desc = getattr(self, 'gen_%s_descriptions'%typ)
except __HOLE__:
hd = typ
if (len(li) > 1):
hd = hd + 's'
hd = hd.capitalize().replace('_... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Document.py/SubDoc.gen_descriptions |
5,071 | def gen_synopsis(self, m):
ats = m.find_aspects('*')
ats = self.combine_attrs_of_same_kind(ats)
tab = self.sortup_aspects(ats, synopsis=1)
if tab:
self.gen_outer_dt('Synopsis')
self.open('dd')
self.open('dl')
self.level += 1
for typ, li in tab:
try:
gen_syn = getattr(self, 'gen_%s_s... | AttributeError | dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/gsl/Document.py/SubDoc.gen_synopsis |
5,072 | def x86flags(archTag, baseArch, extraFlags, ofInterest):
try:
lines = open("/proc/cpuinfo").read().split("\n")
except __HOLE__:
lines=[]
rc = [ (x, deps.FLAG_SENSE_PREFERRED) for x in extraFlags ]
for line in lines:
if not line.startswith("flags"): continue
fields = lin... | IOError | dataset/ETHPy150Open sassoftware/conary/conary/deps/arch.py/x86flags |
5,073 | def _url_for_fetch(self, mapping):
try:
return mapping['pre_processed_url']
except __HOLE__:
return mapping['raw_url'] | KeyError | dataset/ETHPy150Open openelections/openelections-core/openelex/us/ia/datasource.py/Datasource._url_for_fetch |
5,074 | def _checkRewrite(self):
try:
if os.stat(self.name)[6] < self.where:
self.reset()
except __HOLE__:
self.close() | OSError | dataset/ETHPy150Open openstack/bareon/contrib/fuel_bootstrap/files/trusty/usr/bin/send2syslog.py/WatchedFile._checkRewrite |
5,075 | def readLines(self):
"""Return list of last append lines from file if exist."""
self._checkRewrite()
if not self.fo:
try:
self.fo = open(self.name, 'r')
except __HOLE__:
return ()
lines = self.fo.readlines()
self.where = se... | IOError | dataset/ETHPy150Open openstack/bareon/contrib/fuel_bootstrap/files/trusty/usr/bin/send2syslog.py/WatchedFile.readLines |
5,076 | def send(self):
"""Send append data from files to servers."""
for watchedfile in self.watchedfiles:
for line in watchedfile.readLines():
line = line.strip()
level = self._get_msg_level(line, self.log_type)
# Get rid of duplicated information i... | KeyError | dataset/ETHPy150Open openstack/bareon/contrib/fuel_bootstrap/files/trusty/usr/bin/send2syslog.py/WatchedGroup.send |
5,077 | @classmethod
def getConfig(cls):
"""Generate config from command line arguments and config file."""
# example_config = {
# "daemon": True,
# "run_once": False,
# "debug": False,
# "watchlist": [
# {"servers": [ {"host": "loca... | ValueError | dataset/ETHPy150Open openstack/bareon/contrib/fuel_bootstrap/files/trusty/usr/bin/send2syslog.py/Config.getConfig |
5,078 | def load_user_config():
"""
Returns the gitver's configuration: tries to read the stored configuration
file and merges it with the default one, ensuring a valid configuration is
always returned.
"""
try:
with open(CFGFILE, 'r') as f:
data = ''
for line in f:
... | KeyError | dataset/ETHPy150Open manuelbua/gitver/gitver/config.py/load_user_config |
5,079 | def __init__(self, parent=None):
QtWidgets.QTableWidget.__init__(self, parent)
self.setColumnCount(6)
self.setHorizontalHeaderLabels(
["Type", "File name", "Line", "Description", 'Details'])
try:
# pyqt4
self.horizontalHeader().setResizeMode(
... | AttributeError | dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/widgets/errors_table.py/ErrorsTable.__init__ |
5,080 | def fromTable(self, data):
try:
(nmatches, nmismatches, nrepmatches, nns,
query_ngaps_counts, query_ngaps_bases,
sbjct_ngaps_counts, sbjct_ngaps_bases,
strand,
query_id, query_length, query_from, query_to,
sbjct_id, sbjct_length, sbjc... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/obsolete/BlatTest.py/Match.fromTable |
5,081 | def fromTable(self, data):
Match.fromTable(self, data)
try:
query_sequence, sbjct_sequence = data[21:23]
except __HOLE__:
raise ParsingError("parsing error", "\t".join(data))
self.mQuerySequence = query_sequence[:-1].split(",")
self.mSbjctSequence = sb... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/obsolete/BlatTest.py/MatchPSLX.fromTable |
5,082 | def next(self):
try:
return self.mIterator.next()
except __HOLE__:
return None | StopIteration | dataset/ETHPy150Open CGATOxford/cgat/obsolete/BlatTest.py/BlatIterator.next |
5,083 | def iterator_test(infile, report_step=100000):
'''only output parseable lines from infile.'''
ninput, noutput, nerrors = 0, 0, 0
while 1:
try:
x = infile.next()
except ParsingError, msg:
nerrors += 1
ninput += 1
E.warn(str(msg))
c... | StopIteration | dataset/ETHPy150Open CGATOxford/cgat/obsolete/BlatTest.py/iterator_test |
5,084 | def _read_eeglab_events(eeg, event_id=None, event_id_func='strip_to_integer'):
"""Create events array from EEGLAB structure
An event array is constructed by looking up events in the
event_id, trying to reduce them to their integer part otherwise, and
entirely dropping them (with a warning) if this is i... | TypeError | dataset/ETHPy150Open mne-tools/mne-python/mne/io/eeglab/eeglab.py/_read_eeglab_events |
5,085 | def execute(self):
res = 0
try:
# Be careful that generator terminates or this will iterate forever
while True:
self.logger.debug("About to call step()")
res = self.step()
self.logger.debug("Result is %d" % (res))
except __... | StopIteration | dataset/ETHPy150Open ejeschke/ginga/ginga/misc/tests/test_Task.py/stepTask.execute |
5,086 | def serve():
server = helloworld_pb2.beta_create_Greeter_server(Greeter())
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(_ONE_DAY_IN_SECONDS)
except __HOLE__:
server.stop() | KeyboardInterrupt | dataset/ETHPy150Open Akagi201/learning-python/grpc/helloworld/greeter_server.py/serve |
5,087 | def open(self, mode):
fn = self._fn
mock_target = self
class Buffer(BytesIO):
# Just to be able to do writing + reading from the same buffer
_write_line = True
def set_wrapper(self, wrapper):
self.wrapper = wrapper
def write(sel... | AttributeError | dataset/ETHPy150Open spotify/luigi/luigi/mock.py/MockTarget.open |
5,088 | def separate_range_build_list(dir_of_logs, unbzipped_logs, start_datetime, to_datetime, server_vers):
# todo - this is a bit big and nasty, but good enough for now
"""Opens current debug.log and un-bz'd logs and builds new list of loglines
that fall within our reporting period. Returns two lists of strin... | IOError | dataset/ETHPy150Open macadmins/sashay/sashay.py/separate_range_build_list |
5,089 | def _get_current_migration_number(self, database):
try:
result = Migration.objects.using(
database
).order_by('-migration_label')[0]
except __HOLE__:
return 0
match = MIGRATION_NAME_RE.match(result.migration_label)
return int(match.grou... | IndexError | dataset/ETHPy150Open paltman-archive/nashvegas/nashvegas/management/commands/upgradedb.py/Command._get_current_migration_number |
5,090 | def init_nashvegas(self):
# Copied from line 35 of django.core.management.commands.syncdb
# Import the 'management' module within each installed app, to
# register dispatcher events.
for app_name in settings.INSTALLED_APPS:
try:
import_module(".management", ap... | ImportError | dataset/ETHPy150Open paltman-archive/nashvegas/nashvegas/management/commands/upgradedb.py/Command.init_nashvegas |
5,091 | def seed_migrations(self, stop_at=None):
# @@@ the command-line interface needs to be re-thinked
# TODO: this needs to be able to handle multi-db when you're
# specifying stop_at
if stop_at is None and self.args:
stop_at = self.args[0]
if stop_at:
... | IndexError | dataset/ETHPy150Open paltman-archive/nashvegas/nashvegas/management/commands/upgradedb.py/Command.seed_migrations |
5,092 | def _get_default_migration_path(self):
try:
path = os.path.dirname(os.path.normpath(
os.sys.modules[settings.SETTINGS_MODULE].__file__)
)
except __HOLE__:
path = os.getcwd()
return os.path.join(path, "migrations") | KeyError | dataset/ETHPy150Open paltman-archive/nashvegas/nashvegas/management/commands/upgradedb.py/Command._get_default_migration_path |
5,093 | def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in range(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
... | ValueError | dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/utils/importlib.py/_resolve_name |
5,094 | def rischDE(fa, fd, ga, gd, DE):
"""
Solve a Risch Differential Equation: Dy + f*y == g.
See the outline in the docstring of rde.py for more information
about the procedure used. Either raise NonElementaryIntegralException, in
which case there is no solution y in the given differential field,
... | NotImplementedError | dataset/ETHPy150Open sympy/sympy/sympy/integrals/rde.py/rischDE |
5,095 | def parse_markdown_readme():
"""
Convert README.md to RST via pandoc, and load into memory
(fallback to LONG_DESCRIPTION on failure)
"""
try:
subprocess.call(
['pandoc', '-t', 'rst', '-o', 'README.rst', 'README.md']
)
except __HOLE__:
return LONG_DESCRIPTION
... | OSError | dataset/ETHPy150Open wq/django-rest-pandas/setup.py/parse_markdown_readme |
5,096 | def setMax(self, maximum):
"""Set the maximum value of the Slider. If the current value of
the Slider is out of new bounds, the value is set to new minimum.
@param maximum: new maximum value of the Slider
"""
self._max = maximum
try:
if float(str( self.getVa... | ValueError | dataset/ETHPy150Open rwl/muntjac/muntjac/ui/slider.py/Slider.setMax |
5,097 | def setMin(self, minimum):
"""Set the minimum value of the Slider. If the current value of
the Slider is out of new bounds, the value is set to new minimum.
@param minimum:
New minimum value of the Slider.
"""
self._min = minimum
try:
if f... | ValueError | dataset/ETHPy150Open rwl/muntjac/muntjac/ui/slider.py/Slider.setMin |
5,098 | def setup(self, shell):
"""Install auto-completions for the appropriate shell.
Args:
shell (str):
String specifying name of shell for which auto-completions
will be installed for.
"""
system = platform.system()
script = resource_string... | IOError | dataset/ETHPy150Open reviewboard/rbtools/rbtools/commands/setup_completion.py/SetupCompletion.setup |
5,099 | def view_docs(browser=None):
"""A script (``openmdao docs``) points to this. It just pops up a browser to
view the openmdao Sphinx docs. If the docs are not already built, it
builds them before viewing; but if the docs already exist, it's not smart enough
to rebuild them if they've changed since th... | ImportError | dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.util/src/openmdao/util/view_docs.py/view_docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.