Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,400
def __init__( self, matchString, identChars=DEFAULT_KEYWORD_CHARS, caseless=False ): super(Keyword,self).__init__() self.match = matchString self.matchLen = len(matchString) try: self.firstMatchChar = matchString[0] except __HOLE__: warnings.warn("null str...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/Keyword.__init__
2,401
def __init__( self, exprs, savelist = False ): super(ParseExpression,self).__init__(savelist) if isinstance( exprs, list ): self.exprs = exprs elif isinstance( exprs, str ): self.exprs = [ Literal( exprs ) ] else: try: self.exprs = list...
TypeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ParseExpression.__init__
2,402
def parseImpl( self, instring, loc, doActions=True ): # pass False as last arg to _parse for first element, since we already # pre-parsed the string as part of our And pre-parsing loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False ) errorStop = False ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/And.parseImpl
2,403
def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxMatchLoc = -1 maxException = None for e in self.exprs: try: loc2 = e.tryParse( instring, loc ) except ParseException as err: if err.loc > maxExcLoc: ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/Or.parseImpl
2,404
def parseImpl( self, instring, loc, doActions=True ): maxExcLoc = -1 maxException = None for e in self.exprs: try: ret = e._parse( instring, loc, doActions ) return ret except ParseException as err: if err.loc > maxExcLoc: ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/MatchFirst.parseImpl
2,405
def parseImpl( self, instring, loc, doActions=True ): try: self.expr.tryParse( instring, loc ) except (ParseException,__HOLE__): pass else: #~ raise ParseException(instring, loc, self.errmsg ) exc = self.myException exc.loc = loc ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/NotAny.parseImpl
2,406
def parseImpl( self, instring, loc, doActions=True ): tokens = [] try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: preloc ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/ZeroOrMore.parseImpl
2,407
def parseImpl( self, instring, loc, doActions=True ): # must be at least one loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) try: hasIgnoreExprs = ( len(self.ignoreExprs) > 0 ) while 1: if hasIgnoreExprs: ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/OneOrMore.parseImpl
2,408
def parseImpl( self, instring, loc, doActions=True ): try: loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False ) except (ParseException,__HOLE__): if self.defaultValue is not _optionalNotMatched: if self.expr.resultsName: ...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/Optional.parseImpl
2,409
def parseImpl( self, instring, loc, doActions=True ): startLoc = loc instrlen = len(instring) expr = self.expr failParse = False while loc <= instrlen: try: if self.failOn: try: self.failOn.tryParse(instring,...
IndexError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/SkipTo.parseImpl
2,410
def traceParseAction(f): """Decorator for debugging parse actions.""" f = ParserElement._normalizeParseActionArgs(f) def z(*paArgs): thisFunc = f.__name__ s,l,t = paArgs[-3:] if len(paArgs)>3: thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc sys.stderr.wri...
AttributeError
dataset/ETHPy150Open ipython/ipython-py3k/IPython/external/pyparsing/_pyparsing.py/traceParseAction
2,411
def change_file_ext(): """ read a file and an extension from the command line and produces a copy with its extension changed""" if len(sys.argv) < 2: print("Usage: change_ext.py filename.old_ext 'new_ext'") sys.exit() name = os.path.splitext(sys.argv[1])[0] + "." + sys.argv[2] print (na...
OSError
dataset/ETHPy150Open bt3gl/Python-and-Algorithms-and-Data-Structures/src/USEFUL/useful_with_files/change_ext_file.py/change_file_ext
2,412
def get_user(self): # django 1.5 uses uidb36, django 1.6 uses uidb64 uidb36 = self.kwargs.get('uidb36') uidb64 = self.kwargs.get('uidb64') assert bool(uidb36) ^ bool(uidb64) try: if uidb36: uid = base36_to_int(uidb36) else: ...
ValueError
dataset/ETHPy150Open fusionbox/django-authtools/authtools/views.py/PasswordResetConfirmView.get_user
2,413
def render(self, context): try: expire_time = self.expire_time_var.resolve(context) except VariableDoesNotExist: raise TemplateSyntaxError('"cache" tag got an unknown variable: %r' % self.expire_time_var.var) try: expire_time = int(expire_time) except ...
TypeError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/templatetags/cache.py/CacheNode.render
2,414
def run_system_command(self, command): """ Run system command (While hiding the prompt. When finished, all the output will scroll above the prompt.) :param command: Shell command to be executed. """ def wait_for_enter(): """ Create a sub applicati...
AttributeError
dataset/ETHPy150Open jonathanslenders/python-prompt-toolkit/prompt_toolkit/interface.py/CommandLineInterface.run_system_command
2,415
def main(): """Parse environment and arguments and call the appropriate action.""" config.parse_args(sys.argv, default_config_files=jsonutils.loads(os.environ['CONFIG_FILE'])) logging.setup(CONF, "nova") global LOG LOG = logging.getLogger('nova.dhcpbridge') if CONF.action.name == 'old'...
TypeError
dataset/ETHPy150Open BU-NU-CLOUD-SP16/Trusted-Platform-Module-nova/nova/cmd/dhcpbridge.py/main
2,416
def save(self, *args, **kwargs): if getattr(self, 'cleanse', None): try: # Passes the rich text content as first argument because # the passed callable has been converted into a bound method self.richtext = self.cleanse(self.richtext) excep...
TypeError
dataset/ETHPy150Open feincms/feincms/feincms/content/section/models.py/SectionContent.save
2,417
def mkdir_p(path): try: os.makedirs(path) except __HOLE__ as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
OSError
dataset/ETHPy150Open eallik/spinoff/spinoff/contrib/filetransfer/util.py/mkdir_p
2,418
def get_by_natural_key(self, app_label, model): try: ct = self.__class__._cache[self.db][(app_label, model)] except __HOLE__: ct = self.get(app_label=app_label, model=model) self._add_to_cache(self.db, ct) return ct
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/contenttypes/models.py/ContentTypeManager.get_by_natural_key
2,419
def get_for_model(self, model, for_concrete_model=True): """ Returns the ContentType object for a given model, creating the ContentType if necessary. Lookups are cached so that subsequent lookups for the same model don't hit the database. """ opts = self._get_opts(model, ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/contenttypes/models.py/ContentTypeManager.get_for_model
2,420
def get_for_models(self, *models, **kwargs): """ Given *models, returns a dictionary mapping {model: content_type}. """ for_concrete_models = kwargs.pop('for_concrete_models', True) # Final results results = {} # models that aren't already in the cache nee...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/contenttypes/models.py/ContentTypeManager.get_for_models
2,421
def get_for_id(self, id): """ Lookup a ContentType by ID. Uses the same shared cache as get_for_model (though ContentTypes are obviously not created on-the-fly by get_by_id). """ try: ct = self.__class__._cache[self.db][id] except __HOLE__: # This ...
KeyError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/contenttypes/models.py/ContentTypeManager.get_for_id
2,422
def decode(stream): try: return stream.decode('utf-8') except __HOLE__: return stream.decode('iso-8859-1', errors='ignore')
UnicodeDecodeError
dataset/ETHPy150Open mesonbuild/meson/mesonbuild/scripts/meson_test.py/decode
2,423
def run_tests(datafilename): global options logfile_base = 'meson-logs/testlog' if options.wrapper is None: wrap = [] logfilename = logfile_base + '.txt' jsonlogfilename = logfile_base+ '.json' else: wrap = [options.wrapper] logfilename = logfile_base + '-' + opti...
ValueError
dataset/ETHPy150Open mesonbuild/meson/mesonbuild/scripts/meson_test.py/run_tests
2,424
def set_fec_id(this_fec_id): try: ftpcandidate = Candidate.objects.filter(cand_id = this_fec_id).order_by('-cycle')[0] except __HOLE__: print "No candidate found in master file for id=%s" % (this_fec_id) return print "Got cycle: %s" % (ftpcandidate.cycle) this_incumbent,...
IndexError
dataset/ETHPy150Open sunlightlabs/read_FEC/fecreader/summary_data/management/commands/set_incumbent.py/set_fec_id
2,425
def get_template_sources(self, template_name, template_dirs=None): """ Returns the absolute paths to "template_name", when appended to each directory in "template_dirs". Any paths that don't lie inside one of the template dirs are excluded from the result set, for security reasons. ...
UnicodeDecodeError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/loaders/layouts_templates.py/Loader.get_template_sources
2,426
def load_template_source(self, template_name, template_dirs=None): for filepath in self.get_template_sources(template_name, template_dirs): try: file = open(filepath) try: return (file.read().decode(settings.FILE_CHARSET), filepath) ...
IOError
dataset/ETHPy150Open ionyse/ionyweb/ionyweb/loaders/layouts_templates.py/Loader.load_template_source
2,427
def DownloadActivityList(self, serviceRecord, exhaustive=False): """ GET List of Activities as JSON File URL: http://app.velohero.com/export/workouts/json Parameters: user = username pass = password date_from = YYYY-MM-DD date_to = YYYY-MM-DD ...
ValueError
dataset/ETHPy150Open cpfair/tapiriik/tapiriik/services/VeloHero/velohero.py/VeloHeroService.DownloadActivityList
2,428
def UploadActivity(self, serviceRecord, activity): """ POST a Multipart-Encoded File URL: http://app.velohero.com/upload/file Parameters: user = username pass = password view = json file = multipart-encodes file (fit, tcx, pwx, gpx, srm, hrm...) ...
ValueError
dataset/ETHPy150Open cpfair/tapiriik/tapiriik/services/VeloHero/velohero.py/VeloHeroService.UploadActivity
2,429
def __init__(self, host='localhost', port=61613, user='', passcode='', ver='1.1', prompt='> ', verbose=True, use_ssl=False, heartbeats=(0, 0), stdin=sys.stdin, stdout=sys.stdout): Cmd.__init__(self, 'Tab', stdin, stdout) ConnectionListener.__init__(self) self.prompt = prompt self.verbose...
ValueError
dataset/ETHPy150Open jasonrbriggs/stomp.py/stomp/__main__.py/StompCLI.__init__
2,430
def main(): parser = OptionParser(version=stomppy_version) parser.add_option('-H', '--host', type='string', dest='host', default='localhost', help='Hostname or IP to connect to. Defaults to localhost if not specified.') parser.add_option('-P', '--port', type=int, dest='port', default=...
KeyboardInterrupt
dataset/ETHPy150Open jasonrbriggs/stomp.py/stomp/__main__.py/main
2,431
def ComputeIPolicyInstanceViolation(ipolicy, instance, cfg, _compute_fn=ComputeIPolicySpecViolation): """Compute if instance meets the specs of ipolicy. @type ipolicy: dict @param ipolicy: The ipolicy to verify against @type instance: L{objects.Instance} @param instance: T...
TypeError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/common.py/ComputeIPolicyInstanceViolation
2,432
def GetUpdatedParams(old_params, update_dict, use_default=True, use_none=False): """Return the new version of a parameter dictionary. @type old_params: dict @param old_params: old parameters @type update_dict: dict @param update_dict: dict containing new parameter values, or const...
KeyError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/common.py/GetUpdatedParams
2,433
def GetUpdatedIPolicy(old_ipolicy, new_ipolicy, group_policy=False): """Return the new version of an instance policy. @param group_policy: whether this policy applies to a group and thus we should support removal of policy entries """ ipolicy = copy.deepcopy(old_ipolicy) for key, value in new_ipolicy.it...
TypeError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/common.py/GetUpdatedIPolicy
2,434
def _SetOpEarlyRelease(early_release, op): """Sets C{early_release} flag on opcodes if available. """ try: op.early_release = early_release except __HOLE__: assert not isinstance(op, opcodes.OpInstanceReplaceDisks) return op
AttributeError
dataset/ETHPy150Open ganeti/ganeti/lib/cmdlib/common.py/_SetOpEarlyRelease
2,435
def test_paths_unequal(self): try: self.assertEqual(self.path1, self.path2) except __HOLE__ as e: if not str(e).startswith("Path data not almost equal to 6 decimals"): raise self.failureException("Path mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_paths_unequal
2,436
def test_contours_unequal(self): try: self.assertEqual(self.contours1, self.contours2) except __HOLE__ as e: if not str(e).startswith("Contours data not almost equal to 6 decimals"): raise self.failureException("Contours mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_contours_unequal
2,437
def test_contour_levels_unequal(self): try: self.assertEqual(self.contours1, self.contours3) except __HOLE__ as e: if not str(e).startswith("Contour levels are mismatched"): raise self.failureException("Contour level are mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_contour_levels_unequal
2,438
def test_bounds_unequal(self): try: self.assertEqual(self.bounds1, self.bounds2) except __HOLE__ as e: if not str(e).startswith("Bounds data not almost equal to 6 decimals"): raise self.failureException("Bounds mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_bounds_unequal
2,439
def test_boxs_unequal(self): try: self.assertEqual(self.box1, self.box2) except __HOLE__ as e: if not str(e).startswith("Box data not almost equal to 6 decimals"): raise self.failureException("Box mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_boxs_unequal
2,440
def test_ellipses_unequal(self): try: self.assertEqual(self.ellipse1, self.ellipse2) except __HOLE__ as e: if not str(e).startswith("Ellipse data not almost equal to 6 decimals"): raise self.failureException("Ellipse mismatch error not raised.")
AssertionError
dataset/ETHPy150Open ioam/holoviews/tests/testcomparisonpath.py/PathComparisonTest.test_ellipses_unequal
2,441
def __init__(self, to, to_field=None, rel_class=ManyToOneRel, **kwargs): try: to._meta.object_name.lower() except __HOLE__: # to._meta doesn't exist, so it must be RECURSIVE_RELATIONSHIP_CONSTANT assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKe...
AttributeError
dataset/ETHPy150Open disqus/sharding-example/sqlshards/db/shards/models.py/PartitionedForeignKey.__init__
2,442
def __get__(self, instance, instance_type=None): if instance is None: return self cache_name = self.field.get_cache_name() try: return getattr(instance, cache_name) except __HOLE__: val = getattr(instance, self.field.attname) if val is Non...
AttributeError
dataset/ETHPy150Open disqus/sharding-example/sqlshards/db/shards/models.py/PartitionedReverseRelatedObjectDescriptor.__get__
2,443
def __init__(self, url, protocols=None, extensions=None, heartbeat_freq=None, ssl_options=None, headers=None): """ A websocket client that implements :rfc:`6455` and provides a simple interface to communicate with a websocket server. This class works on its own but will...
AttributeError
dataset/ETHPy150Open Lawouach/WebSocket-for-Python/ws4py/client/__init__.py/WebSocketBaseClient.__init__
2,444
def call_highest_priority(method_name): """A decorator for binary special methods to handle _op_priority. Binary special methods in Expr and its subclasses use a special attribute '_op_priority' to determine whose special method will be called to handle the operation. In general, the object having the ...
AttributeError
dataset/ETHPy150Open sympy/sympy/sympy/core/decorators.py/call_highest_priority
2,445
def matchCall(func_name, args, star_list_arg, star_dict_arg, num_defaults, positional, pairs, improved = False): # This is of incredible code complexity, but there really is no other way to # express this with less statements, branches, or variables. # pylint: disable=R0912,R0914,R0915 as...
StopIteration
dataset/ETHPy150Open kayhayen/Nuitka/nuitka/nodes/ParameterSpecs.py/matchCall
2,446
def render(self, name, value, *args, **kwargs): try: lat = value.lat lng = value.lng except __HOLE__: lat = settings.DEFAULT_LATITUDE lng = settings.DEFAULT_LONGITUDE js = ''' </script> <script type="text/javascript"> ...
AttributeError
dataset/ETHPy150Open albatrossandco/brubeck_cms/brubeck/mapping/fields.py/LocationWidget.render
2,447
def _add_plugin(self, plugindir): """ If this is a Jig plugin, add it. ``plugindir`` should be the full path to a directory containing all the files required for a jig plugin. """ # Is this a plugins? config_filename = join(plugindir, PLUGIN_CONFIG_FILENAME) ...
KeyError
dataset/ETHPy150Open robmadole/jig/src/jig/plugins/manager.py/PluginManager._add_plugin
2,448
def pre_commit(self, git_diff_index): """ Runs the plugin's pre-commit script, passing in the diff. ``git_diff_index`` is a :py:class:`jig.diffconvert.GitDiffIndex` object. The pre-commit script will receive JSON data as standard input (stdin). The JSON data is comprise...
OSError
dataset/ETHPy150Open robmadole/jig/src/jig/plugins/manager.py/Plugin.pre_commit
2,449
def __init__(self, *args, **kwargs): super(FluentCommentForm, self).__init__(*args, **kwargs) # Remove fields from the form. # This has to be done in the constructor, because the ThreadedCommentForm # inserts the title field in the __init__, instead of the static form definition. ...
KeyError
dataset/ETHPy150Open edoburu/django-fluent-comments/fluent_comments/forms.py/FluentCommentForm.__init__
2,450
def callable_year(dt_value): try: return dt_value.year except __HOLE__: return None
AttributeError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/tests/regressiontests/admin_views/admin.py/callable_year
2,451
def run_interaction(f, args, kwargs): """ Run an interaction function, which may yield FrontEndOperation objects to interact with the front end. """ g = f(*args, **kwargs) def advance(to_send=None): try: op = g.send(to_send) except __HOLE__: return ...
StopIteration
dataset/ETHPy150Open Microsoft/ivy/ivy/ui_extensions_api.py/run_interaction
2,452
def run(self): while True: try: msg = self.child_conn.recv() except __HOLE__: continue if msg == 'shutdown': break elif msg == 'start': self._collect() self.child_conn.close()
KeyboardInterrupt
dataset/ETHPy150Open dask/dask/dask/diagnostics/profile.py/_Tracker.run
2,453
def _get_remote_branch(self): """Return the remote branch assoicated with this repository. If the remote branch is not defined, the parent branch of the repository is returned. """ remote = getattr(self.options, 'tracking', None) if not remote: try: ...
IndexError
dataset/ETHPy150Open reviewboard/rbtools/rbtools/clients/mercurial.py/MercurialClient._get_remote_branch
2,454
def test_frozen(self): with captured_stdout() as stdout: try: import __hello__ except ImportError as x: self.fail("import __hello__ failed:" + str(x)) self.assertEqual(__hello__.initialized, True) expect = set(self.module_attrs) ...
ImportError
dataset/ETHPy150Open amrdraz/kodr/app/brython/www/src/Lib/test/test_frozen.py/FrozenTests.test_frozen
2,455
def save(self, commit=True): instance = super(OrgForm, self).save(commit=False) if 'issues' in self.fields: old_issues = instance.issues.all() new_issues = self.cleaned_data['issues'] to_delete = set(old_issues) - set(new_issues) to_create = set(new_issues...
ValidationError
dataset/ETHPy150Open jumoconnect/openjumo/jumodjango/org/forms.py/OrgForm.save
2,456
def encode(self, media): """ Encode media into a temporary file for the current encoding profile. """ temp_file, encode_path = mkstemp(suffix=".%s" % self.container, dir=settings.FILE_UPLOAD_TEMP_DIR) os.close(temp_file) co...
OSError
dataset/ETHPy150Open jbittel/django-multimedia/multimedia/models.py/EncodeProfile.encode
2,457
def upload(self, local_path): """ Upload an encoded file to remote storage and remove the local file. """ new_hash = self.generate_content_hash(local_path) if new_hash != self.content_hash: self.unlink() self.content_hash = new_hash if not...
OSError
dataset/ETHPy150Open jbittel/django-multimedia/multimedia/models.py/RemoteStorage.upload
2,458
def unlink(self): """Delete the remote file if it is no longer referenced.""" refs = RemoteStorage.objects.filter(content_hash=self.content_hash) if refs.count() == 1: try: logger.info("Deleting %s" % self.remote_path) self.get_storage().delete(self.re...
IOError
dataset/ETHPy150Open jbittel/django-multimedia/multimedia/models.py/RemoteStorage.unlink
2,459
def Filter(self, container, unused_args): """Filter method that writes the content of the file into a file. Args: container: Container object which holds all information for one definition file. See Container class for details. unused_args: No extra arguments required by this filter impleme...
IOError
dataset/ETHPy150Open google/capirca/definate/file_filter.py/WriteFileFilter.Filter
2,460
def run( func, argv=None, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr ): argv = argv or sys.argv[1:] include_func_name_in_errors = False # Handle multiple functions if isinstance(func, (tuple, list)): funcs = dict([ (fn.__name__, fn) for fn in func ...
IndexError
dataset/ETHPy150Open simonw/optfunc/optfunc.py/run
2,461
def validate_unique_prez_2012_general(): """Should only be a single contest for 2012 prez general""" count = Contest.objects.filter(election_id='md-2012-11-06-general', slug='president').count() expected = 1 try: assert count == expected print "PASS: %s general prez contest found for 201...
AssertionError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/md/validate/__init__.py/validate_unique_prez_2012_general
2,462
def validate_obama_candidacies_2012(): """Should only be two Obama candidacies in 2012 (primary and general)""" kwargs = { 'election_id__startswith': 'md-2012', 'slug': 'barack-obama', } count = Candidate.objects.filter(**kwargs).count() expected = 2 try: assert count == ...
AssertionError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/md/validate/__init__.py/validate_obama_candidacies_2012
2,463
def validate_unique_contests(): """Should have a unique set of contests for all elections""" # Get all election ids election_ids = list(Contest.objects.distinct('election_id')) for elec_id in election_ids: contests = Contest.objects.filter(election_id=elec_id) # compare the number of con...
AssertionError
dataset/ETHPy150Open openelections/openelections-core/openelex/us/md/validate/__init__.py/validate_unique_contests
2,464
def main(): with Input() as input: with FullscreenWindow() as window: b = Board() while True: window.render_to_terminal(b.display()) if b.turn == 9 or b.winner(): c = input.next() # hit any key sys.exit() ...
ValueError
dataset/ETHPy150Open thomasballinger/curtsies/examples/tictactoeexample.py/main
2,465
def initial(self, request, *args, **kwargs): if hasattr(self, 'PaidControl') and self.action and self.action not in ('list', 'retrieve', 'create'): if django_settings.NODECONDUCTOR.get('SUSPEND_UNPAID_CUSTOMERS'): entity = self.get_object() def get_obj(name): ...
AttributeError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/structure/views.py/UpdateOnlyByPaidCustomerMixin.initial
2,466
def create(self, request, *args, **kwargs): if django_settings.NODECONDUCTOR.get('SUSPEND_UNPAID_CUSTOMERS'): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) def get_obj(name): try: args = geta...
AttributeError
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/structure/views.py/UpdateOnlyByPaidCustomerMixin.create
2,467
def get_stats_for_scope(self, quota_name, scope, dates): stats_data = [] try: quota = scope.quotas.get(name=quota_name) except Quota.DoesNotExist: return stats_data versions = reversion\ .get_for_object(quota)\ .select_related('revision')\ ...
StopIteration
dataset/ETHPy150Open opennode/nodeconductor/nodeconductor/structure/views.py/QuotaTimelineStatsView.get_stats_for_scope
2,468
def parse_json(self, req, name, field): """Pull a json value from the request.""" try: json_data = webapp2_extras.json.decode(req.body) except __HOLE__: return core.missing return core.get_value(json_data, name, field, allow_many_nested=True)
ValueError
dataset/ETHPy150Open sloria/webargs/webargs/webapp2parser.py/Webapp2Parser.parse_json
2,469
@property def overrides(self): warnings.warn("`Settings.overrides` attribute is deprecated and won't " "be supported in Scrapy 0.26, use " "`Settings.set(name, value, priority='cmdline')` instead", category=ScrapyDeprecationWarning, stackleve...
AttributeError
dataset/ETHPy150Open scrapy/scrapy/scrapy/settings/__init__.py/BaseSettings.overrides
2,470
@property def defaults(self): warnings.warn("`Settings.defaults` attribute is deprecated and won't " "be supported in Scrapy 0.26, use " "`Settings.set(name, value, priority='default')` instead", category=ScrapyDeprecationWarning, stacklevel=...
AttributeError
dataset/ETHPy150Open scrapy/scrapy/scrapy/settings/__init__.py/BaseSettings.defaults
2,471
@csrf_exempt def rest(request, *pargs): """ Calls python function corresponding with HTTP METHOD name. Calls with incomplete arguments will return HTTP 400 """ if request.method == 'GET': rest_function = get elif request.method == 'POST': rest_function = post elif request.me...
TypeError
dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/user.py/rest
2,472
@RequireLogin(role='admin') def post(request): """ Create a new user. """ try: new = json.loads(request.body) assert "username" in new assert "password" in new assert "email" in new except AssertionError: return HttpResponseBadRequest("argument mismatch") ...
ValueError
dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/user.py/post
2,473
@RequireLogin() def put(request, username): """ Update existing user based on username. """ # Users can only update their own account, unless admin if (request.user['username'] != username) and (auth.is_admin(request.user) is False): return HttpResponseForbidden() try: in_json =...
ValueError
dataset/ETHPy150Open emccode/heliosburn/heliosburn/django/hbproject/api/views/user.py/put
2,474
def __init__(self, subject, decimate=False): self.subject = subject self.types = [] left, right = db.get_surf(subject, "fiducial") try: fleft, fright = db.get_surf(subject, "flat", nudge=True, merge=False) except IOError: fleft = None if decimate...
IOError
dataset/ETHPy150Open gallantlab/pycortex/cortex/brainctm.py/BrainCTM.__init__
2,475
def addCurvature(self, **kwargs): npz = db.get_surfinfo(self.subject, type='curvature', **kwargs) try: self.left.aux[:,1] = npz.left[self.left.mask] self.right.aux[:,1] = npz.right[self.right.mask] except __HOLE__: self.left.aux[:,1] = npz.left sel...
AttributeError
dataset/ETHPy150Open gallantlab/pycortex/cortex/brainctm.py/BrainCTM.addCurvature
2,476
def __init__(self, **kwargs): # pylint: disable=W0613 super(Device, self).__init__(**kwargs) if not self.path_module: raise NotImplementedError('path_module must be specified by the deriving classes.') libpath = os.path.dirname(os.__file__) modpath = os.path.join(libpath, se...
IOError
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/core/device.py/Device.__init__
2,477
def publish(self, channel, *args, **kwargs): """Return output of all subscribers for the given channel.""" if channel not in self.listeners: return [] exc = ChannelFailures() output = [] items = [(self._priorities[(channel, listener)], listener) for...
KeyboardInterrupt
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/process/wspbus.py/Bus.publish
2,478
def start(self): """Start all services.""" atexit.register(self._clean_exit) self.state = states.STARTING self.log('Bus STARTING') try: self.publish('start') self.state = states.STARTED self.log('Bus STARTED') except (__HOLE__, SystemE...
KeyboardInterrupt
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/process/wspbus.py/Bus.start
2,479
def block(self, interval=0.1): """Wait for the EXITING state, KeyboardInterrupt or SystemExit. This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. ...
KeyboardInterrupt
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/process/wspbus.py/Bus.block
2,480
def wait(self, state, interval=0.1, channel=None): """Poll for the given state(s) at intervals; publish to channel.""" if isinstance(state, (tuple, list)): states = state else: states = [state] def _wait(): while self.state not in states: ...
KeyError
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/process/wspbus.py/Bus.wait
2,481
def _set_cloexec(self): """Set the CLOEXEC flag on all open files (except stdin/out/err). If self.max_cloexec_files is an integer (the default), then on platforms which support it, it represents the max open files setting for the operating system. This function will be called just befor...
IOError
dataset/ETHPy150Open clips/pattern/pattern/server/cherrypy/cherrypy/process/wspbus.py/Bus._set_cloexec
2,482
def get_slave_instances(self, ): instances = self.get_database_instances() master = self.get_master_instance() try: instances.remove(master) except __HOLE__: raise Exception("Master could not be detected") return instances
ValueError
dataset/ETHPy150Open globocom/database-as-a-service/dbaas/drivers/base.py/BaseDriver.get_slave_instances
2,483
def execute_command(server_config, command, **kwargs): before_fds = _get_open_fds() # see the comment in the finally clause below if isinstance(command, basestring): command = Command(command, **kwargs) timeout = 300 if command.name in ['stop', 'pull'] else 10 factory = CommandExecutorFactory(s...
OSError
dataset/ETHPy150Open ARM-software/workload-automation/wlauto/external/daq_server/src/daqpower/client.py/execute_command
2,484
def test_exception_record(self): formatter = logger.JsonLogFormatter(job_id='jobid', worker_id='workerid') try: raise ValueError('Something') except __HOLE__: attribs = dict(self.SAMPLE_RECORD) attribs.update({'exc_info': sys.exc_info()}) record = self.create_log_record(**attribs) ...
ValueError
dataset/ETHPy150Open GoogleCloudPlatform/DataflowPythonSDK/google/cloud/dataflow/worker/logger_test.py/JsonLogFormatterTest.test_exception_record
2,485
def process(fn): try: f = open(fn) except __HOLE__ as err: print(err) return try: for i, line in enumerate(f): line = line.rstrip('\n') sline = line.rstrip() if len(line) >= 80 or line != sline or not isascii(line): print('{...
IOError
dataset/ETHPy150Open python/asyncio/check.py/process
2,486
def validate(self, modelXbrl, parameters=None): if not hasattr(modelXbrl.modelDocument, "xmlDocument"): # not parsed return self._isStandardUri = {} modelXbrl.modelManager.disclosureSystem.loadStandardTaxonomiesDict() # find typedDomainRefs before validateXB...
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateFiling.py/ValidateFiling.validate
2,487
def isStandardUri(self, uri): try: return self._isStandardUri[uri] except __HOLE__: isStd = (uri in self.disclosureSystem.standardTaxonomiesDict or (not isHttpUrl(uri) and # try 2011-12-23 RH: if works, remove the localHrefs ...
KeyError
dataset/ETHPy150Open Arelle/Arelle/arelle/ValidateFiling.py/ValidateFiling.isStandardUri
2,488
def _resolve_value(self, name): """ Returns an appropriate value for the given name. """ name = str(name) if name in self._metadata._meta.elements: element = self._metadata._meta.elements[name] # Look in instances for an explicit value if element.editable: ...
AttributeError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/backends.py/MetadataBaseModel._resolve_value
2,489
def get_model(self, options): class ViewMetadataBase(MetadataBaseModel): _view = models.CharField(_('view'), max_length=255, unique=not (options.use_sites or options.use_i18n), default="", blank=True) if options.use_sites: _site = models.ForeignKey(Site, null=True, blank=...
AttributeError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/backends.py/ViewBackend.get_model
2,490
def get_model(self, options): class ModelInstanceMetadataBase(MetadataBaseModel): _path = models.CharField(_('path'), max_length=255, editable=False, unique=not (options.use_sites or options.use_i18n)) _content_type = models.ForeignKey(ContentType, editable=False) _object_id ...
AttributeError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/backends.py/ModelInstanceBackend.get_model
2,491
def get_model(self, options): class ModelMetadataBase(MetadataBaseModel): _content_type = models.ForeignKey(ContentType) if options.use_sites: _site = models.ForeignKey(Site, null=True, blank=True, verbose_name=_("site")) if options.use_i18n: _...
AttributeError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/backends.py/ModelBackend.get_model
2,492
@staticmethod def validate(options): """ Validates the application of this backend to a given metadata """ try: if options.backends.index('modelinstance') > options.backends.index('model'): raise Exception("Metadata backend 'modelinstance' must come before 'model...
ValueError
dataset/ETHPy150Open willhardy/django-seo/rollyourown/seo/backends.py/ModelBackend.validate
2,493
def update(self): """Check module status, update upstream and run compute. This is the execution logic for the module. It handled all the different possible states (cached, suspended, already failed), run the upstream and the compute() method, reporting everything to the logger. ...
KeyboardInterrupt
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/modules/vistrails_module.py/Module.update
2,494
def compute_while(self): """This method executes the module once for each input. Similarly to controlflow's fold, it calls update() in a loop to handle lists of inputs. """ name_condition = self.control_params.get( ModuleControlParam.WHILE_COND_KEY, None) ma...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/modules/vistrails_module.py/Module.compute_while
2,495
def get_input_list(self, port_name): """Returns the value(s) coming in on the input port named **port_name**. When a port can accept more than one input, this method obtains all the values being passed in. :param port_name: the name of the input port being queried :type port_na...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/modules/vistrails_module.py/Module.get_input_list
2,496
def set_streaming_output(self, port, generator, size=0): """This method is used to set a streaming output port. :param port: the name of the output port to be set :type port: str :param generator: An iterator object supporting .next() :param size: The number of values if known (...
StopIteration
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/modules/vistrails_module.py/Module.set_streaming_output
2,497
def __call__(self): result = self.obj.get_output(self.port) if isinstance(result, Module): warnings.warn( "A Module instance was used as data: " "module=%s, port=%s, object=%r" % (type(self.obj).__name__, ...
TypeError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/core/modules/vistrails_module.py/ModuleConnector.__call__
2,498
def copy_to_unicode(element): """ used to transform the lxml version of unicode to a standard version of unicode that can be pickalable - necessary for linting """ if isinstance(element, dict): return { key: copy_to_unicode(val) for key, val in element.items() } ...
TypeError
dataset/ETHPy150Open CenterForOpenScience/scrapi/scrapi/util.py/copy_to_unicode
2,499
def test_patch_wont_create_by_default(self): try: @patch('%s.frooble' % builtin_string, sentinel.Frooble) def test(): self.assertEqual(frooble, sentinel.Frooble) test() except __HOLE__: pass else: self.fail('Patching no...
AttributeError
dataset/ETHPy150Open testing-cabal/mock/mock/tests/testpatch.py/PatchTest.test_patch_wont_create_by_default