Unnamed: 0 int64 0 10k | function stringlengths 79 138k | label stringclasses 20
values | info stringlengths 42 261 |
|---|---|---|---|
9,500 | def get_logging_config(logging_dir):
try:
log_file = os.path.join(logging_dir, 'pynacea.log')
if not os.path.exists(logging_dir):
os.makedirs(logging_dir)
if not os.path.exists(log_file):
with open(log_file, 'w') as f:
pass
log_level = config.s... | KeyError | dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/get_logging_config |
9,501 | def check_negative(value):
e = argparse.ArgumentTypeError('{} is an invalid non-negative float value'.format(value))
try:
fvalue = float(value)
except __HOLE__:
raise e
if fvalue < 0:
raise e
return fvalue | ValueError | dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/check_negative |
9,502 | def get_number_string(line):
num_words = []
for word in line.split():
if hasattr(_locals, 'NUMBERS_MAP') and word in _locals.NUMBERS_MAP:
num_words.append(_locals.NUMBERS_MAP[word])
else:
try:
num = float(word)
if int(num) - num == 0:
... | TypeError | dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/get_number_string |
9,503 | def convert_to_num(word):
try:
return _locals.NUMBERS_MAP[word]
except AttributeError:
try:
num = float(word)
if num.is_integer():
num = int(num)
return str(num)
except (ValueError, __HOLE__, IndexError):
return None | TypeError | dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/convert_to_num |
9,504 | def log_message(log_handler, level, message):
try:
handler_method = getattr(log_handler, level)
handler_method(message)
except __HOLE__:
pass | AttributeError | dataset/ETHPy150Open evfredericksen/pynacea/pynhost/pynhost/utilities.py/log_message |
9,505 | def safe_import(module_name, class_name):
"""
try to import a module, and if it fails because an ImporError
it logs on WARNING, and logs the traceback on DEBUG level
"""
if type(class_name) is list:
for name in class_name:
safe_import(module_name, name)
return
package... | ImportError | dataset/ETHPy150Open qtile/qtile/libqtile/widget/__init__.py/safe_import |
9,506 | def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
inout = file(os.devnull, "r+")
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
... | OSError | dataset/ETHPy150Open openstack/gertty/gertty/app.py/BackgroundBrowser.open |
9,507 | def run(self):
try:
self.loop.run()
except __HOLE__:
pass | KeyboardInterrupt | dataset/ETHPy150Open openstack/gertty/gertty/app.py/App.run |
9,508 | def _syncOneChangeFromQuery(self, query):
number = changeid = restid = None
if query.startswith("change:"):
number = query.split(':')[1].strip()
try:
number = int(number)
except __HOLE__:
number = None
changeid = query.s... | ValueError | dataset/ETHPy150Open openstack/gertty/gertty/app.py/App._syncOneChangeFromQuery |
9,509 | @classmethod
def get_installer(cls, name, path, adapter_info, cluster_info, hosts_info):
try:
mod_file, path, descr = imp.find_module(name, [path])
if mod_file:
mod = imp.load_module(name, mod_file, path, descr)
config_manager = BaseConfigManager(adapt... | ImportError | dataset/ETHPy150Open openstack/compass-core/compass/deployment/installers/installer.py/BaseInstaller.get_installer |
9,510 | def get_all_permissions(self, user, obj=None):
"""Returns a set of permission strings that the user has.
This permission available to the user is derived from the user's
Keystone "roles".
The permissions are returned as ``"openstack.{{ role.name }}"``.
"""
if user.is_an... | KeyError | dataset/ETHPy150Open openstack/django_openstack_auth/openstack_auth/backend.py/KeystoneBackend.get_all_permissions |
9,511 | def _write_cache(self, code, ts, file_info):
""" Write the cached file for then given info, creating the
cache directory if needed. This call will suppress any
IOError or OSError exceptions.
Parameters
----------
code : types.CodeType
The code object to write... | IOError | dataset/ETHPy150Open ContinuumIO/ashiba/enaml/enaml/core/import_hooks.py/EnamlImporter._write_cache |
9,512 | @classmethod
def get_ip_port(cls, ip=None, port=None):
ip = ip or os.environ.get('LIBPROCESS_IP', '0.0.0.0')
try:
port = int(port or os.environ.get('LIBPROCESS_PORT', 0))
except __HOLE__:
raise cls.Error('Invalid ip/port provided')
return ip, port | ValueError | dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context.get_ip_port |
9,513 | def _get_dispatch_method(self, pid, method):
try:
return getattr(self._processes[pid], method)
except __HOLE__:
raise self.InvalidProcess('Unknown process %s' % pid)
except AttributeError:
raise self.InvalidMethod('Unknown method %s on %s' % (method, pid)) | KeyError | dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context._get_dispatch_method |
9,514 | def __erase_link(self, to_pid):
for pid, links in self._links.items():
try:
links.remove(to_pid)
log.debug('PID link from %s <- %s exited.' % (pid, to_pid))
self._processes[pid].exited(to_pid)
except __HOLE__:
continue | KeyError | dataset/ETHPy150Open wickman/compactor/compactor/context.py/Context.__erase_link |
9,515 | def rm_empty_dir(path):
try:
os.rmdir(path)
except __HOLE__: # directory might not exist or not be empty
pass | OSError | dataset/ETHPy150Open ContinuumIO/menuinst/menuinst/utils.py/rm_empty_dir |
9,516 | def utcparse(input):
""" Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
the timezone, so that it's compatible with normal datetime.datetime objects.
For safety this can also handle inputs that are either timestamps, or datetimes
"""
# prepare the input for t... | ValueError | dataset/ETHPy150Open fp7-ofelia/ocf/ofam/src/src/foam/sfa/util/sfatime.py/utcparse |
9,517 | def get_revision(self, id_):
"""Return the :class:`.Script` instance with the given rev id."""
id_ = self.as_revision_number(id_)
try:
return self._revision_map[id_]
except __HOLE__:
# do a partial lookup
revs = [x for x in self._revision_map
... | KeyError | dataset/ETHPy150Open goFrendiAsgard/kokoropy/kokoropy/packages/alembic/script.py/ScriptDirectory.get_revision |
9,518 | def ia_credentials_helper(client_id, client_secret,
credentials_cache_file="credentials.json",
cache_key="default"):
"""Helper function to manage a credentials cache during testing.
This function attempts to load and refresh a credentials object from a
... | IOError | dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/ia_credentials_helper |
9,519 | def google_equivalent(text1, text2):
# Google spreadsheets modify some characters, and anything that looks like
# a date. So this function will return true if text1 would equal text2 if
# both were input into a google cell.
lines1 = [l.replace('\t',' ').strip() for l in text1.splitlines()]
lin... | ValueError | dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/google_equivalent |
9,520 | def _get_value_for_column(self, key_tuple, raw_row, col):
# Given a column, and a row dictionary.. returns the value
# of the field corresponding with that column.
try:
header = self.header.col_lookup(col)
except __HOLE__:
logger.error("Unexpected: column %s... | KeyError | dataset/ETHPy150Open mbrenig/SheetSync/sheetsync/__init__.py/Sheet._get_value_for_column |
9,521 | def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
try:
if decode_content and self._decoder:
data = self._decoder.decompress(data)
except (__HOLE__, zlib.error) as e:
... | IOError | dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/requests/packages/urllib3/response.py/HTTPResponse._decode |
9,522 | def _update_chunk_length(self):
# First, we'll figure out length of a chunk and then
# we'll try to read it from socket.
if self.chunk_left is not None:
return
line = self._fp.fp.readline()
line = line.split(b';', 1)[0]
try:
self.chunk_left = int(l... | ValueError | dataset/ETHPy150Open CouchPotato/CouchPotatoServer/libs/requests/packages/urllib3/response.py/HTTPResponse._update_chunk_length |
9,523 | def __init__(self, parent):
parent.title = "PectoralisSegmentation" # TODO make this more human readable by adding spaces
parent.categories = ["Chest Imaging Platform"]
parent.dependencies = []
parent.contributors = ["Applied Chest Imaging Laboratory, Brigham and Women's Hopsital"] # replace with "First... | AttributeError | dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PectoralisSegmentation/PectoralisSegmentation.py/PectoralisSegmentation.__init__ |
9,524 | def conv_unixtime(t):
try:
t = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')
t = int(time.mktime(t.timetuple()))
except TypeError:
t = None
except __HOLE__:
print('error: invalid time \'%s\'' % t)
exit(1)
return t | ValueError | dataset/ETHPy150Open YoshiyukiYamauchi/mrtparse/examples/slice.py/conv_unixtime |
9,525 | def get_range(self, name, min_value=None, max_value=None, default=0):
"""Parses the given int argument, limiting it to the given range.
Args:
name: the name of the argument
min_value: the minimum int value of the argument (if any)
max_value: the maximum int value of the argument (if any)
... | ValueError | dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/ext/webapp/__init__.py/Request.get_range |
9,526 | def assert_has_keys(dct, required=[], optional=[]):
for k in required:
try:
assert k in dct
except __HOLE__:
extra_keys = set(dct.keys()).difference(set(required + optional))
raise AssertionError("found unexpected keys: %s" %
list(... | AssertionError | dataset/ETHPy150Open openstack/python-rackclient/rackclient/openstack/common/apiclient/fake_client.py/assert_has_keys |
9,527 | def client_request(self, client, method, url, **kwargs):
# Check that certain things are called correctly
if method in ["GET", "DELETE"]:
assert "json" not in kwargs
# Note the call
self.callstack.append(
(method,
url,
kwargs.get("header... | KeyError | dataset/ETHPy150Open openstack/python-rackclient/rackclient/openstack/common/apiclient/fake_client.py/FakeHTTPClient.client_request |
9,528 | def format_default_result(result):
try:
output = json.loads(result) if isinstance(result, six.string_types) else result
return _serialize(output)
except (ValueError, __HOLE__):
return result | TypeError | dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_default_result |
9,529 | def format_localrunner_result(result, do_serialize=True):
output = format_possible_failure_result(result)
# Add in various properties if they have values
stdout = result.get('stdout', None)
if stdout:
try:
output['stdout'] = stdout.strip()
except __HOLE__:
output[... | AttributeError | dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_localrunner_result |
9,530 | def format_pythonrunner_result(result):
output = format_possible_failure_result(result)
# Add in various properties if they have values
result_ = result.get('result', None)
if result_ is not None:
output['result'] = result_
stdout = result.get('stdout', None)
if stdout:
try:
... | AttributeError | dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/format_pythonrunner_result |
9,531 | def _get_result(self, data):
result = data.get('data', {'result': {}}).get('result', '{}')
try:
result = json.loads(result)
except __HOLE__:
# if json.loads fails then very return result as-is. Should not happen.
return result
return FORMATTERS.get(dat... | ValueError | dataset/ETHPy150Open StackStorm/st2contrib/packs/hubot/actions/post_result.py/PostResultAction._get_result |
9,532 | def test_object_qualname(self):
# Test preservation of function __qualname__ attribute.
try:
__qualname__ = function1o().__qualname__
except __HOLE__:
pass
else:
self.assertEqual(function1d().__qualname__, __qualname__) | AttributeError | dataset/ETHPy150Open GrahamDumpleton/wrapt/tests/test_nested_function.py/TestNamingNestedFunction.test_object_qualname |
9,533 | def __call__(self, obj, do_raise=False):
"""Select a datum to operate on.
Selects the relevant datum within the object.
:param obj: The object from which to select the object.
:param do_raise: If False (the default), return None if the
indexed datum does not ex... | IndexError | dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/Selector.__call__ |
9,534 | def __call__(self, obj, do_raise=False):
"""Returns empty string if the selected value does not exist."""
try:
return super(EmptyStringSelector, self).__call__(obj, True)
except __HOLE__:
return "" | KeyError | dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/EmptyStringSelector.__call__ |
9,535 | def apply(self, elem, obj):
"""Apply text and attributes to an etree.Element.
Applies the text and attribute instructions in the template
element to an etree.Element instance.
:param elem: An etree.Element instance.
:param obj: The base object associated with this template
... | KeyError | dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/TemplateElement.apply |
9,536 | def reset(self):
expatreader.ExpatParser.reset(self)
if self.forbid_dtd:
self._parser.StartDoctypeDeclHandler = self.start_doctype_decl
self._parser.EndDoctypeDeclHandler = None
if self.forbid_entities:
self._parser.EntityDeclHandler = self.entity_decl
... | AttributeError | dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/ProtectedExpatParser.reset |
9,537 | def safe_minidom_parse_string(xml_string):
"""Parse an XML string using minidom safely."""
try:
return minidom.parseString(xml_string, parser=ProtectedExpatParser())
except (sax.SAXParseException, __HOLE__,
expat.ExpatError, LookupError) as e:
# NOTE(Vijaya Erukala): XML input su... | ValueError | dataset/ETHPy150Open openstack/rack/rack/api/xmlutil.py/safe_minidom_parse_string |
9,538 | def compile_template(func):
try:
spec = inspect.getargspec(func)
except __HOLE__:
spec = ArgSpec((), 'args', 'kwargs', None)
# Slicing with [1:-1] to get rid of parentheses
spec_str = inspect.formatargspec(*spec)
assigns = '\n'.join(" __call.{0} = {0}".format(arg) for arg in... | TypeError | dataset/ETHPy150Open Suor/funcy/drafts/bench_decorators.py/compile_template |
9,539 | def eventlet_rpc_server():
pool = eventlet.GreenPool()
LOG.info(_LI("Eventlet based AMQP RPC server starting..."))
try:
neutron_rpc = service.serve_rpc()
except __HOLE__:
LOG.info(_LI("RPC was already started in parent process by "
"plugin."))
else:
pool.... | NotImplementedError | dataset/ETHPy150Open openstack/neutron/neutron/server/rpc_eventlet.py/eventlet_rpc_server |
9,540 | def _package_conf_ordering(conf, clean=True, keep_backup=False):
'''
Move entries in the correct file.
'''
if conf in SUPPORTED_CONFS:
rearrange = []
path = BASE_PATH.format(conf)
backup_files = []
for triplet in os.walk(path):
for file_name in triplet[2]:
... | IndexError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/_package_conf_ordering |
9,541 | def append_to_package_conf(conf, atom='', flags=None, string='', overwrite=False):
'''
Append a string or a list of flags for a given package or DEPEND atom to a
given configuration file.
CLI Example:
.. code-block:: bash
salt '*' portage_config.append_to_package_conf use string="app-admi... | OSError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/append_to_package_conf |
9,542 | def get_flags_from_package_conf(conf, atom):
'''
Get flags for a given package or DEPEND atom.
Warning: This only works if the configuration files tree is in the correct
format (the one enforced by enforce_nice_config)
CLI Example:
.. code-block:: bash
salt '*' portage_config.get_flag... | AttributeError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/get_flags_from_package_conf |
9,543 | def is_present(conf, atom):
'''
Tell if a given package or DEPEND atom is present in the configuration
files tree.
Warning: This only works if the configuration files tree is in the correct
format (the one enforced by enforce_nice_config)
CLI Example:
.. code-block:: bash
salt '*'... | IOError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/is_present |
9,544 | def get_all_cpv_use(cp):
'''
.. versionadded:: 2015.8.0
Uses portage to determine final USE flags and settings for an emerge.
@type cp: string
@param cp: eg cat/pkg
@rtype: lists
@return use, use_expand_hidden, usemask, useforce
'''
cpv = _get_cpv(cp)
portage = _get_portage()
... | KeyError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/get_all_cpv_use |
9,545 | def is_changed_uses(cp):
'''
.. versionadded:: 2015.8.0
Uses portage for determine if the use flags of installed package
is compatible with use flags in portage configs.
@type cp: string
@param cp: eg cat/pkg
'''
cpv = _get_cpv(cp)
i_flags, conf_flags = get_cleared_flags(cpv)
f... | ValueError | dataset/ETHPy150Open saltstack/salt/salt/modules/portage_config.py/is_changed_uses |
9,546 | def _Exists(self):
"""Returns true if the affinity group exists."""
show_cmd = [AZURE_PATH,
'account',
'affinity-group',
'show',
'--json',
self.name]
stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True)
try:
... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_network.py/AzureAffinityGroup._Exists |
9,547 | def _Exists(self):
"""Returns true if the storage account exists."""
show_cmd = [AZURE_PATH,
'storage',
'account',
'show',
'--json',
self.name]
stdout, _, _ = vm_util.IssueCommand(show_cmd, suppress_warning=True)
try:
... | ValueError | dataset/ETHPy150Open GoogleCloudPlatform/PerfKitBenchmarker/perfkitbenchmarker/providers/azure/azure_network.py/AzureStorageAccount._Exists |
9,548 | def init(self, app, cache, timeout=None, debug=None):
twitter_timeout = 60*60*24*365
if timeout > twitter_timeout:
raise Exception("TwitterOEmbedder: Cache expiry should not exceed 1 year "
"per Twitter API specification")
max_timeout = {'saslmemcached':60... | KeyError | dataset/ETHPy150Open eriktaubeneck/flask-twitter-oembedder/flask_twitter_oembedder.py/TwitterOEmbedder.init |
9,549 | @system.setter
def system(self, new_system):
if new_system is not None and not isinstance(new_system, System):
msg = "{} should be a valid pydy.System object".format(new_system)
raise TypeError(msg)
if new_system is not None:
msg = ('The {} attribute has already... | AttributeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.system |
9,550 | @times.setter
def times(self, new_times):
try:
if new_times is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'times cannot be set. Set Scene.system = None to '
'allow a time array t... | AttributeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.times |
9,551 | @states_symbols.setter
def states_symbols(self, new_states_symbols):
try:
if new_states_symbols is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'coordinates cannot be set. Set Scene.system = None '
... | AttributeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.states_symbols |
9,552 | @states_trajectories.setter
def states_trajectories(self, new_states_trajectories):
try:
if new_states_trajectories is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'states_trajectories cannot be set. Set... | AttributeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.states_trajectories |
9,553 | @constants.setter
def constants(self, new_constants):
try:
if new_constants is not None and self.system is not None:
msg = ('The system attribute has already been set, so the '
'constants cannot be set. Set Scene.system = None to '
'a... | AttributeError | dataset/ETHPy150Open pydy/pydy/pydy/viz/scene.py/Scene.constants |
9,554 | def _v1_auth(self, token_url):
creds = self.creds
headers = {}
headers['X-Auth-User'] = creds['username']
headers['X-Auth-Key'] = creds['password']
tenant = creds.get('tenant')
if tenant:
headers['X-Auth-Tenant'] = tenant
resp, resp_body = self._do_... | KeyError | dataset/ETHPy150Open rcbops/glance-buildpackage/glance/common/auth.py/KeystoneStrategy._v1_auth |
9,555 | def annotateWindows(contig, windows, gff_data, fasta, options):
"""annotate windows."""
index = IndexedGenome.IndexedGenome()
for g in gff_data:
index.add(g.contig, g.start, g.end, g)
is_gtf = options.is_gtf
if options.transform == "none":
transform = lambda x, y, z: map(lambda x:... | KeyError | dataset/ETHPy150Open CGATOxford/cgat/scripts/gff2table.py/annotateWindows |
9,556 | @environmentfilter
def do_first(environment, seq):
"""Return the first item of a sequence."""
try:
return iter(seq).next()
except __HOLE__:
return environment.undefined('No first item, sequence was empty.') | StopIteration | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_first |
9,557 | @environmentfilter
def do_last(environment, seq):
"""Return the last item of a sequence."""
try:
return iter(reversed(seq)).next()
except __HOLE__:
return environment.undefined('No last item, sequence was empty.') | StopIteration | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_last |
9,558 | @environmentfilter
def do_random(environment, seq):
"""Return a random item from the sequence."""
try:
return choice(seq)
except __HOLE__:
return environment.undefined('No random item, sequence was empty.') | IndexError | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_random |
9,559 | def do_int(value, default=0):
"""Convert the value into an integer. If the
conversion doesn't work it will return ``0``. You can
override this default using the first parameter.
"""
try:
return int(value)
except (TypeError, ValueError):
# this quirk is necessary so that "42.23"|i... | TypeError | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_int |
9,560 | def do_float(value, default=0.0):
"""Convert the value into a floating point number. If the
conversion doesn't work it will return ``0.0``. You can
override this default using the first parameter.
"""
try:
return float(value)
except (TypeError, __HOLE__):
return default | ValueError | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_float |
9,561 | def do_reverse(value):
"""Reverse the object or return an iterator the iterates over it the other
way round.
"""
if isinstance(value, basestring):
return value[::-1]
try:
return reversed(value)
except __HOLE__:
try:
rv = list(value)
rv.reverse()
... | TypeError | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_reverse |
9,562 | @environmentfilter
def do_attr(environment, obj, name):
"""Get an attribute of an object. ``foo|attr("bar")`` works like
``foo["bar"]`` just that always an attribute is returned and items are not
looked up.
See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.
"""
try:
... | AttributeError | dataset/ETHPy150Open IanLewis/kay/kay/lib/jinja2/filters.py/do_attr |
9,563 | def readfile(self,filepath=''):
"""Read a table from a file
Parameters:
1. filepath: the path to a file to read
"""
#open a file
fn=os.path.join(filepath,self.get_name()+'.xls')
try:
f=open(fn,'r')
except __HOLE__:
... | IOError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Table.readfile |
9,564 | def fit_to_db(self,chrom,i):
"""Fit the ith row of the table to the db"""
export_data=[]
for column in self.columns[1:]:
element=self.table[chrom][column][i]
if type(element).__name__=='list': element=str(element)[1:-1]+','
try:
export... | TypeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.fit_to_db |
9,565 | def add_row(self,chrom,elements):
"""Add a row to the table"""
try:
self[chrom]['coordinate'].append(elements[0])
self[chrom]['promoter'].append(elements[1])
self[chrom]['bipromoter'].append(elements[2])
self[chrom]['downstream'].append(elements[3... | IndexError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.add_row |
9,566 | def size(self,chrom=''):
"""Return a tuple of the table size"""
numcol=len(self.columns)
numrow=0
if not chrom:
chrs=self.get_chroms()
try:
for chr in chrs:
numrow+=len(self.table[chr][self.columns[1]])
exce... | IndexError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/AnnotTable.size |
9,567 | def fit_to_db(self,chrom):
"""Fit the ith row to the db"""
export_data=[chrom]
for column in self.columns[1:]:
element=self.table[chrom][column]
if column=='rel_loc' or column=='rel_loc_cds': element=element[0]+element[1]
if type(element)==list: element=str(e... | TypeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.fit_to_db |
9,568 | def summarize(self):
"""Summarize the table in 'whole' row"""
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return
# obtain a summary statistics
self.init_table('whole'... | AttributeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.summarize |
9,569 | def get_p(self):
"""Return a P object of probabilites"""
p=P()
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return p
for chrom in chroms:
total=self[chrom]['Ns']
... | AttributeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/Summary.get_p |
9,570 | def fit_to_db(self,chrom):
"""Fit the ith row to the db"""
export_data=[chrom]
for column in self.columns[1:]:
element=self.table[chrom][column]
if column=='rel_loc' or column=='rel_loc_cds': element=element[0]+element[1]
if type(element)==list: element=str(e... | TypeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/P.fit_to_db |
9,571 | def get_p(self):
"""Return a P object of probabilites"""
p=PGBG(numprom=self.numprom,numbiprom=self.numbiprom,numdown=self.numdown)
try:
chroms=self.get_chroms()
if not chroms: raise ValueError
except (__HOLE__,ValueError):
return p
... | AttributeError | dataset/ETHPy150Open taoliu/taolib/Assoc/tables.py/SummaryGBG.get_p |
9,572 | def collect_tcp(self, uri):
parsed = self.parse_url(uri)
try:
host, port = parsed.netloc.split(':')
port = int(port)
except __HOLE__:
self.log.error('OpenVPN expected host:port in URI, got "%s"',
parsed.netloc)
return
... | ValueError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/openvpn/openvpn.py/OpenVPNCollector.collect_tcp |
9,573 | def publish_number(self, key, value):
key = key.replace('/', '-').replace(' ', '_').lower()
try:
value = long(value)
except __HOLE__:
self.log.error('OpenVPN expected a number for "%s", got "%s"',
key, value)
return
else:
... | ValueError | dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/openvpn/openvpn.py/OpenVPNCollector.publish_number |
9,574 | def is_ipv6_supported():
has_ipv6_support = socket.has_ipv6
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s.close()
except socket.error as e:
if e.errno == errno.EAFNOSUPPORT:
has_ipv6_support = False
else:
raise
# check if there is ... | IOError | dataset/ETHPy150Open openstack/rack/rack/tests/utils.py/is_ipv6_supported |
9,575 | def from_str(self, s):
for typ in self.elem_types:
try:
return typ.from_str(s)
except __HOLE__:
pass
raise ValueError('No match found') | ValueError | dataset/ETHPy150Open rllab/rllab/rllab/envs/box2d/parser/xml_attr_types.py/Either.from_str |
9,576 | @property
def apps(self):
INSTALLED_APPS = []
# optionaly enable sorl.thumbnail
try:
import sorl # noqa
INSTALLED_APPS += ['sorl.thumbnail']
except Exception:
pass
# optionaly enable easy_thumbnails
try:
import easy_... | ImportError | dataset/ETHPy150Open django-leonardo/django-leonardo/leonardo/module/web/__init__.py/Default.apps |
9,577 | def _SetupColours():
"""Initializes the colour constants.
"""
# pylint: disable=W0603
# due to global usage
global _INFO_SEQ, _WARNING_SEQ, _ERROR_SEQ, _RESET_SEQ
# Don't use colours if stdout isn't a terminal
if not sys.stdout.isatty():
return
try:
import curses
except __HOLE__:
# Don'... | ImportError | dataset/ETHPy150Open ganeti/ganeti/qa/qa_logging.py/_SetupColours |
9,578 | def validate_number(self, number):
"""Validates the given 1-based page number.
Override to stop checking if we have gone to far since that requires
knowing the total number of pages.
"""
try:
number = int(number)
except __HOLE__:
raise PageNotAnIn... | ValueError | dataset/ETHPy150Open mozilla/kitsune/kitsune/sumo/paginator.py/SimplePaginator.validate_number |
9,579 | def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
parser = E.OptionParser(version="%prog version: $Id: matrix2stats.py 2795 2009-09-16 15:29:23Z andreas $",
usage=globals()... | ValueError | dataset/ETHPy150Open CGATOxford/cgat/scripts/matrix2stats.py/main |
9,580 | @staticmethod
def _get_commands(inst):
cmds = {}
for objname in dir(inst):
obj = getattr(inst, objname)
if getattr(obj, '_is_cmd', False):
try:
cmds[obj._cmd_name] = (obj, inst)
except __HOLE__:
# skip it... | AttributeError | dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase._get_commands |
9,581 | @classmethod
def command_instance(cls, cmd_name):
try:
return cls._cmds[cmd_name][1]
except __HOLE__:
raise CommandNotFoundError(cmd_name) | KeyError | dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase.command_instance |
9,582 | @classmethod
def command_function(cls, cmd_name):
try:
return cls._cmds[cmd_name][0]
except __HOLE__:
raise CommandNotFoundError(cmd_name) | KeyError | dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandBase.command_function |
9,583 | def __getattr__(self, key):
try:
return getattr(self.wrapped_module, key)
except __HOLE__:
return getattr(CommandBase, key) | AttributeError | dataset/ETHPy150Open rackerlabs/openstack-guest-agents-unix/commands/__init__.py/CommandModuleWrapper.__getattr__ |
9,584 | @login_required
def log_detail(request, slug, id, template='threebot/workflow/log.html'):
orgs = get_my_orgs(request)
workflow_log = get_object_or_404(WorkflowLog, id=id)
workflow = get_object_or_404(Workflow, owner__in=orgs, slug=slug)
try:
templates = render_templates(workflow_log, mask=True)
... | AttributeError | dataset/ETHPy150Open 3bot/3bot/threebot/views/workflow.py/log_detail |
9,585 | @login_required
def log_detail_render(request, slug, id):
# get id params, slug+type
format = request.GET.get("format", 'raw')
wf_task_slug = request.GET.get("task")
orgs = get_my_orgs(request)
workflow_log = get_object_or_404(WorkflowLog, id=id)
workflow = get_object_or_404(Workflow, owner__in... | KeyError | dataset/ETHPy150Open 3bot/3bot/threebot/views/workflow.py/log_detail_render |
9,586 | def calculate_total_active(self):
""" Read proc.txt file and calculate 'self.active' and 'self.total' """
all_cores = set(xrange(self.cores))
self.total = [[] for _ in all_cores]
self.active = [[] for _ in all_cores]
with open(self.infile, "r") as fh:
# parsing logic:... | StopIteration | dataset/ETHPy150Open ARM-software/workload-automation/wlauto/instrumentation/coreutil/__init__.py/Calculator.calculate_total_active |
9,587 | def reset_module_registry(module):
try:
registry = module.__warningregistry__
except __HOLE__:
pass
else:
registry.clear() | AttributeError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/reset_module_registry |
9,588 | def test_forbidden_names(self):
# So we don't screw up our globals
def safe_exec(expr):
def f(**kwargs): pass
exec expr in {'f' : f}
tests = [("True", "assignment to True or False is forbidden in 3.x"),
("False", "assignment to True or False is forbidden... | NameError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/TestPy3KWarnings.test_forbidden_names |
9,589 | def check_removal(self, module_name, optional=False):
"""Make sure the specified module, when imported, raises a
DeprecationWarning and specifies itself in the message."""
with CleanImport(module_name), warnings.catch_warnings():
warnings.filterwarnings("error", ".+ (module|package) ... | ImportError | dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_py3kwarn.py/TestStdlibRemovals.check_removal |
9,590 | def get_hexdigest(algorithm, salt, raw_password):
"""
Returns a string of the hexdigest of the given plaintext password and salt
using the given algorithm ('md5', 'sha1' or 'crypt').
"""
raw_password, salt = smart_str(raw_password), smart_str(salt)
if algorithm == 'crypt':
try:
... | ImportError | dataset/ETHPy150Open aino/django-primate/primate/auth/helpers.py/get_hexdigest |
9,591 | def setup(self):
# Check mode
if self.args.mode =="rw":
print("Mode = %s, changes to file will be committed to disk." % self.args.mode)
elif self.args.mode != "r":
print("Warning: invalud mode: " + self.args.mode)
# Try to read in file
print("Reading: " + self.ar... | KeyboardInterrupt | dataset/ETHPy150Open grantbrown/laspy/laspy/tools/lasexplorer.py/lasexplorer.setup |
9,592 | def _handle_other(self, text):
if text.startswith('&'):
# deal with undefined entities
try:
text = unichr(entities.name2codepoint[text[1:-1]])
self._enqueue(TEXT, text)
except __HOLE__:
filename, lineno, offset = self._getpos()
... | KeyError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/XMLParser._handle_other |
9,593 | def handle_entityref(self, name):
try:
text = unichr(entities.name2codepoint[name])
except __HOLE__:
text = '&%s;' % name
self._enqueue(TEXT, text) | KeyError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/HTMLParser.handle_entityref |
9,594 | def handle_pi(self, data):
if data.endswith('?'):
data = data[:-1]
try:
target, data = data.split(None, 1)
except __HOLE__:
# PI with no data
target = data
data = ''
self._enqueue(PI, (target.strip(), data.strip())) | ValueError | dataset/ETHPy150Open timonwong/OmniMarkupPreviewer/OmniMarkupLib/Renderers/libs/python2/genshi/input.py/HTMLParser.handle_pi |
9,595 | def generate_create_database(engine_str):
"Generate a create_database function that creates the database"
if engine_str == 'sqlite':
import sqlite3
dbi = sqlite3
def create_database_sqlite(admin_username, admin_password, database_name, new_user, new_password, host = "localhost", port =... | ImportError | dataset/ETHPy150Open weblabdeusto/weblabdeusto/server/src/weblab/admin/deploy.py/generate_create_database |
9,596 | def parse_date_to_obj(date_str):
try:
return parse(date_str)
except __HOLE__:
raise ValueError("Invalid date", date_str) | ValueError | dataset/ETHPy150Open practo/r5d4/r5d4/mapping_functions.py/parse_date_to_obj |
9,597 | def expand_integer(str_range):
"""
>>> expand_integer('1') == set(['1'])
True
>>> expand_integer('1..5,10') == set(['1','2','3','4','5','10'])
True
>>> expand_integer('9..3') == set(['3','4','5','6','7','8','9'])
True
>>> expand_integer('1..5,8..3') == set(['1','2','3','4','5','6','7'... | ValueError | dataset/ETHPy150Open practo/r5d4/r5d4/mapping_functions.py/expand_integer |
9,598 | def parse_table_definition_file(file, options):
'''
This function parses the input to get run sets and columns.
The param 'file' is an XML file defining the result files and columns.
If column titles are given in the XML file,
they will be searched in the result files.
If no title is given, all... | IOError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/tablegenerator/__init__.py/parse_table_definition_file |
9,599 | def _get_decimal_digits(decimal_number_match, number_of_significant_digits):
"""
Returns the amount of decimal digits of the given regex match, considering the number of significant
digits for the provided column.
@param decimal_number_match: a regex match of a decimal number, resulting from REGEX_MEAS... | TypeError | dataset/ETHPy150Open sosy-lab/benchexec/benchexec/tablegenerator/__init__.py/_get_decimal_digits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.