Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,100
def find_in_workspaces(search_dirs=None, project=None, path=None, _workspaces=None, considered_paths=None, first_matching_workspace_only=False, first_match_only=False, workspace_to_source_spaces=None, source_path_to_packages=None): ''' Find all paths which match the search criteria. All workspaces are searc...
StopIteration
dataset/ETHPy150Open ros/catkin/python/catkin/find_in_workspaces.py/find_in_workspaces
8,101
def _remove_method(self, meths, method): try: meths.remove(method) except __HOLE__: pass
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._remove_method
8,102
def _find_toggle_methods(self, klass, methods): """Find/store methods of the form <Value>{On,Off} in the given `methods`. Returns the remaining list of methods. """ meths = methods[:] tm = self.toggle_meths for method in meths[:]: if method[-2:] == '...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_toggle_methods
8,103
def _find_state_methods(self, klass, methods): """Find/store methods of the form Set<Prop>To<Value> in the given `methods`. Returns the remaining list of methods. The method also computes the mapped value of the different <Values>. """ # These ignored ones are r...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_state_methods
8,104
def _find_get_set_methods(self, klass, methods): """Find/store methods of the form {Get,Set}Prop in the given `methods` and returns the remaining list of methods. Note that it makes sense to call this *after* `_find_state_methods` is called in order to avoid incorrect dupl...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._find_get_set_methods
8,105
def _get_instance(self, klass): """Given a VTK class, `klass`, returns an instance of the class. If the class is abstract, it uses the class tree to return an instantiable subclass. This is necessary to get the values of the 'state' methods and the ranges for the Get/Set ...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/contrib/titan/vtk_parser.py/VTKMethodParser._get_instance
8,106
def load_config(config_file): error = None paths = [config_file] if config_file else ["blockade.yaml", "blockade.yml"] try: for path in paths: try: with open(path) as f: d = yaml.safe_load(f) ...
IOError
dataset/ETHPy150Open dcm-oss/blockade/blockade/cli.py/load_config
8,107
def main(args=None): parser = setup_parser() opts = parser.parse_args(args=args) rc = 0 try: opts.func(opts) except InsufficientPermissionsError as e: puts_err(colored.red("\nInsufficient permissions error:\n") + str(e) + "\n") rc = 1 except BlockadeError as e: ...
KeyboardInterrupt
dataset/ETHPy150Open dcm-oss/blockade/blockade/cli.py/main
8,108
def buildAttributes(self, node, attrs, already_processed): value = find_attr_value_('ordinal_position', node) if value is not None: try: self.ordinal_position = int(value) except __HOLE__ as exp: raise_parse_error(node, 'Bad integer attribute: %s'...
ValueError
dataset/ETHPy150Open CybOXProject/python-cybox/cybox/bindings/http_session_object.py/HTTPRequestResponseType.buildAttributes
8,109
def execute(self): """ Called to execute the task. This method is called from multiple threads in a parallel build, so only do thread safe stuff here. Do thread unsafe stuff in prepare(), executed() or failed(). """ T = self.tm.trace if T: T.write(self.t...
IOError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Task.execute
8,110
def _exception_raise(self): """ Raises a pending exception that was recorded while getting a Task ready for execution. """ exc = self.exc_info()[:] try: exc_type, exc_value, exc_traceback = exc except __HOLE__: exc_type, exc_value = exc ...
ValueError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Task._exception_raise
8,111
def find_next_candidate(self): """ Returns the next candidate Node for (potential) evaluation. The candidate list (really a stack) initially consists of all of the top-level (command line) targets provided when the Taskmaster was initialized. While we walk the DAG, visiting Nod...
IndexError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster.find_next_candidate
8,112
def _find_next_ready_node(self): """ Finds the next node that is ready to be built. This is *the* main guts of the DAG walk. We loop through the list of candidates, looking for something that has no un-built children (i.e., that is a leaf Node or has dependencies that are ...
SystemExit
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster._find_next_ready_node
8,113
def will_not_build(self, nodes, node_func=lambda n: None): """ Perform clean-up about nodes that will never be built. Invokes a user defined function on all of these nodes (including all of their parents). """ T = self.trace pending_children = self.pending_child...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Taskmaster.py/Taskmaster.will_not_build
8,114
@classmethod def mpc_convert_lhs(cls, x): try: y = cls.context.convert(x) return y except __HOLE__: return NotImplemented
TypeError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_mp_python.py/_mpc.mpc_convert_lhs
8,115
def convert(ctx, x, strings=True): """ Converts *x* to an ``mpf`` or ``mpc``. If *x* is of type ``mpf``, ``mpc``, ``int``, ``float``, ``complex``, the conversion will be performed losslessly. If *x* is a string, the result will be rounded to the present working precision...
ValueError
dataset/ETHPy150Open fredrik-johansson/mpmath/mpmath/ctx_mp_python.py/PythonMPContext.convert
8,116
def get_ext_modules(use_cython=USE_CYTHON): global cmdclass python_header_dir = get_python_header_dir() if use_cython: try: from Cython.Distutils import build_ext except __HOLE__: stderr.write('\"cython\" is not installed. Forcing \"USE_CYTHON\" ' ...
ImportError
dataset/ETHPy150Open mulhod/reviewer_experience_prediction/setup.py/get_ext_modules
8,117
def __init__(self, qname, rdtype, rdclass, response): self.qname = qname self.rdtype = rdtype self.rdclass = rdclass self.response = response min_ttl = -1 rrset = None for count in xrange(0, 15): try: rrset = response.find_rrset(respons...
KeyError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Answer.__init__
8,118
def read_resolv_conf(self, f): """Process f as a file in the /etc/resolv.conf format. If f is a string, it is used as the name of the file to open; otherwise it is treated as the file itself.""" if isinstance(f, str) or isinstance(f, unicode): try: f = open(f...
IOError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Resolver.read_resolv_conf
8,119
def _win32_is_nic_enabled(self, lm, guid, interface_key): # Look in the Windows Registry to determine whether the network # interface corresponding to the given guid is enabled. # # (Code contributed by Paul Marks, thanks!) # try: # This hard-coded loca...
ValueError
dataset/ETHPy150Open catap/namebench/nb_third_party/dns/resolver.py/Resolver._win32_is_nic_enabled
8,120
def parseBitShiftConstant(s, pos, tokens): try: c1, c2 = tokens[0] return int(c1) << int(c2) except __HOLE__: c1, c2, c3 = tokens[0] return (int(c1) << int(c2)) - c3 # # Rudimentary C source grammar # # Limitations: # # - Macros are not processed. # - The function body parser eats newlines and wh...
ValueError
dataset/ETHPy150Open skyostil/tracy/src/generator/Parser.py/parseBitShiftConstant
8,121
def parseSource(source): """ Parses the given source string and adds all found functions to the library. @param header: Source text @returns: A library containing the parsed functions """ task = Task.startTask("parser", "Parsing type declarations", len(source)) library = Library() # R...
ValueError
dataset/ETHPy150Open skyostil/tracy/src/generator/Parser.py/parseSource
8,122
def __getattr__(self, attr): for replacement in settings.REPLACEMENTS: attr = attr.replace(replacement, '') attr = attr.lower() if attr == 'random': attr = self.data['randomize'][ str(random.randint(0, len(self.data['randomize']) - 1)) ] ...
KeyError
dataset/ETHPy150Open SickRage/SickRage/lib/fake_useragent/fake.py/UserAgent.__getattr__
8,123
def queryset(self, request, queryset): try: return queryset.filter(**self.used_parameters) except __HOLE__ as e: raise IncorrectLookupParameters(e)
ValidationError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/admin/filters.py/FieldListFilter.queryset
8,124
def search_ip(request): if request.method == "POST": form = IpSearchForm(request.POST) try: if form.is_valid(): ip_type = form.cleaned_data['ip_type'] search_ip = form.cleaned_data['search_ip'] try: if ip_type == '4': ...
ValidationError
dataset/ETHPy150Open rtucker-mozilla/mozilla_inventory/core/views.py/search_ip
8,125
def _set_submission_time_to_query(query, request): query[SUBMISSION_TIME] = {} try: if request.GET.get('start'): query[SUBMISSION_TIME]['$gte'] = format_date_for_mongo( request.GET['start']) if request.GET.get('end'): query[SUBMISSION_TIME]['$lte'] = forma...
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/_set_submission_time_to_query
8,126
def dd_for_params(id_string, owner, request): start = end = None dd = DataDictionary.objects.get(id_string__exact=id_string, user=owner) if request.GET.get('start'): try: start = encode(request.GET['start']) except __HOLE__: # bad f...
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/dd_for_params
8,127
def charts(request, username, id_string): xform, is_owner, can_edit, can_view = get_xform_and_perms( username, id_string, request) # no access if not (xform.shared_data or can_view or request.session.get('public_link') == xform.uuid): return HttpResponseForbidden(_(u'Not shared....
ValueError
dataset/ETHPy150Open kobotoolbox/kobocat/onadata/apps/viewer/views.py/charts
8,128
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'): """ Similar to smart_unicode, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case fi...
UnicodeDecodeError
dataset/ETHPy150Open dcramer/sentry-old/sentry/utils/encoding.py/force_unicode
8,129
def _HashFile(self, fd): """Look for the required hashes in the file.""" hashes = fd.Get(fd.Schema.HASH) if hashes: found_all = True for fingerprint_type, hash_types in self.HASH_TYPES.iteritems(): for hash_type in hash_types: if fingerprint_type == "pecoff": hash_t...
IOError
dataset/ETHPy150Open google/grr/grr/lib/aff4_objects/filestore.py/HashFileStore._HashFile
8,130
def load_mlcomp(name_or_id, set_="raw", mlcomp_root=None, **kwargs): """Load a datasets as downloaded from http://mlcomp.org Parameters ---------- name_or_id : the integer id or the string name metadata of the MLComp dataset to load set_ : select the portion to load: 'train', 'te...
KeyError
dataset/ETHPy150Open scikit-learn/scikit-learn/sklearn/datasets/mlcomp.py/load_mlcomp
8,131
def from_db_value(self, value, *args, **kwargs): try: return KeyValueContainer(value, separator=self.separator) except __HOLE__ as e: raise ValidationError(e)
ValueError
dataset/ETHPy150Open rewardz/django_model_helpers/model_helpers.py/KeyValueField.from_db_value
8,132
def main(): if len(sys.argv) < 3: usage() sr_path = sys.argv[1] action = sys.argv[2] if action not in ('print', 'delete', 'move'): usage() if action == 'move': if len(sys.argv) < 4: print "error: must specify where to move bad VHDs" sys.exit(1) ...
KeyError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/tools/xenserver/vdi_chain_cleanup.py/main
8,133
def __new__(mcs, name, bases, attributes): try: constructor = attributes["__new__"] except KeyError: return type.__new__(mcs, name, bases, attributes) def preparing_constructor(mcs, name, bases, attributes): try: mc...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/utils/schema.py/Prepareable.__new__
8,134
def __new__(mcs, name, bases, attrs): # Register the class as an item class attrs['__item__'] = True attrs['__item_name__'] = None # Instantiate an empty list to store the config item attribute names attributes = [] for base in reversed(bases): try: ...
TypeError
dataset/ETHPy150Open saltstack/salt/salt/utils/schema.py/BaseSchemaItemMeta.__new__
8,135
def main(args): """Runs the client, exits when done. See _CreateParser for the complete list of supported commands. Requires a $LAB_DEVICE_PROXY_URL environment variable (or --url argument) that's set to the server's URL. Args: args: List of command and arguments, e.g. ['./adb', 'install', 'foo...
ValueError
dataset/ETHPy150Open google/lab_device_proxy/lab_device_proxy_client.py/main
8,136
def get_package_info(package_name, pkginfo, pkgchk): try: return package_info[package_name] except __HOLE__: version = None pathname = None try: sadm_contents = open('/var/sadm/install/contents', 'r').read() except EnvironmentError: pass el...
KeyError
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Tool/sunc++.py/get_package_info
8,137
def add_video_from_post(form): try: name = form.get('name', '').strip() url = form.get('url', '').strip() duration = form.get('duration', '').strip() if len(name) < 1 or len(url) < 10 or len(duration) < 1 or \ int(duration) <= 0: raise ValueError...
ValueError
dataset/ETHPy150Open cn28h/mobilecloud-14-flask/week2/video/app.py/add_video_from_post
8,138
def runserver(self): """ Command to run for development environments. """ print(textwrap.dedent(""" {2} Welcome to Decanter! You're ready to go! Server running on http://{1}:{0} {2}""".format(self.port, self.hostname, '=' * 50))...
KeyboardInterrupt
dataset/ETHPy150Open gengo/decanter/decanter/decanter.py/Decanter.runserver
8,139
def status(self): try: with open(self.pidfile, 'r') as fp: pid = int(fp.read()) os.kill(pid, 0) print("Decanter is running, pidfile: {0}, process: {1}".format( self.pidfile, pid)) except (__HOLE__, IOError): print("Decanter ...
OSError
dataset/ETHPy150Open gengo/decanter/decanter/decanter.py/Decanter.status
8,140
def user_ready(username): if username.endswith(".php"): return False uh = UserHistory(username) # First, check to see if the file is fresh uh.load_if_possible() if uh.data_age() < settings.HISTORY_TTL: return uh.num_weeks() # Then, do a quick weeklist fetch to comp...
AssertionError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_ready
8,141
def ajax_user_queuepos(request, username): "Returns what number the user is in the request queue." try: return jsonify(list(LastFmUser.queue()).index(LastFmUser.by_username(username)) + 1) except (ValueError, __HOLE__): return jsonify(None) ### Graphs ###
IndexError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/ajax_user_queuepos
8,142
@referrer_limit @cache_page(60 * 15) def graph_artist(request, username, artist, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width=800 if not height: width=300 uh = UserHistory(username) uh.l...
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_artist
8,143
@referrer_limit @cache_page(60 * 15) def graph_timeline(request, username, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width = 800 if not height: height = 300 series_set = graph_timeline_data(use...
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_timeline
8,144
@referrer_limit @cache_page(60 * 15) def graph_timeline_basic(request, username, width=800, height=300): ready_or_update(username) width = int(width) height = int(height) if not width: width = 1280 if not height: height = 50 series_set = graph_timeline_da...
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_timeline_basic
8,145
@referrer_limit @cache_page(60 * 15) def graph_sig1(request, username, width=300, height=100): ready_or_update(username) width = int(width) height = int(height) if not width: width = 300 if not height: height = 100 series_set = graph_timeline_data(usernam...
ValueError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/graph_sig1
8,146
def user_artists(request, username): uh = UserHistory(username) uh.load_if_possible() artists = [(sum(weeks.values()), artist) for artist, weeks in uh.artists.items()] artists.sort() artists.reverse() try: max_plays = float(artists[0][0]) except __HOLE__: max_p...
IndexError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_artists
8,147
def user_export_all_tabular(request, username, filetype): uh = UserHistory(username) uh.load_if_possible() data = [(("Week", {"bold":True}),("Artist", {"bold":True}),("Plays", {"bold":True}))] for week, artists in uh.weeks.items(): for artist, plays in artists.items(): data...
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_all_tabular
8,148
def user_export_artist_tabular(request, username, artist, filetype): uh = UserHistory(username) uh.load_if_possible() data = [(("Week", {"bold":True}),("Plays", {"bold":True}))] try: for week, plays in uh.artists[artist].items(): data.append((week, plays)) except KeyErr...
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_artist_tabular
8,149
def user_export_artist_json(request, username, artist): uh = UserHistory(username) uh.load_if_possible() try: return jsonify({"username": username, "artist":artist, "weeks":uh.artists[artist]}) except __HOLE__: raise Http404("No such artist.")
KeyError
dataset/ETHPy150Open andrewgodwin/lastgraph/lastgui/views.py/user_export_artist_json
8,150
def symb_forward(self, symb_input): # If no `wrt` is passed, we use the referenced module's graph and go # through it backwards, using all its parameters etc. if self.wrt is None: try: start = self.modules[0]._last_symb_inp[self._mode] end = self.mod...
KeyError
dataset/ETHPy150Open lucasb-eyer/DeepFried2/DeepFried2/containers/Backward.py/Backward.symb_forward
8,151
def __call__(self, parser, namespace, value, option_string=None): try: if self.settings.check_for_updates: common.check_for_updates(self.settings.package_name, self.api.check_versions()['cctrl']) except __HOLE__: pass ...
KeyError
dataset/ETHPy150Open cloudControl/cctrl/cctrl/app_commands.py/list_action.__call__
8,152
def setup_cli(settings): api = common.init_api(settings) try: app = AppController(api, settings) parse_cmdline(app, settings) except __HOLE__: pass finally: common.shutdown(api, settings)
KeyboardInterrupt
dataset/ETHPy150Open cloudControl/cctrl/cctrl/app_commands.py/setup_cli
8,153
def run_only_if_psutil_is_available(func): try: import psutil except __HOLE__: psutil = None return run_only(func, lambda: psutil is not None)
ImportError
dataset/ETHPy150Open BrightcoveOS/Diamond/src/collectors/processresources/test/testprocessresources.py/run_only_if_psutil_is_available
8,154
def test_message_from_kwargs(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(message='test', data={}) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'te...
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_message_from_kwargs
8,155
def test_explicit_message_on_exception_event(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(data={'message': 'foobar'}) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(ev...
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_explicit_message_on_exception_event
8,156
def test_exception_event(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException() self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'ValueError: foo') sel...
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_exception_event
8,157
def test_exception_event_true_exc_info(self): try: raise ValueError('foo') except __HOLE__: self.client.captureException(exc_info=True) self.assertEquals(len(self.client.events), 1) event = self.client.events.pop(0) self.assertEquals(event['message'], 'Va...
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_exception_event_true_exc_info
8,158
def test_context(self): self.client.context.merge({ 'tags': {'foo': 'bar'}, }) try: raise ValueError('foo') except __HOLE__: self.client.captureException() else: self.fail('Exception should have been raised') assert len(sel...
ValueError
dataset/ETHPy150Open getsentry/raven-python/tests/base/tests.py/ClientTest.test_context
8,159
def new_opensslconf(self): """ Create new openssl.conf configuration file. """ directory = os.path.dirname(self.configfile) for section in self.__class__.DEFAULT.keys(): self.config.add_section(section) print "[{}]".format(section) for option ...
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/Config.new_opensslconf
8,160
def parse_opensslconf(self): """ Parse the openssl.conf file to find relevant paths. """ self.config.read(self.configfile) configuration = {} for section in self.__class__.DEFAULT.keys(): for option in self.__class__.DEFAULT[section].keys(): ra...
KeyError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/Config.parse_opensslconf
8,161
def fingerprint(filename): """ Return the sha256 fingerprint of a certificate `filename`. Can only be run on trusted/signed certificates. Equivalent to: openssl x509 -sha256 -in ./runtime.csr -noout -fingerprint """ log = subprocess.Popen(["openssl", "x509", "-sha...
IndexError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/fingerprint
8,162
def new_runtime(conf, name, nodeid=None): """ Create new runtime certificate. Return name of certificate signing request file. Equivalent of: mkdir -p $new_certs_dir openssl req -config $OPENSSL_CONF -new \ -newkey rsa:2048 -nodes \ -out $new_certs_dir/runtime.cs...
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/new_runtime
8,163
def new_domain(conf): """ Create new domain Certificate Authority Cert. Return path and filename of new domain certificate. Equivalent of: echo "Creating a certificate authority for a new domain." mkdir -p -m 700 $private_dir mkdir -p -m 700 $crl_dir chmod 700 $private_dir #Because mkdi...
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/new_domain
8,164
def sign_req(conf, req, name): """ Sign a certificate request. Conf is a Config object with a loaded openssl.conf configuration. Req is the name of a Certificate Signing Request in $new_certs_dir. Equivalent of: mkdir -p $certs openssl ca -in $new_certs_dir/$SIGN_REQ -config ...
OSError
dataset/ETHPy150Open EricssonResearch/calvin-base/calvin/utilities/certificate.py/sign_req
8,165
def _request(self, command, json=True, opcode_name='command', fetch_list=False, **kwargs): kwargs.update({ 'apiKey': self.key, opcode_name: command, }) if json: kwargs['response'] = 'json' if 'page' in kwargs or fetch_list: ...
ValueError
dataset/ETHPy150Open exoscale/cs/cs.py/CloudStack._request
8,166
def read_config(ini_group=None): if not ini_group: ini_group = os.environ.get('CLOUDSTACK_REGION', 'cloudstack') # Try env vars first os.environ.setdefault('CLOUDSTACK_METHOD', 'get') os.environ.setdefault('CLOUDSTACK_TIMEOUT', '10') keys = ['endpoint', 'key', 'secret', 'method', 'timeout'] ...
AttributeError
dataset/ETHPy150Open exoscale/cs/cs.py/read_config
8,167
def main(): parser = argparse.ArgumentParser(description='Cloustack client.') parser.add_argument('--region', metavar='REGION', help='Cloudstack region in ~/.cloudstack.ini', default=os.environ.get('CLOUDSTACK_REGION', ...
KeyboardInterrupt
dataset/ETHPy150Open exoscale/cs/cs.py/main
8,168
def test_noniterable(self): val = self.arr while True: try: val = val[0] except __HOLE__: break method = self.model.objects.create self.assertRaises(ValidationError, method, arr=val)
TypeError
dataset/ETHPy150Open ecometrica/django-dbarray/dbarray/tests/tests.py/ArrayTestMixin.test_noniterable
8,169
def flush(self): """Flushes the stream.""" try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (AttributeError, __HOLE__): pass else: stream.flush()
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/_cplogging.py/WSGIErrorHandler.flush
8,170
def emit(self, record): """Emit a record.""" try: stream = cherrypy.serving.request.wsgi_environ.get('wsgi.errors') except (__HOLE__, KeyError): pass else: try: msg = self.format(record) fs = "%s\n" impor...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/_cplogging.py/WSGIErrorHandler.emit
8,171
def memoize(func): saved = {} def call(*args): try: return saved[args] except KeyError: res = func(*args) saved[args] = res return res except __HOLE__: # Unhashable argument return func(*args) call.__name__ = fun...
TypeError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_decorators.py/memoize
8,172
def run(self, result): try: raise RuntimeError("error that occurs outside of a test") except __HOLE__: log.err(failure.Failure())
RuntimeError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/trial/test/test_runner.py/BreakingSuite.run
8,173
def testPythonSetupD(self): try: __import__('setuptools') except __HOLE__: raise testhelp.SkipTestException('Missing python-setuptools package') recipestr = r""" class Test(PackageRecipe): name = 'test' version = '0' clearBuildReqs() def setup(r): ...
ImportError
dataset/ETHPy150Open sassoftware/conary/conary_test/cvctest/buildtest/buildtest.py/PythonSetupTest.testPythonSetupD
8,174
def testPythonSetupNonPure(self): try: __import__('setuptools') except __HOLE__: raise testhelp.SkipTestException('Missing python-setuptools package') recipestr = r""" class Test(PackageRecipe): name = 'test' version = '0' clearBuildReqs() def setup(r...
ImportError
dataset/ETHPy150Open sassoftware/conary/conary_test/cvctest/buildtest/buildtest.py/TestMakeFIFO.testPythonSetupNonPure
8,175
def _str_datetime_now(self, x=None): """Return datetime string for use with time attributes Handling depends on input: 'now' - returns datetime for now number - assume datetime values, generate string other - no change, return same value """ if...
TypeError
dataset/ETHPy150Open resync/resync/resync/resource_container.py/ResourceContainer._str_datetime_now
8,176
def status(self): status = { # summary = 'notfound', 'sleeping', 'on', or 'recording' 'summary': 'notfound', 'raw': {} } camActive = True # loop through different status URLs for cmd in self.statusMatrix: # stop sending requests i...
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.status
8,177
def image(self): try: # use OpenCV to capture a frame and store it in a numpy array stream = cv2.VideoCapture(self._previewURL()) success, numpyImage = stream.read() if success: # use Image to save the image to a file, but actually save it ...
IOError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.image
8,178
def command(self, command, value=None): func_str = 'GoProHero.command({}, {})'.format(command, value) if command in self.commandMaxtrix: args = self.commandMaxtrix[command] # accept both None and '' for commands without a value if value == '': value =...
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.command
8,179
def test(self, url, toHex=True): try: url = 'http://{}/{}'.format(self._ip, url) print(url) response = urlopen( url, timeout=self.timeout).read() if toHex: response = response.encode('hex') print(response) exc...
HTTPError
dataset/ETHPy150Open joshvillbrandt/goprohero/goprohero/GoProHero.py/GoProHero.test
8,180
def __init__(self, connection): QTabWidget.__init__(self) self.connection = connection self.setupUi(self) self.tableProcessList.verticalHeader().hide() cur = self.connection.cursor() cur.execute("SHOW TABLES IN information_schema LIKE 'PROCESSLIST'") self.proce...
ValueError
dataset/ETHPy150Open mtorromeo/sqlantaresia/sqlantaresia/ProcessListTab.py/ProcessListTab.__init__
8,181
@conserve_mpmath_dps def test_lambdify(): mpmath.mp.dps = 16 sin02 = mpmath.mpf("0.198669330795061215459412627") f = lambdify(x, sin(x), "numpy") prec = 1e-15 assert -prec < f(0.2) - sin02 < prec try: f(x) # if this succeeds, it can't be a numpy function assert False except ...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/external/tests/test_numpy.py/test_lambdify
8,182
@extensionclassmethod(Observable, alias=["from_", "from_list"]) def from_iterable(cls, iterable, scheduler=None): """Converts an array to an observable sequence, using an optional scheduler to enumerate the array. 1 - res = rx.Observable.from_iterable([1,2,3]) 2 - res = rx.Observable.from_iterable([1,2...
StopIteration
dataset/ETHPy150Open ReactiveX/RxPY/rx/linq/observable/fromiterable.py/from_iterable
8,183
def as_tuple(x, N, t=None): """ Coerce a value to a tuple of given length (and possibly given type). Parameters ---------- x : value or iterable N : integer length of the desired tuple t : type, optional required type for all elements Returns ------- tuple ...
TypeError
dataset/ETHPy150Open Lasagne/Lasagne/lasagne/utils.py/as_tuple
8,184
def onDeleteBtn(self, event): """ :param event: :return: """ self.checkIfEditing() try: if self.selectedObject: if len(self.selectedObject) > 1: length = len(self.selectedObject) msg = GMD.GenericMessag...
TypeError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/controller/frmAddPoints.py/AddPoints.onDeleteBtn
8,185
def onSelected(self, event): """ :param event: :return: """ obj = event.GetEventObject() object = obj.innerList[obj.FocusedItem] object = self.olv.GetSelectedObjects() try: if len(object) > 1: self.selectedObject = object ...
TypeError
dataset/ETHPy150Open ODM2/ODMToolsPython/odmtools/controller/frmAddPoints.py/AddPoints.onSelected
8,186
def get_view(endpoint): """Returns the view for the endpoint. It will cache both positive and negative hits, so never pass untrusted values to it. If a view does not exist, `None` is returned. """ view = _resolved_views.get(endpoint) if view is not None: return view try: vi...
AttributeError
dataset/ETHPy150Open mitsuhiko/solace/solace/application.py/get_view
8,187
def inject_lang_code(request, endpoint, values): """Returns a dict with the values for the given endpoint. You must not alter the dict because it might be shared. If the given endpoint does not exist `None` is returned. """ rv = values if 'lang_code' not in rv: try: if requ...
KeyError
dataset/ETHPy150Open mitsuhiko/solace/solace/application.py/inject_lang_code
8,188
def _set_lang(self, gettext): lang = request.GET['lang'] try: set_lang(lang) except (LanguageError, __HOLE__), e: resp_unicode = gettext('Could not set language to "%(lang)s"') % {'lang': lang} else: session['lang'] = lang session.save() ...
IOError
dataset/ETHPy150Open Pylons/pylons/tests/test_webapps/filestotest/controller_sample.py/SampleController._set_lang
8,189
def emit(self, record): """Emit a record. This implementation is based on the implementation of StreamHandler.emit(). Args: record: A Python logging.LogRecord object. """ try: if features.IsEnabled("LogServiceWriteRecord"): logservice.write_record(self._AppLogsLevel(record....
SystemExit
dataset/ETHPy150Open GoogleCloudPlatform/python-compat-runtime/appengine-compat/exported_appengine_sdk/google/appengine/api/app_logging.py/AppLogsHandler.emit
8,190
def test_change_attr(self): class Foo(object): def __init__(self): self.foo = 1 obj = Foo() self.assertEqual(obj.foo, 1) with self.changeAttr(obj, 'foo', 2): self.assertEqual(obj.foo, 2) self.assertEqual(obj.foo, 1) # Check that the...
ValueError
dataset/ETHPy150Open cjerdonek/open-rcv/openrcv/test/utiltest/test_helpers.py/UnitCaseTest.test_change_attr
8,191
def __cmp__(self,other): # only works for equal result = -1 try: result = cmp(self.name,other.name) or \ cmp(self.__class__, other.__class__) except __HOLE__: pass return result #-------------------------------------------------------...
AttributeError
dataset/ETHPy150Open scipy/scipy/scipy/weave/c_spec.py/common_base_converter.__cmp__
8,192
def _run_command_compare_to_string(self, command, exit_status, stdout_text=None, stderr_text=None): """ Compares stdout from the CLI to the given string """ try: main.parse_and_validate_commands(command) except __HOLE__ as e:...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/BaseMainCase._run_command_compare_to_string
8,193
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) def test_hosts_on_cli_overrides_topology(self, unused_mock_load): try: main.main(['--hosts', 'master,slave1', 'topology', 'show']) except __HOLE__ as e: self.assertEqual(e.code, 0) self.assertDe...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_hosts_on_cli_overrides_topology
8,194
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) @patch('prestoadmin.main.getpass.getpass') def test_initial_password(self, pass_mock, unused_mock_load): try: main.parse_and_validate_commands(['-I', 'topology', 'show']) except __HOLE__ as e: self.a...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_initial_password
8,195
@patch('prestoadmin.main.load_config', side_effect=mock_load_topology()) def test_env_vars_persisted(self, unused_mock_load): try: main.main(['topology', 'show']) except __HOLE__ as e: self.assertEqual(e.code, 0) self.assertDefaultHosts()
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_env_vars_persisted
8,196
@patch('prestoadmin.main.load_config', side_effect=mock_empty_topology()) def test_topology_defaults_override_fabric_defaults( self, unused_mock_load): self.remove_runs_once_flag(topology.show) try: main.main(['topology', 'show']) except __HOLE__ as e: sel...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_topology_defaults_override_fabric_defaults
8,197
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_has_args_expecting_none(self, crawl_mock, crawl_mock_main): def task(): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task stat...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_has_args_expecting_none
8,198
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_too_few_args(self, crawl_mock, crawl_mock_main): def task(arg1): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task state.env.n...
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_few_args
8,199
@patch('prestoadmin.main.crawl') @patch('prestoadmin.fabric_patches.crawl') def test_too_many_args(self, crawl_mock, crawl_mock_main): def task(arg1): """This is my task""" pass crawl_mock.return_value = task crawl_mock_main.return_value = task state.env....
SystemExit
dataset/ETHPy150Open prestodb/presto-admin/tests/unit/test_main.py/TestMain.test_too_many_args