Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
6,200
def _start_application(self, application, port): # Note: No significant application logic should be executed before this point. The call to application.listen() # will raise an exception if another process is using the same port. We rely on this exception to force us to # exit if there are any p...
OSError
dataset/ETHPy150Open box/ClusterRunner/app/subcommands/service_subcommand.py/ServiceSubcommand._start_application
6,201
def _write_pid_file(self, filename): fs.write_file(str(os.getpid()), filename) def remove_pid_file(): try: os.remove(filename) except __HOLE__: pass UnhandledExceptionHandler.singleton().add_teardown_callback(remove_pid_file)
OSError
dataset/ETHPy150Open box/ClusterRunner/app/subcommands/service_subcommand.py/ServiceSubcommand._write_pid_file
6,202
def create_apikey_model(user_model): """ Generate ApiKey model class and connect it with :user_model:. ApiKey is generated with relationship to user model class :user_model: as a One-to-One relationship with a backreference. ApiKey is set up to be auto-generated when a new :user_model: is created. ...
ValueError
dataset/ETHPy150Open ramses-tech/nefertari/nefertari/authentication/models.py/create_apikey_model
6,203
def __init__(self, command, input_pipe=None): """ Initializes a InputPipeProcessWrapper instance. :param command: a subprocess.Popen instance with stdin=input_pipe and stdout=subprocess.PIPE. Alternatively, just its args argument as a convenience....
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/InputPipeProcessWrapper.__init__
6,204
def _abort(self): """ Call _finish, but eat the exception (if any). """ try: self._finish() except __HOLE__: raise except BaseException: pass
KeyboardInterrupt
dataset/ETHPy150Open spotify/luigi/luigi/format.py/InputPipeProcessWrapper._abort
6,205
def __getattr__(self, name): if name in ['_process', '_input_pipe']: raise AttributeError(name) try: return getattr(self._process.stdout, name) except __HOLE__: return getattr(self._input_pipe, name)
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/InputPipeProcessWrapper.__getattr__
6,206
def __getattr__(self, name): if name in ['_process', '_output_pipe']: raise AttributeError(name) try: return getattr(self._process.stdin, name) except __HOLE__: return getattr(self._output_pipe, name)
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/OutputPipeProcessWrapper.__getattr__
6,207
def __init__(self, stream, *args, **kwargs): self._stream = stream try: super(BaseWrapper, self).__init__(stream, *args, **kwargs) except __HOLE__: pass
TypeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/BaseWrapper.__init__
6,208
def __init__(self, *args, **kwargs): self.args = args try: self.input = args[0].input except AttributeError: pass try: self.output = args[-1].output except __HOLE__: pass if not kwargs.get('check_consistency', True): ...
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/ChainFormat.__init__
6,209
def __del__(self, *args): # io.TextIOWrapper close the file on __del__, let the underlying file decide if not self.closed and self.writable(): super(TextWrapper, self).flush() try: self._stream.__del__(*args) except __HOLE__: pass
AttributeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/TextWrapper.__del__
6,210
def __init__(self, stream, *args, **kwargs): self._stream = stream try: super(TextWrapper, self).__init__(stream, *args, **kwargs) except __HOLE__: pass
TypeError
dataset/ETHPy150Open spotify/luigi/luigi/format.py/TextWrapper.__init__
6,211
def validate_fields(self, bundle, request=None): errors = [] for field in self.validated_fields[request.method]: validation_func = getattr(self, '%s_is_valid' % field) try: validation_func(bundle.data.get(field, None), bundle, request) except __HOLE__,...
ValidationError
dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastytools/tastytools/validation.py/FieldsValidation.validate_fields
6,212
@staticmethod def uri_to_pk(uri): if uri is None: return None # convert everything to lists multiple = not isinstance(uri, basestring) uris = uri if multiple else [uri] # handle all passed URIs converted = [] for one_uri in uris: try:...
ValueError
dataset/ETHPy150Open mozilla/inventory/vendor-local/src/django-tastytools/tastytools/validation.py/FieldsValidation.uri_to_pk
6,213
def _get_stream_parameters(kind, device, channels, dtype, latency, samplerate): """Generate PaStreamParameters struct.""" if device is None: if kind == 'input': device = _pa.Pa_GetDefaultInputDevice() elif kind == 'output': device = _pa.Pa_GetDefaultOutputDevice() in...
KeyError
dataset/ETHPy150Open bastibe/PySoundCard/pysoundcard.py/_get_stream_parameters
6,214
def _split(value): """Split input/output value into two values.""" if isinstance(value, str): # iterable, but not meant for splitting return value, value try: invalue, outvalue = value except TypeError: invalue = outvalue = value except __HOLE__: raise ValueEr...
ValueError
dataset/ETHPy150Open bastibe/PySoundCard/pysoundcard.py/_split
6,215
def DoAttributes(self, c, fsm): # m try: while 1: n = int(fsm.pop()) self.screen.set_attribute(n) except __HOLE__: pass
IndexError
dataset/ETHPy150Open kdart/pycopia/QA/pycopia/ANSIterm.py/ANSITerminal.DoAttributes
6,216
@staticmethod def from_string(data_string): """Deserializes a token from a string like one returned by `to_string()`.""" if not len(data_string): raise ValueError("Invalid parameter string.") params = parse_qs(data_string, keep_blank_values=False) if not len(pa...
KeyError
dataset/ETHPy150Open project-fondue/python-yql/yql/__init__.py/YahooToken.from_string
6,217
def validate_statementId(req_dict): if 'statementId' in req_dict['params'] and 'voidedStatementId' in req_dict['params']: err_msg = "Cannot have both statementId and voidedStatementId in a GET request" raise ParamError(err_msg) elif 'statementId' in req_dict['params']: statementId = req_...
ValueError
dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_validate.py/validate_statementId
6,218
@auth def activities_get(req_dict): rogueparams = set(req_dict['params']) - set(["activityId"]) if rogueparams: raise ParamError("The get activities request contained unexpected parameters: %s" % ", ".join(rogueparams)) try: activity_id = req_dict['params']['activityId'] except __HOLE__...
KeyError
dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_validate.py/activities_get
6,219
@auth def agents_get(req_dict): rogueparams = set(req_dict['params']) - set(["agent"]) if rogueparams: raise ParamError("The get agent request contained unexpected parameters: %s" % ", ".join(rogueparams)) try: req_dict['params']['agent'] except __HOLE__: err_msg = "Error -- ag...
KeyError
dataset/ETHPy150Open adlnet/ADL_LRS/lrs/utils/req_validate.py/agents_get
6,220
def __getitem__(self, name): name = self._to_colons[name] try: return self._unknowns[name] except __HOLE__: return self._params[name]
KeyError
dataset/ETHPy150Open OpenMDAO/OpenMDAO/openmdao/components/exec_comp.py/_UPDict.__getitem__
6,221
def get(self, key, default=None, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock.reader(): exp = self._expire_info.get(key) if exp is None: return default elif exp > time.time(): t...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/cache/backends/locmem.py/LocMemCache.get
6,222
def has_key(self, key, version=None): key = self.make_key(key, version=version) self.validate_key(key) with self._lock.reader(): exp = self._expire_info.get(key) if exp is None: return False elif exp > time.time(): return True ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/cache/backends/locmem.py/LocMemCache.has_key
6,223
def _delete(self, key): try: del self._cache[key] except __HOLE__: pass try: del self._expire_info[key] except KeyError: pass
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.4/django/core/cache/backends/locmem.py/LocMemCache._delete
6,224
def script(): """ Execute the program as a script. Set up logging, invoke main() using the user-provided arguments and handle any exception raised. """ # Setup logging import logging logging.basicConfig( format="%(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S", ...
SystemExit
dataset/ETHPy150Open dvarrazzo/pgxnclient/pgxnclient/cli.py/script
6,225
def setup_server(): try: import routes except __HOLE__: raise nose.SkipTest('Install routes to test RoutesDispatcher code') class Dummy: def index(self): return "I said good day!" class City: def __in...
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/cherrypy/cherrypy/test/test_routes.py/RoutesDispatchTest.setup_server
6,226
def __init__(self, first, last=None): try: first_num = WEEKDAYS.index(first.lower()) except __HOLE__: raise ValueError('Invalid weekday name "%s"' % first) if last: try: last_num = WEEKDAYS.index(last.lower()) except ValueError: ...
ValueError
dataset/ETHPy150Open agronholm/apscheduler/apscheduler/triggers/cron/expressions.py/WeekdayRangeExpression.__init__
6,227
def __init__(self, option_name, weekday_name): try: self.option_num = self.options.index(option_name.lower()) except ValueError: raise ValueError('Invalid weekday position "%s"' % option_name) try: self.weekday = WEEKDAYS.index(weekday_name.lower()) e...
ValueError
dataset/ETHPy150Open agronholm/apscheduler/apscheduler/triggers/cron/expressions.py/WeekdayPositionExpression.__init__
6,228
def from_inet_ptoi(bgp_id): """Convert an IPv4 address string format to a four byte long. """ four_byte_id = None try: packed_byte = socket.inet_pton(socket.AF_INET, bgp_id) four_byte_id = int(packed_byte.encode('hex'), 16) except __HOLE__: LOG.debug('Invalid bgp id given for...
ValueError
dataset/ETHPy150Open osrg/ryu/ryu/services/protocols/bgp/utils/bgp.py/from_inet_ptoi
6,229
def get_sort_options(expressions=None, match_scorer=None, limit=1000): """A function to handle the sort expression API differences in 1.6.4 vs. 1.6.5+. An example of usage (NOTE: Do NOT put limit SortExpression or MatchScorer): expr_list = [ search.SortExpression(expression='author', default_value='', ...
AttributeError
dataset/ETHPy150Open GoogleCloudPlatform/appengine-search-python-java/product_search_python/sortoptions.py/get_sort_options
6,230
def get_command_handler(self, command): """ Parsing command and returning appropriate handler. :param command: command :return: command_handler """ try: command_handler = getattr(self, "command_{}".format(command)) except __HOLE__: raise Routerspl...
AttributeError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/BaseInterpreter.get_command_handler
6,231
def start(self): """ Routersploit main entry point. Starting interpreter loop. """ print(self.banner) while True: try: command, args = self.parse_line(raw_input(self.prompt)) if not command: continue command_handler...
KeyboardInterrupt
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/BaseInterpreter.start
6,232
def complete(self, text, state): """Return the next possible completion for 'text'. If a command has not been entered, then complete against command list. Otherwise try to call complete_<command> to get list of completions. """ if state == 0: original_line = readline...
IndexError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/BaseInterpreter.complete
6,233
def load_modules(self): self.main_modules_dirs = [module for module in os.listdir(self.modules_directory) if not module.startswith("__")] self.modules = [] self.modules_with_errors = {} for root, dirs, files in os.walk(self.modules_directory): _, package, root = root.rpartit...
ImportError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/RoutersploitInterpreter.load_modules
6,234
@property def prompt(self): """ Returns prompt string based on current_module attribute. Adding module prefix (module.name) if current_module attribute is set. :return: prompt string with appropriate module prefix. """ if self.current_module: try: ...
KeyError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/RoutersploitInterpreter.prompt
6,235
def command_use(self, module_path, *args, **kwargs): module_path = utils.pythonize_path(module_path) module_path = '.'.join(('routersploit', 'modules', module_path)) # module_path, _, exploit_name = module_path.rpartition('.') try: module = importlib.import_module(module_path...
ImportError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/RoutersploitInterpreter.command_use
6,236
@utils.module_required def get_opts(self, *args): """ Generator returning module's Option attributes (option_name, option_value, option_description) :param args: Option names :return: """ for opt_key in args: try: opt_description = self.current_mo...
KeyError
dataset/ETHPy150Open reverse-shell/routersploit/routersploit/interpreter.py/RoutersploitInterpreter.get_opts
6,237
def test_dnn_tag(): """ Test that if cudnn isn't avail we crash and that if it is avail, we use it. """ x = T.ftensor4() old = theano.config.on_opt_error theano.config.on_opt_error = "raise" sio = StringIO() handler = logging.StreamHandler(sio) logging.getLogger('theano.compile.test...
AssertionError
dataset/ETHPy150Open rizar/attention-lvcsr/libs/Theano/theano/sandbox/gpuarray/tests/test_dnn.py/test_dnn_tag
6,238
def add_edge(self, u, v, key=None, attr_dict=None, **attr): """Add an edge between u and v. The nodes u and v will be automatically added if they are not already in the graph. Edge attributes can be specified with keywords or by providing a dictionary with key/value pairs. See...
AttributeError
dataset/ETHPy150Open networkx/networkx/networkx/classes/multigraph.py/MultiGraph.add_edge
6,239
def add_edges_from(self, ebunch, attr_dict=None, **attr): """Add all the edges in ebunch. Parameters ---------- ebunch : container of edges Each edge given in the container will be added to the graph. The edges can be: - 2-tuples (u,v) or ...
AttributeError
dataset/ETHPy150Open networkx/networkx/networkx/classes/multigraph.py/MultiGraph.add_edges_from
6,240
def has_edge(self, u, v, key=None): """Return True if the graph has an edge between nodes u and v. Parameters ---------- u, v : nodes Nodes can be, for example, strings or numbers. key : hashable identifier, optional (default=None) If specified return Tr...
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/classes/multigraph.py/MultiGraph.has_edge
6,241
def get_edge_data(self, u, v, key=None, default=None): """Return the attribute dictionary associated with edge (u,v). Parameters ---------- u, v : nodes default : any Python object (default=None) Value to return if the edge (u,v) is not found. key : hashab...
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/classes/multigraph.py/MultiGraph.get_edge_data
6,242
def number_of_edges(self, u=None, v=None): """Return the number of edges between two nodes. Parameters ---------- u, v : nodes, optional (default=all edges) If u and v are specified, return the number of edges between u and v. Otherwise return the total number of...
KeyError
dataset/ETHPy150Open networkx/networkx/networkx/classes/multigraph.py/MultiGraph.number_of_edges
6,243
def check_formfield(cls, model, opts, label, field): if getattr(cls.form, 'base_fields', None): try: cls.form.base_fields[field] except __HOLE__: raise ImproperlyConfigured("'%s.%s' refers to field '%s' that " "is missing from the form." % (cls.__name__, label...
KeyError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/admin/validation.py/check_formfield
6,244
def fetch_attr(cls, model, opts, label, field): try: return opts.get_field(field) except models.FieldDoesNotExist: pass try: return getattr(model, field) except __HOLE__: raise ImproperlyConfigured("'%s.%s' refers to '%s' that is neither a field, method or property of mod...
AttributeError
dataset/ETHPy150Open dcramer/django-compositepks/django/contrib/admin/validation.py/fetch_attr
6,245
def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: # Nod to tastypie's use of importlib. parts = val.split('.') module_path, class_name = '.'.join(parts[:-1]), parts[-1] module = importlib.import_module(module_p...
ImportError
dataset/ETHPy150Open tomchristie/flask-api/flask_api/settings.py/import_from_string
6,246
@staticmethod def get_variables_from_file(full_filename, file_encoding='utf-8'): path, filename = os.path.split(full_filename) temp_abspath = None global_dict = globals().copy() try: # add settings dir from path sys.path.insert(0, path) execfile...
IOError
dataset/ETHPy150Open guilhermechapiewski/simple-db-migrate/simple_db_migrate/helpers.py/Utils.get_variables_from_file
6,247
def getattr(obj, name, *default): """a version of getattr() that supports NetProxies""" if len(default) > 1: raise TypeError("getattr expected at most 3 arguments, got %d" % (2 + len(default),)) if orig_isinstance(obj, NetProxy): try: return obj.__getattr__(name) e...
AttributeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/Rpyc/Utils/Builtins.py/getattr
6,248
def hasattr(obj, name): """a version of hasattr() that supports NetProxies""" try: getattr(obj, name) except __HOLE__: return False else: return True
AttributeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/Rpyc/Utils/Builtins.py/hasattr
6,249
def _get_fullname(cls): """ a heuristic to generate a unique identifier for classes, that is not machine-, platform-, or runtime-dependent """ if orig_isinstance(cls, NetProxy): modules = _get_conn(cls).modules.sys.modules else: modules = sys.modules try: f...
KeyError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/Rpyc/Utils/Builtins.py/_get_fullname
6,250
def isinstance(obj, bases): """a version of isinstance that supports NetProxies""" try: cls = obj.__getattr__("__class__") except __HOLE__: try: cls = obj.__class__ except AttributeError: cls = orig_type(obj) return issubclass(cls, bases)
AttributeError
dataset/ETHPy150Open deanhiller/databus/webapp/play1.3.x/python/Lib/site-packages/Rpyc/Utils/Builtins.py/isinstance
6,251
def stop(self): try: if self.process: #disconnect the subprocess try: result = self.process.poll() if result is None: self.process.kill() except __HOLE__: pass ...
OSError
dataset/ETHPy150Open ufora/ufora/ufora/core/SubprocessRunner.py/SubprocessRunner.stop
6,252
def _fill_result_cache(self): """ Fill the result cache with all results. """ idx = 0 try: while True: idx += 1000 self._fill_result_cache_to_idx(idx) except __HOLE__: pass self._count = len(self._result_ca...
StopIteration
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet._fill_result_cache
6,253
def _fill_result_cache_to_idx(self, idx): self._execute_query() if self._result_idx is None: self._result_idx = -1 qty = idx - self._result_idx if qty < 1: return else: for idx in range(qty): self._result_idx += 1 ...
IndexError
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet._fill_result_cache_to_idx
6,254
def __iter__(self): self._execute_query() idx = 0 while True: if len(self._result_cache) <= idx: try: self._result_cache.append(next(self._result_generator)) except __HOLE__: break instance = self._...
StopIteration
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.__iter__
6,255
def __getitem__(self, s): self._execute_query() if isinstance(s, slice): start = s.start if s.start else 0 # calculate the amount of results that need to be loaded end = s.stop if start < 0 or s.stop is None or s.stop < 0: end = self.coun...
StopIteration
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.__getitem__
6,256
def first(self): try: return six.next(iter(self)) except __HOLE__: return None
StopIteration
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.first
6,257
def iff(self, *args, **kwargs): """Adds IF statements to queryset""" if len([x for x in kwargs.values() if x is None]): raise CQLEngineException("None values on iff are not allowed") clone = copy.deepcopy(self) for operator in args: if not isinstance(operator, Co...
KeyError
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.iff
6,258
def filter(self, *args, **kwargs): """ Adds WHERE arguments to the queryset, returning a new queryset See :ref:`retrieving-objects-with-filters` Returns a QuerySet filtered on the keyword arguments """ # add arguments to the where clause filters if len([x for x ...
KeyError
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.filter
6,259
def get(self, *args, **kwargs): """ Returns a single instance matching this query, optionally with additional filter kwargs. See :ref:`retrieving-objects-with-filters` Returns a single object matching the QuerySet. .. code-block:: python user = User.get(id=1) ...
IndexError
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/AbstractQuerySet.get
6,260
def __getattr__(self, item): try: return self[item] except __HOLE__: raise AttributeError
KeyError
dataset/ETHPy150Open datastax/python-driver/cassandra/cqlengine/query.py/ResultObject.__getattr__
6,261
def run(self, host=None, port=None, debug=None, **options): import tornado.wsgi import tornado.ioloop import tornado.httpserver import tornado.web if host is None: host = '127.0.0.1' if port is None: server_name = self.config['SERVER_NAME'] ...
ImportError
dataset/ETHPy150Open binux/pyspider/pyspider/webui/app.py/QuitableFlask.run
6,262
def update(self): """Called each display loop to update the slide positions.""" super(MoveIn, self).update() if not self.active_transition: return # figure out which direction is non-zero and move it towards zero if self.slide_b_current_x: self.slide_b_c...
AttributeError
dataset/ETHPy150Open missionpinball/mpf/mpf/media_controller/transitions/move_in.py/MoveIn.update
6,263
def parseEventRange(self, trace, eventRange): """ Convert an event range description string into a concrete event range for a trace. The string may be an integral event number or a frame number preceded with '#', or a range with ":" as the separator between start and end events. @param trace ...
ValueError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Analyzer.py/InteractiveAnalyzer.parseEventRange
6,264
def parseBoolean(self, boolean): """ Parse a boolean descriptor and return True or False accordingly. """ try: return bool(int(boolean)) except __HOLE__: if boolean.lower() in ["yes", "on", "true", "enabled"]: return True return False
ValueError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Analyzer.py/InteractiveAnalyzer.parseBoolean
6,265
def lookupFunction(self, event): """ Fetch a function from the project's library for an event. @param event: Event for which the function should be sought @returns a Function or None if it wasn't found """ try: library = self.project.targets["code"].library except __HOLE__: ...
KeyError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Analyzer.py/InteractiveAnalyzer.lookupFunction
6,266
def run(self): while not self.done: try: self.colorizer.setColor(0xff, 0xff, 0xff) try: sys.stdout.write("%s> " % self.project.config.name) except __HOLE__: sys.stdout.write("%s> " % "(no project)") self.colorizer.resetColor() command = raw_input() ...
AttributeError
dataset/ETHPy150Open skyostil/tracy/src/analyzer/Analyzer.py/InteractiveAnalyzer.run
6,267
def __unicode__(self): # for translated errors we only return the message if self.translated: return self.message # otherwise attach some stuff location = 'line %d' % self.lineno name = self.filename or self.name if name: location = 'File "%s", %s...
IndexError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/jinja2-2.6/jinja2/exceptions.py/TemplateSyntaxError.__unicode__
6,268
def omz_env(): try: import workflow return 'Editorial' except ImportError: try: import scene return 'Pythonista' except __HOLE__: return None
ImportError
dataset/ETHPy150Open cclauss/Ten-lines-or-less/omz_env.py/omz_env
6,269
def request(self, method, url, body=None, headers=None): self._method = method self._url = url try: self._body = body.read() except __HOLE__: self._body = body if headers is None: headers = [] elif hasattr(headers, 'items'): headers = headers.items() self.headers = he...
AttributeError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/dist/httplib.py/HTTPConnection.request
6,270
def getresponse(self): if self.port and self.port != self.default_port: host = '%s:%s' % (self.host, self.port) else: host = self.host if not self._url.startswith(self.protocol): url = '%s://%s%s' % (self.protocol, host, self._url) else: url = self._url headers = dict(sel...
KeyError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/dist/httplib.py/HTTPConnection.getresponse
6,271
def get_json(self, force=False, silent=False, cache=True): """Parses the incoming JSON request data and returns it. If parsing fails the :meth:`on_json_loading_failed` method on the request object will be invoked. By default this function will only load the json data if the mimetype is...
ValueError
dataset/ETHPy150Open pallets/flask/flask/wrappers.py/Request.get_json
6,272
def key_Return(self, entry, event): text = self.getText() # Figure out if that Return meant "next line" or "execute." try: c = code.compile_command(text) except SyntaxError, e: # This could conceivably piss you off if the client's python # doesn't acce...
ValueError
dataset/ETHPy150Open kuri65536/python-for-android/python-modules/twisted/twisted/manhole/ui/gtk2manhole.py/ConsoleInput.key_Return
6,273
def discover_post_import_hooks(group): try: import pkg_resources except __HOLE__: return for entrypoint in pkg_resources.iter_entry_points(group=group): callback = _create_import_hook_from_entrypoint(entrypoint) register_post_import_hook(callback, entrypoint.name) # Indicat...
ImportError
dataset/ETHPy150Open GrahamDumpleton/wrapt/src/wrapt/importer.py/discover_post_import_hooks
6,274
def get_biblio_for_id(self, id, provider_url_template=None, cache_enabled=True): logger.debug(u"%20s getting biblio for %s" % (self.provider_name, id)) if not provider_url_template: provider_url_template = self.biblio_url_template url = self._g...
TypeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/webpage.py/Webpage.get_biblio_for_id
6,275
def _extract_biblio(self, page, id=None): biblio_dict = {} if not page: return biblio_dict unicode_page = to_unicode_or_bust(page) try: parsed_html = lxml.html.document_fromstring(unicode_page) try: response = parsed_html.fin...
AttributeError
dataset/ETHPy150Open Impactstory/total-impact-webapp/totalimpact/providers/webpage.py/Webpage._extract_biblio
6,276
def parse_mime_type(mime_type): """Carves up a mime-type and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/xhtml;q=0.5' would get parsed into: ('application', 'xht...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/mimeparse.py/parse_mime_type
6,277
def parse_media_range(range): """Carves up a media range and returns a tuple of the (type, subtype, params) where 'params' is a dictionary of all the parameters for the media range. For example, the media range 'application/*;q=0.5' would get parsed into: ('application', '*', {'q...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/Paste-2.0.1/paste/util/mimeparse.py/parse_media_range
6,278
def get_snippets_file(): snippets_file = os.path.join(os.path.expanduser('~'), '.clf.yaml') if not os.path.isfile(snippets_file): try: f = open(snippets_file, 'w') f.close() except __HOLE__: raise OSException('Could not create {}'.format(snippets_file)) ...
OSError
dataset/ETHPy150Open ncrocfer/clf/clf/utils.py/get_snippets_file
6,279
def LoadJsonFile(self, path, expand=False): """Loads a file but ignores the broken ones. Fails a test assertion if the file is not loadable. Args: path: (str) path to file. expand: (bool, default False) whether to expand as a Json template. Returns: (dict) or None if the file is in a...
ValueError
dataset/ETHPy150Open google/apis-client-generator/src/googleapis/codegen/configuration_test.py/ConfigurationTest.LoadJsonFile
6,280
def serialize(obj, fields=None, invalid=ABORT): """ Serialize a GitModel object to JSON. fields: When None, serilizes all fields. Otherwise, only the given fields will be returned in the serialized output. invalid: If a field cannot be coerced into its respective data type, a ...
ValidationError
dataset/ETHPy150Open bendavis78/python-gitmodel/gitmodel/serializers/python.py/serialize
6,281
def deserialize(workspace, data, oid, invalid=IGNORE): """ Load a python dict as a GitModel instance. model: the model class representing the data data: a valid JSON string invalid: If a field cannot be coerced into its respective data type, a ``ValidationError`` will be raised. When...
KeyError
dataset/ETHPy150Open bendavis78/python-gitmodel/gitmodel/serializers/python.py/deserialize
6,282
def _call(self, host, method, params, secret=None, timeout=5000): params['format'] = params.get('format', 'json') # default to json if self.access_token: scheme = 'https' params['access_token'] = self.access_token host = self.ssl_host else: schem...
HTTPError
dataset/ETHPy150Open bitly/bitly-api-python/bitly_api/bitly_api.py/Connection._call
6,283
def do_action(self, acs_request): ep = region_provider.find_product_domain(self.get_region_id(), acs_request.get_product()) if ep is None: raise exs.ClientException(error_code.SDK_INVALID_REGION_ID, error_msg.get_msg('SDK_INVALID_REGION_ID')) if not isinstance(acs_request, AcsRequest): raise exs.ClientExcep...
AttributeError
dataset/ETHPy150Open aliyun/aliyun-openapi-python-sdk/aliyun-python-sdk-core/aliyunsdkcore/client.py/AcsClient.do_action
6,284
def get_response(self, acs_request): ep = region_provider.find_product_domain(self.get_region_id(), acs_request.get_product()) if ep is None: raise exs.ClientException(error_code.SDK_INVALID_REGION_ID, error_msg.get_msg('SDK_INVALID_REGION_ID')) if not isinstance(acs_request, AcsRequest): raise exs.ClientEx...
IOError
dataset/ETHPy150Open aliyun/aliyun-openapi-python-sdk/aliyun-python-sdk-core/aliyunsdkcore/client.py/AcsClient.get_response
6,285
def fit(dataset, n_clusters=5, max_iterations=10, random_state=None, save_results=True, show=False): """ Optimize k-clustering for `iterations` iterations with cluster center definitions as given in `center`. """ from disco.job import Job from disco.worker.pipeline.worker import Worker, Stage ...
ValueError
dataset/ETHPy150Open romanorac/discomll/discomll/clustering/kmeans.py/fit
6,286
def args_func(args, p): try: args.func(args, p) except __HOLE__ as e: sys.exit("Error: %s" % e) except Exception as e: if e.__class__.__name__ not in ('ScannerError', 'ParserError'): message = """\ An unexpected error has occurred with osprey (version %s), please consider...
RuntimeError
dataset/ETHPy150Open msmbuilder/osprey/osprey/cli/main.py/args_func
6,287
def NormalizeAndTypeCheck(arg, types): """Normalizes and type checks the given argument. Args: arg: an instance or iterable of the given type(s) types: allowed type or tuple of types Returns: A (list, bool) tuple. The list is a normalized, shallow copy of the argument. The boolean is True if the...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/NormalizeAndTypeCheck
6,288
def _GetConnection(): """Retrieve a datastore connection local to the thread.""" connection = None if os.getenv(_ENV_KEY): try: connection = _thread_local.connection except __HOLE__: pass if connection is None: connection = datastore_rpc.Connection(adapter=_adapter) _SetCon...
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/_GetConnection
6,289
@staticmethod def _FromPb(pb, require_valid_key=True, default_kind='<not specified>'): """Static factory method. Returns the Entity representation of the given protocol buffer (datastore_pb.Entity). Not intended to be used by application developers. The Entity PB's key must be complete. If it isn't, ...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/Entity._FromPb
6,290
def _CheckFilter(self, filter, values): """Type check a filter string and list of values. Raises BadFilterError if the filter string is empty, not a string, or invalid. Raises BadValueError if the value type is not supported. Args: filter: String containing the filter text. values: List of...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/Query._CheckFilter
6,291
def __init__(self, entity_iterator, orderings): """Ctor. Args: entity_iterator: an iterator of entities which will be wrapped. orderings: an iterable of (identifier, order) pairs. order should be either Query.ASCENDING or Query.DESCENDING. """ self.__entity_iterator = ...
StopIteration
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/MultiQuery.SortOrderEntity.__init__
6,292
def Run(self, **kwargs): """Return an iterable output with all results in order. Merge sort the results. First create a list of iterators, then walk though them and yield results in order. Args: kwargs: Any keyword arguments accepted by datastore_query.QueryOptions(). Returns: An iter...
StopIteration
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/MultiQuery.Run
6,293
def __delitem__(self, query_filter): """Delete a filter by deleting it from all subqueries. If a KeyError is raised during the attempt, it is ignored, unless every subquery raised a KeyError. If any other exception is raised, any deletes will be rolled back. Args: query_filter: the filter to...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/api/datastore.py/MultiQuery.__delitem__
6,294
def __getattr__(self, name): # type: (str) -> Any try: return self[name] except __HOLE__: raise AttributeError(name)
KeyError
dataset/ETHPy150Open tornadoweb/tornado/tornado/util.py/ObjectDict.__getattr__
6,295
def import_object(name): # type: (_BaseString) -> Any """Imports an object by name. import_object('x') is equivalent to 'import x'. import_object('x.y.z') is equivalent to 'from x.y import z'. >>> import tornado.escape >>> import_object('tornado.escape') is tornado.escape True >>> impo...
AttributeError
dataset/ETHPy150Open tornadoweb/tornado/tornado/util.py/import_object
6,296
def __init__(self, func, name): # type: (Callable, str) -> None self.name = name try: self.arg_pos = self._getargnames(func).index(name) except __HOLE__: # Not a positional parameter self.arg_pos = None
ValueError
dataset/ETHPy150Open tornadoweb/tornado/tornado/util.py/ArgReplacer.__init__
6,297
def _getargnames(self, func): # type: (Callable) -> List[str] try: return getargspec(func).args except __HOLE__: if hasattr(func, 'func_code'): # Cython-generated code has all the attributes needed # by inspect.getargspec, but the inspect m...
TypeError
dataset/ETHPy150Open tornadoweb/tornado/tornado/util.py/ArgReplacer._getargnames
6,298
def do_run_tests(project, logger, execution_prefix, execution_name): test_dir = _register_test_and_source_path_and_return_test_dir(project, sys.path, execution_prefix) file_suffix = project.get_property("%s_file_suffix" % execution_prefix) if file_suffix is not None: logger.warn( "%(pre...
ImportError
dataset/ETHPy150Open pybuilder/pybuilder/src/main/python/pybuilder/plugins/python/unittest_plugin.py/do_run_tests
6,299
def setup_env(dev_appserver_version=1): """Configures GAE environment for command-line apps.""" if dev_appserver_version not in (1, 2): raise Exception('Invalid dev_appserver_version setting, expected 1 or 2, got %s' % dev_appserver_version) # Try to import the appengine code from the system path....
ImportError
dataset/ETHPy150Open django-nonrel/djangoappengine/djangoappengine/boot.py/setup_env