Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
5,900
def validate_url(url): if not url.count('://'): url = "http://" + url validate = URLValidator(verify_exists=True) try: validate(url) return True except __HOLE__: return False
ValidationError
dataset/ETHPy150Open haystack/eyebrowse-server/common/view_helpers.py/validate_url
5,901
def get_config(self): try: return self.config except __HOLE__: pass self.config = ConfigParser.ConfigParser() path = self.ask('Path to the config?', '~/.pyplease') path = self.normalize_path(path) self.note('Using "%s" as config' % path...
AttributeError
dataset/ETHPy150Open va1en0k/please/pyplease/modules/please.py/Module.get_config
5,902
def _validate(self, value): try: if value != int(value): raise ValueError() value = int(value) except __HOLE__: raise ValueError("%s must be an integer" % self.label) if value < self.min: raise ValueError("%s must be >= %i" % (sel...
ValueError
dataset/ETHPy150Open glue-viz/glue/glue/core/simpleforms.py/IntOption._validate
5,903
def pop_command(self, id_): self.acquire() try: try: return self.commands.pop(id_) except __HOLE__: return None finally: self.release()
KeyError
dataset/ETHPy150Open Skype4Py/Skype4Py/Skype4Py/api/__init__.py/SkypeAPIBase.pop_command
5,904
def load_config(): """ Returns the config information """ # This is global _config_file = '{}/config.yaml'.format(os.getenv('POCS', '/var/panoptes/POCS')) _local_config_file = '{}/config_local.yaml'.format(os.getenv('POCS', '/var/panoptes/POCS')) _config = dict() # Load the global config t...
IOError
dataset/ETHPy150Open panoptes/POCS/panoptes/utils/config.py/load_config
5,905
def test_nC_nP_nT(): from sympy.utilities.iterables import ( multiset_permutations, multiset_combinations, multiset_partitions, partitions, subsets, permutations) from sympy.functions.combinatorial.numbers import ( nP, nC, nT, stirling, _multiset_histogram, _AOP_product) from sympy.c...
AssertionError
dataset/ETHPy150Open sympy/sympy/sympy/functions/combinatorial/tests/test_comb_numbers.py/test_nC_nP_nT
5,906
def _debug_body(self, body, headers): try: ctype = headers['content-type'] except __HOLE__: ctype = None if ctype is not None and ctype[:5] == 'text/': self.logger.debug("Body:") for line in str(body).split('\n'): self.logger.debug(" %s" % line) else: self.logger.d...
AttributeError
dataset/ETHPy150Open versionone/VersionOne.SDK.Python/v1pysdk/client.py/V1Server._debug_body
5,907
def fetch(self, path, query='', postdata=None): "Perform an HTTP GET or POST depending on whether postdata is present" url = self.build_url(path, query=query) self.logger.debug("URL: %s" % url) try: if postdata is not None: if isinstance(postdata, dict): postdata = urlencod...
HTTPError
dataset/ETHPy150Open versionone/VersionOne.SDK.Python/v1pysdk/client.py/V1Server.fetch
5,908
@frappe.whitelist(allow_guest=True) def accept(): args = frappe.form_dict files = [] web_form = frappe.get_doc("Web Form", args.web_form) if args.doctype != web_form.doc_type: frappe.throw(_("Invalid Request")) elif args.name and not web_form.allow_edit: frappe.throw(_("You are not allowed to update this Web...
ValueError
dataset/ETHPy150Open frappe/frappe/frappe/website/doctype/web_form/web_form.py/accept
5,909
def profile_start_response(self, app, environ, start_response): """Collect and store statistics for a single request. Use this method from middleware in place of the standard request-serving pattern. Do: profiler = RequestProfiler(...) return profiler(app, environ, start_...
StopIteration
dataset/ETHPy150Open gae-init/gae-init-debug/main/libx/gae_mini_profiler/profiler.py/RequestProfiler.profile_start_response
5,910
def _tuple_from_version(version): def _intify(s): try: return int(s) except __HOLE__: return s return tuple(_intify(b) for b in version.split('.'))
ValueError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/tools/cutarelease.py/_tuple_from_version
5,911
def _version_from_version_info(version_info): v = str(version_info[0]) state_dot_join = True for i in version_info[1:]: if state_dot_join: try: int(i) except __HOLE__: state_dot_join = False else: pass if sta...
ValueError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/tools/cutarelease.py/_version_from_version_info
5,912
def _version_info_from_version(version): m = _version_re.match(version) if not m: raise Error("could not convert '%s' version to version info" % version) version_info = [] for g in m.groups(): if g is None: break try: version_info.append(int(g)) ex...
ValueError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/tools/cutarelease.py/_version_info_from_version
5,913
def parse_changelog(changes_path): """Parse the given changelog path and return `(content, parsed, nyr)` where `nyr` is the ' (not yet released)' marker and `parsed` looks like: [{'body': u'\n(nothing yet)\n\n', 'verline': u'restify 1.0.1 (not yet released)', 'version': u'1.0.1'}, ...
ValueError
dataset/ETHPy150Open an0/Letterpress/code/markdown2/tools/cutarelease.py/parse_changelog
5,914
def get_pdf(html, options=None): html = scrub_urls(html) html, options = prepare_options(html, options) fname = os.path.join("/tmp", "frappe-pdf-{0}.pdf".format(frappe.generate_hash())) try: pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() ...
IOError
dataset/ETHPy150Open frappe/frappe/frappe/utils/pdf.py/get_pdf
5,915
def compile(self, sources, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None): macros, objects, extra_postargs, pp_opts, build = \ self._setup_compile(output_dir, macros, include_dirs, sources, ...
KeyError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/distutils/bcppcompiler.py/BCPPCompiler.compile
5,916
def _perform_request(self, request_type, resource, **kwargs): ''' Utility method that performs all requests. ''' request_type_methods = set(["get", "post", "put", "delete"]) if request_type not in request_type_methods: raise Exception("Unknown request type. Supported ...
ValueError
dataset/ETHPy150Open xmunoz/sodapy/sodapy/__init__.py/Socrata._perform_request
5,917
def _raise_for_status(response): ''' Custom raise_for_status with more appropriate error message. ''' http_error_msg = "" if 400 <= response.status_code < 500: http_error_msg = "{0} Client Error: {1}".format(response.status_code, respo...
ValueError
dataset/ETHPy150Open xmunoz/sodapy/sodapy/__init__.py/_raise_for_status
5,918
def __exit__(self, *args): for p in self.processes: try: p.wait() except __HOLE__: log.warning('%s failed', p)
OSError
dataset/ETHPy150Open romanz/amodem/amodem/alsa.py/Interface.__exit__
5,919
def supports_c_code(self, inputs): """ Returns True if the current op and reduce pattern has functioning C code. """ # If we don't even have the right method, we certainly # don't support the C code # (This is the test that used to be implemented by # lo...
NotImplementedError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/cuda/basic_ops.py/GpuCAReduce.supports_c_code
5,920
def truthiness(s): """Returns a boolean from a string""" try: return str(s).lower() in ['true', 't', '1'] except (__HOLE__, ValueError, UnicodeEncodeError): return False
TypeError
dataset/ETHPy150Open rehandalal/buchner/buchner/helpers.py/truthiness
5,921
def get_success_url(self): """ Returns the supplied URL. """ if self.success_url: url = self.success_url % self.object.__dict__ else: try: url = self.object.get_absolute_url() except __HOLE__: raise ImproperlyCon...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/views/generic/edit.py/ModelFormMixin.get_success_url
5,922
def evalfun(self, inputx): """ This is like self.f.evalfun(), i.e. evaluating the benchmark function, but without incrementing usage counters. This may be used only for re-evaluating a function at a point we already obtained but simply cannot conveniently retrieve right now; ...
TypeError
dataset/ETHPy150Open pasky/cocopf/experiment.py/FInstance.evalfun
5,923
def KeyboardListener(event): global choiceboxChoices, choiceboxWidget key = event.keysym if len(key) <= 1: if key in string.printable: # Find the key in the list. # before we clear the list, remember the selected member try: start_n = int(c...
IndexError
dataset/ETHPy150Open datalyze-solutions/pandas-qt/pandasqt/ui/fallback/easygui/boxes/base_boxes.py/KeyboardListener
5,924
def _init_pathinfo(): """Return a set containing all existing directory entries from sys.path""" d = set() for dir in sys.path: try: if os.path.isdir(dir): dir, dircase = makepath(dir) d.add(dircase) except __HOLE__: continue return...
TypeError
dataset/ETHPy150Open babble/babble/include/jython/Lib/site.py/_init_pathinfo
5,925
def addpackage(sitedir, name, known_paths): """Add a new path to known_paths by combining sitedir and 'name' or execute sitedir if it starts with 'import'""" if known_paths is None: _init_pathinfo() reset = 1 else: reset = 0 fullname = os.path.join(sitedir, name) try: ...
IOError
dataset/ETHPy150Open babble/babble/include/jython/Lib/site.py/addpackage
5,926
def __setup(self): if self.__lines: return data = None for dir in self.__dirs: for filename in self.__files: filename = os.path.join(dir, filename) try: fp = file(filename, "rU") data = fp.read() ...
IOError
dataset/ETHPy150Open babble/babble/include/jython/Lib/site.py/_Printer.__setup
5,927
def __call__(self): self.__setup() prompt = 'Hit Return for more, or q (and Return) to quit: ' lineno = 0 while 1: try: for i in range(lineno, lineno + self.MAXLINES): print self.__lines[i] except __HOLE__: break...
IndexError
dataset/ETHPy150Open babble/babble/include/jython/Lib/site.py/_Printer.__call__
5,928
def execsitecustomize(): """Run custom site specific code, if available.""" try: import sitecustomize except __HOLE__: pass
ImportError
dataset/ETHPy150Open babble/babble/include/jython/Lib/site.py/execsitecustomize
5,929
@synchronized('daemon-client-lock') def _get_client(cls, rootwrap_config): try: return cls._clients[rootwrap_config] except __HOLE__: from oslo_rootwrap import client new_client = client.Client([ "sudo", "nova-rootwrap-daemon", rootwrap_config]) ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/RootwrapDaemonHelper._get_client
5,930
def parse_server_string(server_str): """Parses the given server_string and returns a tuple of host and port. If it's not a combination of host part and port, the port element is an empty string. If the input is invalid expression, return a tuple of two empty strings. """ try: # First of ...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/parse_server_string
5,931
def is_valid_ipv6_cidr(address): try: netaddr.IPNetwork(address, version=6).cidr return True except (__HOLE__, netaddr.AddrFormatError): return False
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/is_valid_ipv6_cidr
5,932
def safe_ip_format(ip): """Transform ip string to "safe" format. Will return ipv4 addresses unchanged, but will nest ipv6 addresses inside square brackets. """ try: if netaddr.IPAddress(ip).version == 6: return '[%s]' % ip except (__HOLE__, netaddr.AddrFormatError): # hostn...
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/safe_ip_format
5,933
@contextlib.contextmanager def tempdir(**kwargs): argdict = kwargs.copy() if 'dir' not in argdict: argdict['dir'] = CONF.tempdir tmpdir = tempfile.mkdtemp(**argdict) try: yield tmpdir finally: try: shutil.rmtree(tmpdir) except __HOLE__ as e: LO...
OSError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/tempdir
5,934
def last_bytes(file_like_object, num): """Return num bytes from the end of the file, and remaining byte count. :param file_like_object: The file to read :param num: The number of bytes to return :returns (data, remaining) """ try: file_like_object.seek(-num, os.SEEK_END) except __...
IOError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/last_bytes
5,935
def validate_integer(value, name, min_value=None, max_value=None): """Make sure that value is a valid integer, potentially within range.""" try: value = int(str(value)) except (__HOLE__, UnicodeEncodeError): msg = _('%(value_name)s must be an integer') raise exception.InvalidInput(re...
ValueError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/validate_integer
5,936
def safe_truncate(value, length): """Safely truncates unicode strings such that their encoded length is no greater than the length provided. """ b_value = encodeutils.safe_encode(value)[:length] # NOTE(chaochin) UTF-8 character byte size varies from 1 to 6. If # truncating a long byte string to...
UnicodeDecodeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/utils.py/safe_truncate
5,937
def _validate_category(self, category): try: if category.type_id != self.parsed_obj["category"]: raise exception.OCCISchemaMismatch( expected=category.type_id, found=self.parsed_obj["category"] ) except __HOLE__: ...
KeyError
dataset/ETHPy150Open openstack/ooi/ooi/occi/validator.py/Validator._validate_category
5,938
def _compare_schemes(self, expected_type, actual): actual_scheme, actual_term = helpers.decompose_type(actual) if expected_type.scheme != actual_scheme: return False try: if expected_type.term != actual_term: return False except __HOLE__: ...
AttributeError
dataset/ETHPy150Open openstack/ooi/ooi/occi/validator.py/Validator._compare_schemes
5,939
def _validate_optional_links(self, expected, links): for uri, l in links.items(): try: rel = l['rel'] except __HOLE__: raise exception.OCCIMissingType(type_id=uri) for ex in expected: if rel == ex.type_id: br...
KeyError
dataset/ETHPy150Open openstack/ooi/ooi/occi/validator.py/Validator._validate_optional_links
5,940
def isNumber(num): "input is a number" try: cnum = complex(num) return True except __HOLE__: return False
ValueError
dataset/ETHPy150Open xraypy/xraylarch/lib/utils/strutils.py/isNumber
5,941
def request(url, method = "get", data = False, limit = config.max_api_pages): status = False req = urllib2.Request(url) if data: req = urllib2.Request(url, json.dumps(data)) try: req.get_method = lambda: method.upper() res = urllib2.urlopen(req) status = True re...
ValueError
dataset/ETHPy150Open jonmorehouse/vimhub/lib/github.py/request
5,942
def _to_seconds(var): sec = 0 MINUTE = 60 HOUR = 60 * MINUTE DAY = 24 * HOUR WEEK = 7 * DAY MONTH = 31 * DAY try: for key, value in var.items(): if key in ('second', 'seconds'): sec += value elif key in ('minute', 'minutes'): se...
AttributeError
dataset/ETHPy150Open ronnix/fabtools/fabtools/require/deb.py/_to_seconds
5,943
def first(self): try: return self.get_queryset()[0] except __HOLE__: pass
IndexError
dataset/ETHPy150Open mirumee/saleor/saleor/product/models/images.py/ImageManager.first
5,944
def lazy_load_library_exists(self): """check if libvirt is available.""" # try to connect libvirt. if fail, skip test. try: import libvirt import libxml2 except __HOLE__: return False global libvirt libvirt = __import__('libvirt') ...
ImportError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/tests/test_libvirt.py/LibvirtConnTestCase.lazy_load_library_exists
5,945
def lazy_load_library_exists(self): """check if libvirt is available.""" # try to connect libvirt. if fail, skip test. try: import libvirt import libxml2 except __HOLE__: return False global libvirt libvirt = __import__('libvirt') ...
ImportError
dataset/ETHPy150Open nii-cloud/dodai-compute/nova/tests/test_libvirt.py/IptablesFirewallTestCase.lazy_load_library_exists
5,946
def __eq__(self, other): ident = self.isidentical(other) if ident is True: return ident try: return self._eq(other) except __HOLE__: # e.g., we can't compare whole tables to other things (yet?) pass return False
AttributeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/core.py/Node.__eq__
5,947
def get_callable_name(o): """Welcome to str inception. Leave your kittens at home. """ # special case partial objects if isinstance(o, partial): keywords = o.keywords kwds = ( ', '.join('%s=%r' % item for item in keywords.items()) if keywords else '' ...
AttributeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/core.py/get_callable_name
5,948
def subs(o, d): """ Substitute values within data structure >>> subs(1, {1: 2}) 2 >>> subs([1, 2, 3], {2: 'Hello'}) [1, 'Hello', 3] """ d = dict((k, v) for k, v in d.items() if k is not v) if not d: return o try: if o in d: d = d.copy() o = d...
TypeError
dataset/ETHPy150Open blaze/blaze/blaze/expr/core.py/subs
5,949
def delete_dir(self): self.path = self.TestConfig['rdf.store_conf'] try: if self.TestConfig['rdf.source'] == "Sleepycat": subprocess.call("rm -rf " + self.path, shell=True) elif self.TestConfig['rdf.source'] == "ZODB": delete_zodb_data_store(self.p...
OSError
dataset/ETHPy150Open openworm/PyOpenWorm/tests/DataTestTemplate.py/_DataTest.delete_dir
5,950
def clean_coordinates(self): coords = self.cleaned_data['coordinates'].strip() if not coords: return None pieces = re.split('[ ,]+', coords) if len(pieces) != 2: raise forms.ValidationError('could not understand coordinates') try: lat = float...
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/locations/forms.py/LocationForm.clean_coordinates
5,951
def win_find_exe(filename, installsubdir=None, env="ProgramFiles"): """Find executable in current dir, system path or given ProgramFiles subdir""" for fn in [filename, filename+".exe"]: try: if installsubdir is None: path = _where(fn) else: path = ...
IOError
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/win_find_exe
5,952
def update(self, data): """Update info about network interface according to given dnet dictionary""" self.name = data["name"] self.description = data['description'] self.win_index = data['win_index'] # Other attributes are optional if conf.use_winpcapy: self._...
AttributeError
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/NetworkInterface.update
5,953
def load_from_powershell(self): for i in get_windows_if_list(): try: interface = NetworkInterface(i) self.data[interface.name] = interface except (__HOLE__, PcapNameNotFoundError): pass if len(self.data) == 0: log_loadin...
KeyError
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/NetworkInterfaceDict.load_from_powershell
5,954
def pcap_name(self, devname): """Return pcap device name for given Windows device name.""" try: pcap_name = self.data[devname].pcap_name except __HOLE__: raise ValueError("Unknown network interface %r" % devname) else: return pcap_name
KeyError
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/NetworkInterfaceDict.pcap_name
5,955
def pcap_name(devname): """Return pypcap device name for given libdnet/Scapy device name""" try: pcap_name = ifaces.pcap_name(devname) except __HOLE__: # pcap.pcap() will choose a sensible default for sniffing if iface=None pcap_name = None return pcap_name
ValueError
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/pcap_name
5,956
def sndrcv(pks, pkt, timeout = 2, inter = 0, verbose=None, chainCC=0, retry=0, multi=0): if not isinstance(pkt, Gen): pkt = SetGen(pkt) if verbose is None: verbose = conf.verb debug.recv = plist.PacketList([],"Unanswered") debug.sent = plist.PacketList([],"Sent") debug.match...
KeyboardInterrupt
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/sndrcv
5,957
def sniff(count=0, store=1, offline=None, prn = None, lfilter=None, L2socket=None, timeout=None, *arg, **karg): """Sniff packets sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets Select interface to sniff by setting conf.iface. Use show_interfaces() to...
KeyboardInterrupt
dataset/ETHPy150Open phaethon/scapy/scapy/arch/windows/__init__.py/sniff
5,958
def _request(method, url, content_type=None, _data=None): ''' Makes a HTTP request. Returns the JSON parse, or an obj with an error. ''' opener = _build_opener(_HTTPHandler) request = _Request(url, data=_data) if content_type: request.add_header('Content-Type', content_type) request....
HTTPError
dataset/ETHPy150Open saltstack/salt/salt/returners/couchdb_return.py/_request
5,959
def getargspec(obj): """ Get the names and default values of a callable's arguments A tuple of four things is returned: (args, varargs, varkw, defaults). - args is a list of the argument names (it may contain nested lists). - varargs and varkw are the names of the * and ...
NotImplementedError
dataset/ETHPy150Open koenbok/Cactus/cactus/utils/internal.py/getargspec
5,960
def close(self): try: self._context._tags[self.tagname].remove(self) except __HOLE__: pass return self._markup(self._close())
ValueError
dataset/ETHPy150Open jek/flatland/flatland/out/markup.py/Tag.close
5,961
def _attribute_sort_key(item): try: return (0, _static_attribute_order.index(item[0])) except __HOLE__: return (1, item[0])
ValueError
dataset/ETHPy150Open jek/flatland/flatland/out/markup.py/_attribute_sort_key
5,962
def _process_alive(pid): if exists("/proc"): return exists("/proc/%d" % pid) else: try: os.kill(int(pid), 0) return True except __HOLE__, err: return err.errno == errno.EPERM
OSError
dataset/ETHPy150Open tmm1/graphite/carbon/lib/carbon/conf.py/_process_alive
5,963
def handleAction(self): """Handle extra argument for backwards-compatibility. * C{start} will simply do minimal pid checking and otherwise let twistd take over. * C{stop} will kill an existing running process if it matches the C{pidfile} contents. * C{status}...
OSError
dataset/ETHPy150Open tmm1/graphite/carbon/lib/carbon/conf.py/CarbonCacheOptions.handleAction
5,964
@webapi_check_local_site @webapi_login_required def get(self, request, *args, **kwargs): """Returns the location of the current draft reply. If the draft reply exists, this will return :http:`302` with a ``Location`` header pointing to the URL of the draft. Any operations on the...
ObjectDoesNotExist
dataset/ETHPy150Open reviewboard/reviewboard/reviewboard/webapi/resources/review_reply_draft.py/ReviewReplyDraftResource.get
5,965
def __init__(self, path, value, raw_value=None, timestamp=None, precision=0, host=None, metric_type='COUNTER', ttl=None): """ Create new instance of the Metric class Takes: path=string: string the specifies the path of the metric value=[float|int]: the v...
ValueError
dataset/ETHPy150Open python-diamond/Diamond/src/diamond/metric.py/Metric.__init__
5,966
def _contains_bad_data(self, event): """ Check if the current event has any incorrect or badly formatted data. """ # All events must have a me if not self._check_media_id(event): print 'XXXX Fail!' return True try: # TODO: tru...
ValueError
dataset/ETHPy150Open pbs/agora-proc/agora/stats.py/PBSVideoStats._contains_bad_data
5,967
def _addEventMediaBufferingStart(self, event): self.buffer_start_events += 1 if not self._valid_buffering_length: return if self.is_buffering: # two MediaBufferingStart events in a row # toss stream self._invalidate_buffer_results() ret...
ValueError
dataset/ETHPy150Open pbs/agora-proc/agora/stats.py/PBSVideoStats._addEventMediaBufferingStart
5,968
def _addEventMediaBufferingEnd(self, event): if event.get('x_after_seek') == 'False': # only count buffering when not seeking return self.buffering_events += 1 if event.get('x_auto'): if event['x_auto'] == 'true': self.auto_bitrate = True ...
ValueError
dataset/ETHPy150Open pbs/agora-proc/agora/stats.py/PBSVideoStats._addEventMediaBufferingEnd
5,969
def is_equivalent(self, other, logger, tolerance=0.): """ Test if self and `other` are equivalent. other: :class:`FlowSolution` The flowfield to check against. logger: :class:`Logger` or None Used to log debug messages that will indicate what, if anything, is ...
AttributeError
dataset/ETHPy150Open OpenMDAO/OpenMDAO-Framework/openmdao.lib/src/openmdao/lib/datatypes/domain/flow.py/FlowSolution.is_equivalent
5,970
def add_file(self, file): try: if os.environ["OS"].startswith("Windows"): self.add_from_file( file ) #+ "\\builder.ui") except __HOLE__ as e: self.add_from_file( file ) #+ "/builder.ui")
KeyError
dataset/ETHPy150Open lionheart/TimeTracker-Linux/libs/UI.py/uiBuilder.add_file
5,971
def builder_build(self, *args, **kwargs): widget_list_dict = kwargs.get('widget_list_dict', {}) def parse_widgets(file): ids = re.compile("(?:id=\"([a-zA-Z0-9_]*?)\")+") classes = re.compile("(?:class=\"([a-zA-Z0-9_]*?)\")+") components = {} current = '' ...
KeyError
dataset/ETHPy150Open lionheart/TimeTracker-Linux/libs/UI.py/uiBuilder.builder_build
5,972
def _ensure_ascii(words): try: for i, word in enumerate(words): word.decode('ascii') except __HOLE__: raise ValueError("Token %d (%r) is non-ASCII. BLLIP Parser " "currently doesn't support non-ASCII inputs." % (i, word))
UnicodeDecodeError
dataset/ETHPy150Open nltk/nltk/nltk/parse/bllip.py/_ensure_ascii
5,973
def demo(): """This assumes the Python module bllipparser is installed.""" # download and install a basic unified parsing model (Wall Street Journal) # sudo python -m nltk.downloader bllip_wsj_no_aux from nltk.data import find model_dir = find('models/bllip_wsj_no_aux').path print('Loading BL...
StopIteration
dataset/ETHPy150Open nltk/nltk/nltk/parse/bllip.py/demo
5,974
def setup_module(module): from nose import SkipTest try: _ensure_bllip_import_or_error() except __HOLE__: raise SkipTest('doctests from nltk.parse.bllip are skipped because ' 'the bllipparser module is not installed')
ImportError
dataset/ETHPy150Open nltk/nltk/nltk/parse/bllip.py/setup_module
5,975
def test_bad_monitoring_input_in_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py avoids wrong # settings of channel_name or dataset_name in the constructor. dim = 3 m = 10 rng = np.random.RandomState([6, 2, 2014]) X = rng.randn(m, dim) learning_rate = 1e-2 ...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/training_algorithms/tests/test_sgd.py/test_bad_monitoring_input_in_monitor_based_lr
5,976
def testing_multiple_datasets_in_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py does not take # multiple datasets in which multiple channels ending in '_objective' # exist. # This case happens when the user has not specified either channel_name or # dataset_name in the c...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/training_algorithms/tests/test_sgd.py/testing_multiple_datasets_in_monitor_based_lr
5,977
def test_reject_mon_batch_without_mon(): # tests that setting up the sgd algorithm # without a monitoring dataset # but with monitoring_batches specified is an error dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) idx = rng.randint(0, dim, (m,)) Y...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/training_algorithms/tests/test_sgd.py/test_reject_mon_batch_without_mon
5,978
def test_determinism(): # Verifies that running SGD twice results in the same examples getting # visited in the same order for mode in _iteration_schemes: dim = 1 batch_size = 3 num_batches = 5 m = num_batches * batch_size dataset = ArangeDataset(m) model ...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/training_algorithms/tests/test_sgd.py/test_determinism
5,979
def test_uneven_batch_size(): """ Testing extensively sgd parametrisations for datasets with a number of examples not divisible by batch size The tested settings are: - Model with force_batch_size = True or False - Training dataset with number of examples divisible or not by batch size - Mo...
ValueError
dataset/ETHPy150Open lisa-lab/pylearn2/pylearn2/training_algorithms/tests/test_sgd.py/test_uneven_batch_size
5,980
def test_BasicHeader(self): template = ''' #from Cheetah.Filters import Markdown #transform Markdown $foo Header ====== ''' expected = '''<p>bar</p> <h1>Header</h1>''' try: template = Cheetah.Template.Template(template, searchList=[{'foo' : 'bar'}]) template = ...
ImportError
dataset/ETHPy150Open binhex/moviegrabber/lib/site-packages/Cheetah/Tests/Filters.py/BasicMarkdownFilterTest.test_BasicHeader
5,981
def get_permittee_from_threadlocals(kw): """ Wrapper to get a permittee keyword from threadlocals and make sure it is usable. """ # Just skip if perm checks are disabled if not ExpedientPermission.objects.are_checks_enabled(): return None d = threadlocals.get_thread_locals() ...
KeyError
dataset/ETHPy150Open fp7-ofelia/ocf/expedient/src/python/expedient/common/permissions/shortcuts.py/get_permittee_from_threadlocals
5,982
def contents(self): from django.contrib.admin.templatetags.admin_list import _boolean_icon from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin try: f, attr, value = lookup_field...
AttributeError
dataset/ETHPy150Open MongoEngine/django-mongoengine/django_mongoengine/mongo_admin/helpers.py/AdminReadonlyField.contents
5,983
def main(argparseOptions): global c, rOpt, appnamePrefix, rClient rOpt = argparseOptions c = string_ops.Printer(rOpt.enableColor) runningApps = [] timestamps = [] try: with open(os.devnull, 'w') as devnull: subprocess.check_call(['notify-send', '--version'], stdout=...
TypeError
dataset/ETHPy150Open ryran/ravshello/rav-notify.py/main
5,984
def validate(self, document): """ Check input for Python syntax errors. """ # When the input starts with Ctrl-Z, always accept. This means EOF in a # Python REPL. if document.text.startswith('\x1a'): return try: if self.get_compiler_flags:...
TypeError
dataset/ETHPy150Open jonathanslenders/ptpython/ptpython/validator.py/PythonValidator.validate
5,985
@admin_required(reviewers=True) def langpacks(request): if request.method == 'POST': try: tasks.fetch_langpacks.delay(request.POST['path']) except __HOLE__: messages.error(request, 'Invalid language pack sub-path provided.') return redirect('zadmin.langpacks') a...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/views.py/langpacks
5,986
@login_required @json_view def es_collections_json(request): app = request.GET.get('app', '') q = request.GET.get('q', '') qs = Collection.search() try: qs = qs.query(id__startswith=int(q)) except ValueError: qs = qs.query(name__match=q) try: qs = qs.filter(app=int(app)) ...
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/views.py/es_collections_json
5,987
@admin_required @post_required def featured_collection(request): try: pk = int(request.POST.get('collection', 0)) except __HOLE__: pk = 0 c = get_object_or_404(Collection, pk=pk) return render(request, 'zadmin/featured_collection.html', dict(collection=c))
ValueError
dataset/ETHPy150Open mozilla/addons-server/src/olympia/zadmin/views.py/featured_collection
5,988
def clean(self): cleaned_data = super(UpdateCaseGroupForm, self).clean() try: self.current_group = CommCareCaseGroup.get(self.cleaned_data.get('item_id')) except __HOLE__: raise forms.ValidationError("You're not passing in the group's id!") except ResourceNotFound...
AttributeError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/data_interfaces/forms.py/UpdateCaseGroupForm.clean
5,989
def nnlf_fr(self, thetash, x, frmask): # new frozen version # - sum (log pdf(x, theta),axis=0) # where theta are the parameters (including loc and scale) # try: if frmask != None: theta = frmask.copy() theta[np.isnan(frmask)] = thetash else: thet...
IndexError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/sandbox/distributions/sppatch.py/nnlf_fr
5,990
def expect_v2(self, fn=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False): '''calculate expected value of a function with respect to the distribution location and scale only tested on a few examples Parameters ---------- all parameters are keyword parameters fn : funct...
ValueError
dataset/ETHPy150Open statsmodels/statsmodels/statsmodels/sandbox/distributions/sppatch.py/expect_v2
5,991
def update(self, node): try: field_list = self.field_list except AttributeError: return for f in field_list: try: delattr(self, f) except AttributeError: pass try: func = getattr(node, 'ge...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/NodeInfoBase.update
5,992
def format(self, field_list=None, names=0): if field_list is None: try: field_list = self.field_list except __HOLE__: field_list = sorted(self.__dict__.keys()) fields = [] for field in field_list: try: f = getatt...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/NodeInfoBase.format
5,993
def get_build_env(self): """Fetch the appropriate Environment to build this node. """ try: return self._memo['get_build_env'] except __HOLE__: pass result = self.get_executor().get_build_env() self._memo['get_build_env'] = result return res...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_build_env
5,994
def get_executor(self, create=1): """Fetch the action executor for this node. Create one if there isn't already one, and requested to do so.""" try: executor = self.executor except __HOLE__: if not create: raise try: ac...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.get_executor
5,995
def executor_cleanup(self): """Let the executor clean up any cached information.""" try: executor = self.get_executor(create=None) except __HOLE__: pass else: if executor is not None: executor.cleanup()
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.executor_cleanup
5,996
def reset_executor(self): "Remove cached executor; forces recompute when needed." try: delattr(self, 'executor') except __HOLE__: pass
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.reset_executor
5,997
def visited(self): """Called just after this node has been visited (with or without a build).""" try: binfo = self.binfo except __HOLE__: # Apparently this node doesn't need build info, so # don't bother calculating or storing it. pass ...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.visited
5,998
def clear(self): """Completely clear a Node of all its cached state (so that it can be re-evaluated by interfaces that do continuous integration builds). """ # The del_binfo() call here isn't necessary for normal execution, # but is for interactive mode, where we might re...
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.clear
5,999
def builder_set(self, builder): self.builder = builder try: del self.executor except __HOLE__: pass
AttributeError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Node/__init__.py/Node.builder_set