Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
9,000
def identical(self, other): """Like equals, but also checks attributes. """ try: return (utils.dict_equiv(self.attrs, other.attrs) and self.equals(other)) except (__HOLE__, AttributeError): return False
TypeError
dataset/ETHPy150Open pydata/xarray/xarray/core/variable.py/Variable.identical
9,001
def find_length(owtf, http_helper, lsig, url, method, detection_struct, ch, headers, body=None): """This function finds the length of the fuzzing placeholder""" size = 8192 minv = 0 http_client = HTTPClient() new_url = url new_body = body new_headers = headers payload = "...
HTTPError
dataset/ETHPy150Open owtf/owtf/framework/http/wafbypasser/core/placeholder_length.py/find_length
9,002
def binary_search(http_helper, lsig, minv, maxv, url, method, detection_struct, ch, headers, body=None): mid = mid_value(minv, maxv) new_url = url new_body = body new_headers = headers if minv > maxv: return maxv http_client = HTTPClient() payloa...
HTTPError
dataset/ETHPy150Open owtf/owtf/framework/http/wafbypasser/core/placeholder_length.py/binary_search
9,003
def is_numeric(s): try: int(s) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/is_numeric
9,004
def run(self, history=False, settings=False, back=True): if not self.window.active_view(): return if not hasattr(self, 'history_manager'): self.history_manager = OverlayHistoryManager() self.back = back try: selection_count = len(self.window.active_vie...
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryShowMenu.run
9,005
def run(self, edit): try: text = sublime.get_clipboard() if text is not None and len(text) > 0: regions = [] sel = self.view.sel() items = text.split("\n") if len(items) == 1: items = [text] strip = True ...
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryPasteCommand.run
9,006
def run(self, edit, command, args=None, text=None, separator=None, items=None): try: cmd = Command.create(command, args) if cmd: items = items if text: items = text.split(separator) cmd.init(self.view, items) regions = [] ...
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryCommandWrapperCommand.run
9,007
def parse_date(self, s): date = None parse_date_formats = global_settings("parse_date_formats", []) for fmt in parse_date_formats: try: date = datetime.datetime.strptime(s, fmt) except __HOLE__: pass return date
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryDateRangeCommand.parse_date
9,008
def add_years(self, d, years): if years == 0: return d try: return d.replace(year = d.year + years) except __HOLE__: return d.replace(day = 28).replace(year = d.year + years)
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryDateRangeCommand.add_years
9,009
def add_months(self, d, m): if m == 0: return d years = 0 months = m + d.month years = int(months / 12) months = int(months % 12) if months == 0: years -= 1 months = 12 try: return self.add_years(d, years).replace(mo...
ValueError
dataset/ETHPy150Open duydao/Text-Pastry/text_pastry.py/TextPastryDateRangeCommand.add_months
9,010
def _parse_cron_yaml(self): """Loads the cron.yaml file and parses it. Returns: A croninfo.CronInfoExternal containing cron jobs. Raises: yaml_errors.Error, StandardError: The cron.yaml was invalid. """ for cron_yaml in ('cron.yaml', 'cron.yml'): try: with open(os.path.jo...
IOError
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/tools/devappserver2/admin/cron_handler.py/CronHandler._parse_cron_yaml
9,011
def get(self, key, default=None): """Get a string representing all headers with a particular value, with multiple headers separated by a comma. If no header is found return a default value :param key: The header name to look up (case-insensitive) :param default: The value to ret...
KeyError
dataset/ETHPy150Open w3c/wptserve/wptserve/request.py/RequestHeaders.get
9,012
def get_list(self, key, default=missing): """Get all the header values for a particular field name as a list""" try: return dict.__getitem__(self, key.lower()) except __HOLE__: if default is not missing: return default else: ...
KeyError
dataset/ETHPy150Open w3c/wptserve/wptserve/request.py/RequestHeaders.get_list
9,013
def __init__(self, *args, **kwds): # pylint: disable=E1003 '''Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary. ''' ...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/utils/odict.py/OrderedDict.__init__
9,014
def clear(self): 'od.clear() -> None. Remove all items from od.' try: for node in six.itervalues(self.__map): del node[:] root = self.__root root[:] = [root, root, None] self.__map.cl...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/utils/odict.py/OrderedDict.clear
9,015
def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) except __HOLE__: return self.__missing__(key)
KeyError
dataset/ETHPy150Open saltstack/salt/salt/utils/odict.py/DefaultOrderedDict.__getitem__
9,016
def _cleanup(request): """ Delete the context manager and everything else. """ del request._in_do del request._chunked del request._charset del request._unhandled del request._context try: del request._gen except __HOLE__: del request._callbacks del req...
AttributeError
dataset/ETHPy150Open ecdavis/pants/pants/web/asynchronous.py/_cleanup
9,017
def _do(request, input, as_exception=False): """ Send the provided input to the asynchronous request handler for *request*. If ``as_exception`` is truthy, throw it into the generator as an exception, otherwise it's just sent. """ if request._in_do: # Let's not enter some bizarre stack re...
StopIteration
dataset/ETHPy150Open ecdavis/pants/pants/web/asynchronous.py/_do
9,018
def callback(self, filename, lines, **kwargs): """publishes lines one by one to the given topic""" timestamp = self.get_timestamp(**kwargs) if kwargs.get('timestamp', False): del kwargs['timestamp'] for line in lines: try: import warnings ...
AttributeError
dataset/ETHPy150Open python-beaver/python-beaver/beaver/transports/mqtt_transport.py/MqttTransport.callback
9,019
def deserialize_json(self, json_value): try: value = json.loads(json_value) except __HOLE__: raise DeserializationError("Invalid JSON value for \"{}\": \"{}\"!".format(self.name, json_value), json_value, self.name) else: if value is not None: i...
ValueError
dataset/ETHPy150Open GreatFruitOmsk/nativeconfig/nativeconfig/options/array_option.py/ArrayOption.deserialize_json
9,020
def wordBreak_TLE(self, s, dict): """ TLE dfs O(n^2) Algorithm: DFS. The reason is that DFS repeatedly calculate whether a certain part of string can be segmented. Therefore we can use dynamic programming. :param s: a string :param dict: a set of...
IndexError
dataset/ETHPy150Open algorhythms/LeetCode/139 Word Break.py/Solution.wordBreak_TLE
9,021
def wordBreak(self, s, dict): """ __ __________ ___ __ ______ ______ .__ __. _______. | | | ____\ \ / / | | / | / __ \ | \ | | / | | | | |__ \ V / | | | ,----'| | | | | \| | | (----` | | | ...
IndexError
dataset/ETHPy150Open algorhythms/LeetCode/139 Word Break.py/Solution.wordBreak
9,022
def __init__(self, value, priority=0): value = unicode(value).strip() media_type = value.split(';') media_type, params = media_type[0].strip(), dict((i.strip() for i in p.split('=', 1)) for p in media_type[1:] if '=' in p) mt = self._MEDIA_TYPE_RE.match(media_type) if not mt: ...
ValueError
dataset/ETHPy150Open mollyproject/mollyproject/molly/utils/http.py/MediaType.__init__
9,023
@app.template_filter(name='truncatechars') def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except __HOLE__: # Invalid literal for int(). return value # Fail silently. ...
ValueError
dataset/ETHPy150Open dcramer/sentry-old/sentry/web/templatetags.py/truncatechars
9,024
def shutdown(self, timeout=None): """ Optional. """ try: shutdown_method = self._proxied_manager.shutdown except __HOLE__: return shutdown_method(timeout)
AttributeError
dataset/ETHPy150Open galaxyproject/pulsar/pulsar/managers/__init__.py/ManagerProxy.shutdown
9,025
def test_remove_invalid_reverse_domain(self): rd1 = self.create_domain(name='130', ip_type='4') rd1.save() rd2 = self.create_domain(name='130.193', ip_type='4') rd2.save() rd3 = self.create_domain(name='130.193.8', ip_type='4') rd3.save() try: rd1.dele...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/mozdns/domain/tests/reverse_tests.py/ReverseDomainTests.test_remove_invalid_reverse_domain
9,026
def test_add_reverse_domains(self): try: self.create_domain(name='192.168', ip_type='4').save() except __HOLE__, e: pass self.assertEqual(ValidationError, type(e)) e = None rdx = self.create_domain(name='192', ip_type='4') rdx.save() rdy = ...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/mozdns/domain/tests/reverse_tests.py/ReverseDomainTests.test_add_reverse_domains
9,027
def test_boot_strap_add_ipv6_domain(self): osu_block = "2.6.2.1.1.0.5.F.0.0.0" test_dname = osu_block + ".d.e.a.d.b.e.e.f" boot_strap_ipv6_reverse_domain(test_dname) try: self.create_domain( name='2.6.2.1.1.0.5.f.0.0.0', ip_type='6').save() except Vali...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/mozdns/domain/tests/reverse_tests.py/ReverseDomainTests.test_boot_strap_add_ipv6_domain
9,028
def test_add_reverse_domainless_ips(self): e = None try: self.add_ptr_ipv4('8.8.8.8') except __HOLE__, e: pass self.assertEqual(ValidationError, type(e)) e = None try: self.add_ptr_ipv6('2001:0db8:85a3:0000:0000:8a2e:0370:733') ...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/mozdns/domain/tests/reverse_tests.py/ReverseDomainTests.test_add_reverse_domainless_ips
9,029
def test_master_reverse_ipv6_domains(self): rds = [] rd = self.create_domain(name='1', ip_type='6') rd.save() rds.append(rd) rd = self.create_domain(name='1.2', ip_type='6') rd.save() rds.append(rd) rd = self.create_domain(name='1.2.8', ip_type='6') ...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/mozdns/domain/tests/reverse_tests.py/ReverseDomainTests.test_master_reverse_ipv6_domains
9,030
def get_global_step_var(): """ :returns: the global_step variable in the current graph. create if not existed""" try: return tf.get_default_graph().get_tensor_by_name(GLOBAL_STEP_VAR_NAME) except __HOLE__: var = tf.Variable( 0, trainable=False, name=GLOBAL_STEP_OP_NAME) r...
KeyError
dataset/ETHPy150Open ppwwyyxx/tensorpack/tensorpack/tfutils/common.py/get_global_step_var
9,031
@patch('prestoadmin.util.application.os.path.exists') @patch('prestoadmin.util.application.sys.stderr') def test_configures_invalid_log_file( self, stderr_mock, path_exists_mock, logging_mock, filesystem_mock ): path_exists_mock.return_value = True ex...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/util/test_application.py/ApplicationTest.test_configures_invalid_log_file
9,032
def run(self, rows, column_names): """ Apply type inference to the provided data and return an array of column types. :param rows: The data as a sequence of any sequences: tuples, lists, etc. """ num_columns = len(column_names) hypotheses = [set(self....
ValueError
dataset/ETHPy150Open wireservice/agate/agate/type_tester.py/TypeTester.run
9,033
def from_map(self, table, inconstrs, target='', rtables=None): """Initialize the dictionary of constraints by converting the input map :param table: table affected by the constraints :param inconstrs: YAML map defining the constraints """ if 'check_constraints' in inconstrs: ...
KeyError
dataset/ETHPy150Open perseas/Pyrseas/pyrseas/dbobject/constraint.py/ConstraintDict.from_map
9,034
def load_cookie(self, resp): cookie = http_cookies.SimpleCookie() try: cookie.load(resp.headers['Set-Cookie']) return cookie except __HOLE__: return None
KeyError
dataset/ETHPy150Open allisson/gunstar/tests/test_session.py/SessionTest.load_cookie
9,035
@staticmethod def _x_user_parser(user, data): _user = data.get('user_info', {}) user.email = _user.get('email') user.gender = _user.get('gender') user.id = _user.get('id') or _user.get('uid') user.locale = _user.get('default_lang') user.name = _user.get('ful...
ValueError
dataset/ETHPy150Open peterhudec/authomatic/authomatic/providers/oauth1.py/Plurk._x_user_parser
9,036
def _topological_sort(data, head, top_node, raise_exception = False, result = None, visited = None): """ Internal function """ if not result: result = [] if not visited: visited = [] deps = data.get(head, list()) if head in visited: if head == top_node and raise_exception...
ValueError
dataset/ETHPy150Open aldebaran/qibuild/python/qisys/sort.py/_topological_sort
9,037
def store_get_async(self, key, callback): try: value = self.store_get(key) callback(self, key, value) except __HOLE__: callback(self, key, None)
KeyError
dataset/ETHPy150Open kivy/kivy/kivy/storage/__init__.py/AbstractStore.store_get_async
9,038
def get_attribute(self, node, attr): try: attribute = node.attributes.get(attr) if attribute is not None: return attribute.value except __HOLE__: pass return None
KeyError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/cdat/scripts/parse_cdat_xml_file.py/XMLNode.get_attribute
9,039
def __init__(self, *args, **kwargs): signals.pre_init.send(sender=self.__class__, args=args, kwargs=kwargs) # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check ...
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/base.py/Model.__init__
9,040
def __repr__(self): try: u = unicode(self) except (UnicodeEncodeError, __HOLE__): u = '[Bad Unicode data]' return smart_str(u'<%s: %s>' % (self.__class__.__name__, u))
UnicodeDecodeError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/base.py/Model.__repr__
9,041
def _collect_sub_objects(self, seen_objs, parent=None, nullable=False): """ Recursively populates seen_objs with all objects related to this object. When done, seen_objs.items() will be in the format: [(model_class, {pk_val: obj, pk_val: obj, ...}), (model_class...
ObjectDoesNotExist
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/base.py/Model._collect_sub_objects
9,042
def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): op = is_next and 'gt' or 'lt' order = not is_next and '-' or '' param = smart_str(getattr(self, field.attname)) q = Q(**{'%s__%s' % (field.name, op): param}) q = q|Q(**{field.name: param, 'pk__%s' % op: self.pk})...
IndexError
dataset/ETHPy150Open CollabQ/CollabQ/vendor/django/db/models/base.py/Model._get_next_or_previous_by_FIELD
9,043
def name_from_signature(sig): """ Takes a method signature. Returns the method's name. Usage: >>> name_from_signature('spam_eggs(arg=<str>, arg2=<str>) -> <str>') 'spam_eggs' >>> """ try: return re.match(SIG_RE, sig).group('name') except __HOLE__: rai...
AttributeError
dataset/ETHPy150Open orokusaki/django-jsonrpc-2-0/jsonrpc/signatures.py/name_from_signature
9,044
def params_from_signature(sig): """ Takes a method signature, such as ``sig_example``. Returns a list of 3-tuples, each with a parameter, it's type, and whether it's optional. Usage: >>> params_from_signature('spam_eggs(arg=<str>, arg2=<str>) -> <str>') [('arg', 'str', False), ('arg2',...
AttributeError
dataset/ETHPy150Open orokusaki/django-jsonrpc-2-0/jsonrpc/signatures.py/params_from_signature
9,045
def return_type_from_signature(sig): """ Returns the string representation of the JSON type returned by a method (for use in ``jsonrpc.types.JSONRPCType``), based on a provided signature. Usage: >>> return_type_from_signature('spam_eggs(arg=<str>, arg2=<str>) -> <str>') 'str' >>> ...
AttributeError
dataset/ETHPy150Open orokusaki/django-jsonrpc-2-0/jsonrpc/signatures.py/return_type_from_signature
9,046
@sensitive_post_parameters() @never_cache @deprecate_current_app def password_reset_confirm(request, uidb64=None, token=None, template_name='registration/password_reset_confirm.html', token_generator=default_token_generator, set_password_f...
TypeError
dataset/ETHPy150Open django/django/django/contrib/auth/views.py/password_reset_confirm
9,047
def start(self, *args, **kwargs): self.running = True LOGGER.info("Starting: Hedwig Worker Service...") try: while self.running: if len(self.workers) < self.num_workers: worker = self.worker_cls(*args, **kwargs) worker.start() ...
KeyboardInterrupt
dataset/ETHPy150Open ofpiyush/hedwig-py/hedwig/core/service.py/ServiceManager.start
9,048
def thumbnail_generator(image_dict): """Generates a thumbnail. Loads the data slowly.""" # Why is it a generator-function and not just a function? thumb_dir = os.path.dirname(image_dict['data']['thumb']) if not os.path.exists(thumb_dir): os.mkdir(thumb_dir) loader = gtk.gdk.PixbufLoader() ...
IOError
dataset/ETHPy150Open thesamet/webilder/src/webilder/thumbs.py/thumbnail_generator
9,049
def receive_empty(self, empty, transaction): """ :type empty: Message :param empty: :type transaction: Transaction :param transaction: :rtype : Transaction """ if empty.type == defines.Types["RST"]: host, port = transaction.request.source ...
KeyError
dataset/ETHPy150Open Tanganelli/CoAPthon/coapthon/layers/observelayer.py/ObserveLayer.receive_empty
9,050
def remove_subscriber(self, message): logger.debug("Remove Subcriber") host, port = message.destination key_token = hash(str(host) + str(port) + str(message.token)) try: self._relations[key_token].transaction.completed = True del self._relations[key_token] ...
KeyError
dataset/ETHPy150Open Tanganelli/CoAPthon/coapthon/layers/observelayer.py/ObserveLayer.remove_subscriber
9,051
@contextlib.contextmanager def make_layout(layout): tempdir = tempfile.mkdtemp() for filename, file_content in layout.items(): real_path = os.path.join(tempdir, filename) try: os.makedirs(os.path.dirname(real_path)) except __HOLE__: # assume EEXIST pass with open(real_path, 'w') a...
OSError
dataset/ETHPy150Open wickman/pystachio/tests/test_config.py/make_layout
9,052
def _get_json(self, fullpage): try: # extract json from inside the first and last parens # from http://codereview.stackexchange.com/questions/2561/converting-jsonp-to-json-is-this-regex-correct page = fullpage[ fullpage.index("(")+1 : fullpage.rindex(")") ] except (At...
ValueError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/scopus.py/Scopus._get_json
9,053
def _extract_metrics_and_provenance_url(self, entries, status_code=200, id=None): try: max_citation = 0 for entry in entries: citation = int(entry["citedby-count"]) if citation > max_citation: max_citation = citation ...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/scopus.py/Scopus._extract_metrics_and_provenance_url
9,054
def _extract_relevant_records(self, fullpage, id): data = provider._load_json(fullpage) response = None try: response = data["search-results"]["entry"] except (__HOLE__, ValueError): # not in Scopus database return None return response
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/scopus.py/Scopus._extract_relevant_records
9,055
def _get_relevant_record_with_biblio(self, biblio_dict): try: url = self._get_scopus_url(biblio_dict) except __HOLE__: logger.debug("tried _get_relevant_record_with_biblio but leaving because KeyError") return None if not url: return None...
KeyError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/scopus.py/Scopus._get_relevant_record_with_biblio
9,056
def _map_list_types(hit_list, col_type): # TODO: handle missing because of VCF. try: if col_type in ("int", "integer"): return [int(h) for h in hit_list if not h in (None, 'nan')] elif col_type == "float": return [float(h) for h in hit_list if not h in (None, 'nan')] ...
ValueError
dataset/ETHPy150Open arq5x/gemini/gemini/gemini_annotate.py/_map_list_types
9,057
def fix_val(val, type): if not type in ("int", "float"): return val if isinstance(val, (int, float)): return val if type == "int": fn = int else: fn = float if not val: return None try: return fn(val) except __HOLE__: sys.exit('Non %s value found in annotation file: ...
ValueError
dataset/ETHPy150Open arq5x/gemini/gemini/gemini_annotate.py/fix_val
9,058
def get_hit_list(hits, col_idxs, args, _count={}): hits = list(hits) if len(hits) == 0: return [] hit_list = defaultdict(list) for hit in hits: if isinstance(hit, basestring): hit = hit.split("\t") if args.anno_file.endswith(('.vcf', '.vcf.gz')): # only m...
IndexError
dataset/ETHPy150Open arq5x/gemini/gemini/gemini_annotate.py/get_hit_list
9,059
def annotate_variants_extract(args, conn, metadata, col_names, col_types, col_ops, col_idxs): """ Populate a new, user-defined column in the variants table based on the value(s) from a specific column. in the annotation file. """ def summarize_hits(hits): hit_list = get_hit_list(hits, co...
ValueError
dataset/ETHPy150Open arq5x/gemini/gemini/gemini_annotate.py/annotate_variants_extract
9,060
def xilinx7_reader(csv_file): '''Extract the pin data from a Xilinx CSV file and return a dictionary of pin data.''' # Create a dictionary that uses the unit numbers as keys. Each entry in this dictionary # contains another dictionary that uses the side of the symbol as a key. Each entry in # that...
KeyError
dataset/ETHPy150Open xesscorp/KiPart/kipart/xilinx7_reader.py/xilinx7_reader
9,061
def clean_number(val): if val is not None and (isinstance(val, str) or isinstance(val, unicode)): try: # it's an int return int(val) except __HOLE__: pass try: # it's a float return float(val) except ValueError: pass # cannot co...
ValueError
dataset/ETHPy150Open ExCiteS/geokey/geokey/contributions/migrations/0010_auto_20150511_1132.py/clean_number
9,062
def _open(self, devpath): # Open i2c device try: self._fd = os.open(devpath, os.O_RDWR) except OSError as e: raise I2CError(e.errno, "Opening I2C device: " + e.strerror) self._devpath = devpath # Query supported functions buf = array.array('I', [...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/i2c.py/I2C._open
9,063
def transfer(self, address, messages): """Transfer `messages` to the specified I2C `address`. Modifies the `messages` array with the results of any read transactions. Args: address (int): I2C address. messages (list): list of I2C.Message messages. Raises: ...
IOError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/i2c.py/I2C.transfer
9,064
def close(self): """Close the i2c-dev I2C device. Raises: I2CError: if an I/O or OS error occurs. """ if self._fd is None: return try: os.close(self._fd) except __HOLE__ as e: raise I2CError(e.errno, "Closing I2C device: ...
OSError
dataset/ETHPy150Open vsergeev/python-periphery/periphery/i2c.py/I2C.close
9,065
@property def plugin(self): try: if self._plugin is not None: return self._plugin except __HOLE__: pass self._plugin = manager.NeutronManager.get_plugin() return self._plugin
AttributeError
dataset/ETHPy150Open openstack/neutron/neutron/db/dvr_mac_db.py/DVRDbMixin.plugin
9,066
def get_job(job_id): try: f = open(config_dir+"/"+job_id+".timer", "r") except __HOLE__, e: return None cfg_str = f.read() f.close() cfg = parse_config(cfg_str) cfg["id"] = job_id return cfg
OSError
dataset/ETHPy150Open emersion/bups/bups/scheduler/systemd.py/get_job
9,067
@receiver(post_save, sender=Task) def call_hook(sender, instance, **kwargs): if instance.hook: f = instance.hook if not callable(f): try: module, func = f.rsplit('.', 1) m = importlib.import_module(module) f = getattr(m, func) e...
AttributeError
dataset/ETHPy150Open Koed00/django-q/django_q/signals.py/call_hook
9,068
def test_jtheta_issue_79(): # near the circle of covergence |q| = 1 the convergence slows # down; for |q| > Q_LIM the theta functions raise ValueError mp.dps = 30 mp.dps += 30 q = mpf(6)/10 - one/10**6 - mpf(8)/10 * j mp.dps -= 30 # Mathematica run first # N[EllipticTheta[3, 1, 6/10 - 10...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/tests/test_elliptic.py/test_jtheta_issue_79
9,069
def upload(self, filepath): """Uploads file from filepath to Redmine and returns an assigned token""" if self.ver is not None and LooseVersion(str(self.ver)) < LooseVersion('1.4.0'): raise VersionMismatchError('File upload') try: with open(filepath, 'rb') as stream: ...
IOError
dataset/ETHPy150Open maxtepkeev/python-redmine/redmine/__init__.py/Redmine.upload
9,070
def download(self, url, savepath=None, filename=None): """Downloads file from Redmine and saves it to savepath or returns it as bytes""" self.requests['stream'] = True # We don't want to load the entire file into memory response = self.request('get', url, raw_response=True) self.reques...
ImportError
dataset/ETHPy150Open maxtepkeev/python-redmine/redmine/__init__.py/Redmine.download
9,071
def request(self, method, url, headers=None, params=None, data=None, raw_response=False): """Makes requests to Redmine and returns result in json format""" kwargs = dict(self.requests, **{ 'headers': headers or {}, 'params': params or {}, 'data': data or {}, }...
TypeError
dataset/ETHPy150Open maxtepkeev/python-redmine/redmine/__init__.py/Redmine.request
9,072
def check_kernel_gradient_functions(kern, X=None, X2=None, output_ind=None, verbose=False, fixed_X_dims=None): """ This function runs on kernels to check the correctness of their implementation. It checks that the covariance function is positive definite for a randomly generated data set. :param ke...
NotImplementedError
dataset/ETHPy150Open SheffieldML/GPy/GPy/testing/kernel_tests.py/check_kernel_gradient_functions
9,073
def test_Add_dims(self): k = GPy.kern.Matern32(2, active_dims=[2,self.D]) + GPy.kern.RBF(2, active_dims=[0,4]) + GPy.kern.Linear(self.D) k.randomize() self.assertRaises(IndexError, k.K, self.X) k = GPy.kern.Matern32(2, active_dims=[2,self.D-1]) + GPy.kern.RBF(2, active_dims=[0,4]) + GPy....
AssertionError
dataset/ETHPy150Open SheffieldML/GPy/GPy/testing/kernel_tests.py/KernelGradientTestsContinuous.test_Add_dims
9,074
@classmethod def select_feature(cls, instance, attr): try: val = getattr(instance, attr) except __HOLE__: try: val = getattr(cls, attr) except AttributeError: raise Exception('Attribute "%s" was not found on either the training inst...
AttributeError
dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/miner/classifiers/classifier.py/Classifier.select_feature
9,075
def obj_change_as_msg(self, obj, msg, meteor_ids=None): """Return DDP change message of specified type (msg) for obj.""" if meteor_ids is None: meteor_ids = {} try: meteor_id = meteor_ids[str(obj.pk)] except __HOLE__: meteor_id = None if meteor...
KeyError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/Collection.obj_change_as_msg
9,076
def user_queries(self, user, *params): """Return queries for this publication as seen by `user`.""" try: get_queries = self.get_queries except __HOLE__: # statically defined queries if self.queries is None: raise NotImplementedError( ...
AttributeError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/Publication.user_queries
9,077
@transaction.atomic def do_sub(self, id_, name, silent, *params): """Subscribe the current thread to the specified publication.""" try: pub = self.get_pub_by_name(name) except __HOLE__: if not silent: raise MeteorError(404, 'Subscription not found') ...
KeyError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/DDP.do_sub
9,078
@api_endpoint(decorate=False) def method(self, method, params, id_): """Invoke a method.""" try: handler = self.api_path_map()[method] except __HOLE__: raise MeteorError(404, 'Method not found', method) try: inspect.getcallargs(handler, *params) ...
KeyError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/DDP.method
9,079
def valid_subscribers(self, model, obj, using): """Calculate valid subscribers (connections) for obj.""" col_user_ids = {} col_connection_ids = collections.defaultdict(set) for sub in Subscription.objects.filter( collections__model_name=model_name(model), ).prefet...
KeyError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/DDP.valid_subscribers
9,080
def send_notify(self, model, obj, msg, using): """Dispatch PostgreSQL async NOTIFY.""" if model_name(model).split('.', 1)[0] in ('migrations', 'dddp'): return # never send migration or DDP internal models new_col_connection_ids = self.valid_subscribers(model, obj, using) ol...
AttributeError
dataset/ETHPy150Open django-ddp/django-ddp/dddp/api.py/DDP.send_notify
9,081
def tearDown(self): super(Cleanup, self).tearDown() ok = True while self._cleanups: fn, args, kwargs = self._cleanups.pop(-1) try: fn(*args, **kwargs) except __HOLE__: raise except...
KeyboardInterrupt
dataset/ETHPy150Open docker/docker-py/tests/base.py/Cleanup.tearDown
9,082
def _auth_by_signature(self): if self._client_key_loader_func is None: raise RuntimeError('Client key loader function was not defined') if 'Authorization' not in request.headers: raise Unauthorized() try: mohawk.Receiver( credentials_map=self....
KeyError
dataset/ETHPy150Open marselester/flask-api-utils/api_utils/auth.py/Hawk._auth_by_signature
9,083
def get_type(atype, prompt="", default=None, input=raw_input, error=default_error): """Get user input of a particular base type.""" while 1: if default is not None: text = input("%s [%s]> " % (prompt, default)) if not text: return default else: ...
ValueError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/get_type
9,084
def choose(somelist, defidx=0, prompt="choose", input=raw_input, error=default_error): """Select an item from a list. Returns the object selected from the list index. """ assert len(list(somelist)) > 0, "list to choose from has no elements!" print_menu_list(somelist) defidx = int(defidx) ass...
ValueError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/choose
9,085
def choose_multiple(somelist, chosen=None, prompt="choose multiple", input=raw_input, error=default_error): somelist = somelist[:] if chosen is None: chosen = [] while 1: print( "Choose from list. Enter to end, negative index removes from chosen.") print_menu_list(somelist) i...
IndexError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/choose_multiple
9,086
def choose_value(somemap, default=None, prompt="choose", input=raw_input, error=default_error): """Select an item from a mapping. Keys are indexes that are selected. Returns the value of the mapping key selected. """ first = print_menu_map(somemap) while 1: try: ri = get_input(pr...
ValueError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/choose_value
9,087
def choose_key(somemap, default=0, prompt="choose", input=raw_input, error=default_error): """Select a key from a mapping. Returns the key selected. """ keytype = type(print_menu_map(somemap)) while 1: try: userinput = get_input(prompt, default, input) except EOFError: ...
ValueError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/choose_key
9,088
def choose_multiple_from_map(somemap, chosen=None, prompt="choose multiple", input=raw_input, error=default_error): """Choose multiple items from a mapping. Returns a mapping of items chosen. Type in the key to select the values. """ somemap = somemap.copy() if chosen is None: ch...
KeyError
dataset/ETHPy150Open kdart/pycopia/core/pycopia/cliutils.py/choose_multiple_from_map
9,089
def _GetCN(self, x509cert): subject = x509cert.get_subject() try: cn_id = subject.nid["CN"] cn = subject.get_entries_by_nid(cn_id)[0] except __HOLE__: raise rdfvalue.DecodeError("Cert has no CN") self.common_name = rdfvalue.RDFURN(cn.get_data().as_text())
IndexError
dataset/ETHPy150Open google/grr/grr/lib/rdfvalues/crypto.py/RDFX509Cert._GetCN
9,090
def _get_stdout_binary(): try: return sys.stdout.buffer except __HOLE__: pass try: fd = sys.stdout.fileno() return os.fdopen(fd, 'ab', 0) except Exception: pass try: return sys.__stdout__.buffer except AttributeError: pass try: ...
AttributeError
dataset/ETHPy150Open alimanfoo/petl/petl/io/sources.py/_get_stdout_binary
9,091
def _get_stdin_binary(): try: return sys.stdin.buffer except AttributeError: pass try: fd = sys.stdin.fileno() return os.fdopen(fd, 'rb', 0) except Exception: pass try: return sys.__stdin__.buffer except __HOLE__: pass try: fd =...
AttributeError
dataset/ETHPy150Open alimanfoo/petl/petl/io/sources.py/_get_stdin_binary
9,092
def handle(self, panel_name=None, **options): if panel_name is None: raise CommandError("You must provide a panel name.") if options.get('dashboard') is None: raise CommandError("You must specify the name of the dashboard " "this panel will be regi...
OSError
dataset/ETHPy150Open CiscoSystems/avos/horizon/management/commands/startpanel.py/Command.handle
9,093
def get_context_text(pathfile): """ Parse file an return context ( yaml ) and text. Context is between "{% zorna" tag and "%}" tag """ start = re.compile(r'.*?{%\s*zorna\s+(.*?)(%}|$)') end = re.compile(r'(.*?)(%})') try: fin = open(pathfile, 'r') except __HOLE__: return ...
IOError
dataset/ETHPy150Open zorna/zorna/zorna/utils.py/get_context_text
9,094
def load_obj(load_path): """ Loads a saved on-disk representation to a python data structure. We currently support the following file formats: * python pickle (.pkl) Arguments: load_path (str): where to the load the serialized object (full path and file name...
AttributeError
dataset/ETHPy150Open NervanaSystems/neon/neon/util/persist.py/load_obj
9,095
def load_class(ctype): """ Helper function to take a string with the neon module and classname then import and return the class object Arguments: ctype (str): string with the neon module and class (e.g. 'neon.layers.layer.Linear') Returns: class """ # e...
ImportError
dataset/ETHPy150Open NervanaSystems/neon/neon/util/persist.py/load_class
9,096
def _get_data(self): adapter = self.data_source['adapter'] geo_col = self.data_source.get('geo_column', 'geo') try: loader = getattr(self, '_get_data_%s' % adapter) except __HOLE__: raise RuntimeError('unknown adapter [%s]' % adapter) data = loader(self.d...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/standard/maps.py/GenericMapReport._get_data
9,097
def _to_geojson(self, data, geo_col): def _parse_geopoint(raw): try: latlon = [float(k) for k in re.split(' *,? *', raw)[:2]] return [latlon[1], latlon[0]] # geojson is lon, lat except __HOLE__: return None metadata = {} de...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/reports/standard/maps.py/GenericMapReport._to_geojson
9,098
def do_bf(): i = 0 try: filename = "codes.txt" FILE = open (filename,"r" ) codes = FILE.readlines() FILE.close() except __HOLE__: screenLock.acquire() print "[+] codes.txt file not found! \n[+] Please put codes into codes.txt and re-run the program\n" screenLock.release() sys.exit(1...
IOError
dataset/ETHPy150Open mertsarica/hack4career/codes/pilight-bf.py/do_bf
9,099
@lazy_import def _win32txf(): try: import esky.fstransact.win32txf except __HOLE__: return None else: return esky.fstransact.win32txf
ImportError
dataset/ETHPy150Open cloudmatrix/esky/esky/fstransact/__init__.py/_win32txf