Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
8,000
def _read_callback(self, data=None): """Callback called when some data are read on the socket. The buffer is given to the hiredis parser. If a reply is complete, we put the decoded reply to on the reply queue. Args: data (str): string (buffer) read on the socket. ""...
IndexError
dataset/ETHPy150Open thefab/tornadis/tornadis/client.py/Client._read_callback
8,001
@staticmethod def translate_to_python(c, top_class=None, text_query=True): try: i = c.index('(') except __HOLE__: if text_query: return TextQuery(c) raise ValueError("Invalid QueryCondition syntax") clsname = c[:i] cls = find_subcla...
ValueError
dataset/ETHPy150Open VisTrails/VisTrails/vistrails/packages/persistent_archive/queries.py/QueryCondition.translate_to_python
8,002
def get(self, request, *args, **kwargs): try: import memcache except __HOLE__: return HttpResponseNotFound() if not request.user.is_authenticated() and request.user.is_staff: return HttpResponseForbidden() if settings.CACHES['default']['BACKEND'] != ...
ImportError
dataset/ETHPy150Open niwinz/niwi-web/src/niwi/contrib/memcache_status/views.py/MemcacheStatusView.get
8,003
def print_cycles(objects, outstream=sys.stdout, show_progress=False): '''Find reference cycles :param list objects: A list of objects to find cycles in. It is often useful to pass in gc.garbage to find the cycles that are preventing some objects from being garbage collected. :param file outstream: The st...
AttributeError
dataset/ETHPy150Open powerline/powerline/powerline/lib/debug.py/print_cycles
8,004
@staticmethod def is_datetime(value): """Verifies that value is a valid Datetime type, or can be converted to it. Returns: bool """ try: dt = Datetime(value) dt # shut up pyflakes return True except __HOLE__: ret...
ValueError
dataset/ETHPy150Open bokeh/bokeh/bokeh/charts/data_source.py/ChartDataSource.is_datetime
8,005
def main(main_name): """The main entry point to the bootstrapper. Call this with the module name to use as your main app.""" # prelaunch should bypass full bootstrap if prelaunch_client.is_prelaunch_client(sys.argv): # This is a lightweight import due to lazy initialization of the message loop. import m...
ImportError
dataset/ETHPy150Open natduca/quickopen/src/bootstrap.py/main
8,006
def next(self): try: x = self.rp[self.ix] except __HOLE__: raise StopIteration self.ix += 1 return x
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/RefPatIter.next
8,007
def __getattr__(self, s): if not self.is_initialized: raise AttributeError, s try: return getattr(self.__class__, s) except __HOLE__: pass try: row = self.get_row_named(s) except ValueError: raise AttributeError, s return row.set
AttributeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/ReferencePattern.__getattr__
8,008
def generate(self, ix=None): while ix is None or ix < 0 or ix >= len(self.lines): try: self.lines.append(self.lg.next()) except __HOLE__: self.isfullygenerated = 1 return self.lines[-1].index = len(self.lines) - 1
StopIteration
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/ReferencePattern.generate
8,009
def get_row(self, key): try: [][key] except TypeError: return self.get_row_named(key) except __HOLE__: return self.get_row_indexed(key)
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/ReferencePattern.get_row
8,010
def get_row_named(self, name): row = self.get_row_indexed(0) for ix in str_as_ixl(name): try: row = row.getchild(ix) except __HOLE__: raise ValueError, 'Reference pattern has no row named %r'%name return row
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/ReferencePattern.get_row_named
8,011
def iterlines(self, start=None): if start is None: start = 0 while 1: try: yield self.get_row_indexed(start) except __HOLE__: return start += 1
IndexError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/guppy-0.1.10/guppy/heapy/RefPat.py/ReferencePattern.iterlines
8,012
def set(self, x, y, z): """Sets the components of this vector. x -- x component y -- y component z -- z component """ v = self._v try: v[0] = x * 1.0 v[1] = y * 1.0 v[2] = z * 1.0 except __HOLE__: raise Typ...
TypeError
dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/Chapter 10/gameobjects/vector3.py/Vector3.set
8,013
def __getitem__(self, index): """Retrieves a component, given its index. index -- 0, 1 or 2 for x, y or z """ try: return self._v[index] except __HOLE__: raise IndexError("There are 3 values in this object, index should be 0, 1 or 2!")
IndexError
dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/Chapter 10/gameobjects/vector3.py/Vector3.__getitem__
8,014
def __setitem__(self, index, value): """Sets a component, given its index. index -- 0, 1 or 2 for x, y or z value -- New (float) value of component """ try: self._v[index] = 1.0 * value except IndexError: raise IndexError("There are 3 values in ...
TypeError
dataset/ETHPy150Open PythonProgramming/Beginning-Game-Development-with-Python-and-Pygame/Chapter 10/gameobjects/vector3.py/Vector3.__setitem__
8,015
def _parse_date_w3dtf(datestr): if not datestr.strip(): return None parts = datestr.lower().split('t') if len(parts) == 1: # This may be a date only, or may be an MSSQL-style date parts = parts[0].split() if len(parts) == 1: # Treat this as a date only ...
ValueError
dataset/ETHPy150Open SickRage/SickRage/lib/feedparser/datetimes/w3dtf.py/_parse_date_w3dtf
8,016
def validate(self): log.debug("Trying to validate stream descriptor for %s", str(self.raw_info['stream_name'])) try: hex_stream_name = self.raw_info['stream_name'] key = self.raw_info['key'] hex_suggested_file_name = self.raw_info['suggested_file_name'] st...
KeyError
dataset/ETHPy150Open lbryio/lbry/lbrynet/lbryfile/StreamDescriptor.py/LBRYFileStreamDescriptorValidator.validate
8,017
def __init__(self, gen): self.content = None self.gen = gen github_url = GITHUB_API.format(self.gen.settings['GITHUB_USER']) try: f = urlopen(github_url) # 3 vs 2 makes us have to do nasty stuff to get encoding without # being 3 or 2 specific. So... Ye...
HTTPError
dataset/ETHPy150Open kura/pelican-githubprojects/pelican_githubprojects/github.py/GithubProjects.__init__
8,018
def status(self): """Print the status of the build system""" is_locked = False try: self.lock_fd = open(self.LOCK_FILE, 'w+') fcntl.flock(self.lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) fcntl.flock(self.lock_fd, fcntl.LOCK_UN) except __HOLE__, exc_value: ...
IOError
dataset/ETHPy150Open mozilla/inventory/mozdns/mozbind/builder.py/DNSBuilder.status
8,019
def build_staging(self, force=False): """ Create the stage folder. Fail if it already exists unless force=True. """ if os.path.exists(self.STAGE_DIR) and not force: raise BuildError("The DNS build scripts tried to build the staging" " area...
OSError
dataset/ETHPy150Open mozilla/inventory/mozdns/mozbind/builder.py/DNSBuilder.build_staging
8,020
def clear_staging(self, force=False): """ rm -rf the staging area. Fail if the staging area doesn't exist. """ self.log("Attempting rm -rf staging " "area. ({0})...".format(self.STAGE_DIR)) if os.path.exists(self.STAGE_DIR) or force: try: ...
OSError
dataset/ETHPy150Open mozilla/inventory/mozdns/mozbind/builder.py/DNSBuilder.clear_staging
8,021
def lock(self): """ Trys to write a lock file. Returns True if we get the lock, else return False. """ try: if not os.path.exists(os.path.dirname(self.LOCK_FILE)): os.makedirs(os.path.dirname(self.LOCK_FILE)) self.log("Attempting acquire mu...
IOError
dataset/ETHPy150Open mozilla/inventory/mozdns/mozbind/builder.py/DNSBuilder.lock
8,022
def stage_to_prod(self, src): """ Copy file over to PROD_DIR. Return the new location of the file. """ if not src.startswith(self.STAGE_DIR): raise BuildError( "Improper file '{0}' passed to stage_to_prod".format(src) ) dst = src.r...
IOError
dataset/ETHPy150Open mozilla/inventory/mozdns/mozbind/builder.py/DNSBuilder.stage_to_prod
8,023
def route(self, msg): k = self._digest(msg) if isinstance(k, (tuple, list)): key, args = k[0], k[1:] else: key, args = k, () try: fn = self._table[key] except __HOLE__ as e: # Check for default handler, key=None ...
KeyError
dataset/ETHPy150Open nickoala/telepot/telepot/helper.py/Router.route
8,024
def notify(self): try: self.spinner = (self.spinner + 1) % 2 os.fchmod(self._tmp.fileno(), self.spinner) except __HOLE__: # python < 2.6 self._tmp.truncate(0) os.write(self._tmp.fileno(), b"X")
AttributeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/gunicorn/workers/workertmp.py/WorkerTmp.notify
8,025
def write_to_files(self, base="."): base = os.path.join(base, "records") try: os.mkdir(base) except __HOLE__: pass f = open(os.path.join(base, "%s"%self.id), "w") self.model = bound_graph() for m in self.meds: ...
OSError
dataset/ETHPy150Open smart-classic/smart_server/smart/lib/i2b2_export.py/i2b2Patient.write_to_files
8,026
def run(self): try: if self.mode != "dir": args = {} if self.path: args["InitialDir"] = os.path.dirname(self.path) path = os.path.splitext(os.path.dirname(self.path)) args["File"] = path[0] ...
RuntimeError
dataset/ETHPy150Open kivy/plyer/plyer/platforms/win/filechooser.py/Win32FileChooser.run
8,027
def obj_get(self, bundle, **kwargs): domain = kwargs['domain'] pk = kwargs['pk'] try: user = self.Meta.object_class.get_by_user_id(pk, domain) except __HOLE__: user = None return user
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/api/resources/v0_1.py/UserResource.obj_get
8,028
def _safe_bool(bundle, param, default=False): try: return string_to_boolean(bundle.request.GET.get(param)) except __HOLE__: return default
ValueError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/api/resources/v0_1.py/_safe_bool
8,029
def _get_backend_from_engine(engine): try: engine_config = dict(utils.load_yaml(engine_cfg))[engine] this_engine_cfg_file = engine_config['cfg'] this_engine_cfg = dict(utils.load_yaml(this_engine_cfg_file)) return Engine.get_backend(this_engine_cfg[engine]['backend'], ...
KeyError
dataset/ETHPy150Open openstack/entropy/entropy/__main__.py/_get_backend_from_engine
8,030
def _add_to_list(engine, script_type, script_name, **script_args): backend = _get_backend_from_engine(engine) if backend.check_script_exists(script_type, script_name): LOG.error('%s already exists, not registering', script_type) return False try: data = { script_name: scr...
KeyError
dataset/ETHPy150Open openstack/entropy/entropy/__main__.py/_add_to_list
8,031
def prepare(self, data): """Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ ...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/pyxmpp2/xmppstringprep.py/Profile.prepare
8,032
def set_stringprep_cache_size(size): """Modify stringprep cache size. :Parameters: - `size`: new cache size """ # pylint: disable-msg=W0603 global _stringprep_cache_size _stringprep_cache_size = size if len(Profile.cache_items) > size: remove = Profile.cache_items[:-size] ...
KeyError
dataset/ETHPy150Open kuri65536/python-for-android/python3-alpha/python-libs/pyxmpp2/xmppstringprep.py/set_stringprep_cache_size
8,033
def main(): opts = parse_args() lines = opts.lines seconds = opts.seconds force_start = opts.force_start client = command.Client(opts.socket) try: if not opts.raw: curses.wrapper(get_stats, client, limit=lines, seconds=seconds, force_start=force_st...
KeyboardInterrupt
dataset/ETHPy150Open qtile/qtile/libqtile/scripts/qtile_top.py/main
8,034
def __init__(self, dir, host, rrd, period="day"): api = twirrdy.RRDBasicAPI() self.rrd = rrd self.host = host path = "%s/%s/%s" % (dir, host, rrd) self.rrd_path = "%s.rrd" % path self.info = api.info(self.rrd_path) self.color = Colorator() self.period = pe...
OSError
dataset/ETHPy150Open marineam/nagcat/python/nagcat/graph.py/Graph.__init__
8,035
@require_POST @require_can_edit_data def excel_commit(request, domain): """ Step three of three. This page is submitted with the list of column to case property mappings for this upload. The config variable is an ImporterConfig object that has everything gathered from previous steps, with the ...
KeyError
dataset/ETHPy150Open dimagi/commcare-hq/corehq/apps/importer/views.py/excel_commit
8,036
def test_original_excepthook(self): savestderr = sys.stderr err = cStringIO.StringIO() sys.stderr = err eh = sys.__excepthook__ self.assertRaises(TypeError, eh) try: raise ValueError(42) except __HOLE__, exc: eh(*sys.exc_info()) ...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_sys.py/SysModuleTest.test_original_excepthook
8,037
def test_exc_clear(self): self.assertRaises(TypeError, sys.exc_clear, 42) # Verify that exc_info is present and matches exc, then clear it, and # check that it worked. def clear_check(exc): typ, value, traceback = sys.exc_info() self.assert_(typ is not None) ...
ValueError
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_sys.py/SysModuleTest.test_exc_clear
8,038
def test_exit(self): self.assertRaises(TypeError, sys.exit, 42, 42) # call without argument try: sys.exit(0) except SystemExit, exc: self.assertEquals(exc.code, 0) except: self.fail("wrong exception") else: self.fail("no ex...
SystemExit
dataset/ETHPy150Open azoft-dev-team/imagrium/env/Lib/test/test_sys.py/SysModuleTest.test_exit
8,039
def get_pool(arg = None, opts = None, abort = False): """ Returns pool to work with Returns a pynipap.Pool object representing the pool we are working with. """ # yep, global variables are evil global pool try: pool = Pool.list({ 'name': arg })[0] except __HOLE__: if ab...
IndexError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/get_pool
8,040
def get_vrf(arg = None, default_var = 'default_vrf_rt', abort = False): """ Returns VRF to work in Returns a pynipap.VRF object representing the VRF we are working in. If there is a VRF set globally, return this. If not, fetch the VRF named 'arg'. If 'arg' is None, fetch the default_vrf ...
KeyError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/get_vrf
8,041
def add_prefix(arg, opts, shell_opts): """ Add prefix to NIPAP """ # sanity checks if 'from-pool' not in opts and 'from-prefix' not in opts and 'prefix' not in opts: print >> sys.stderr, "ERROR: 'prefix', 'from-pool' or 'from-prefix' must be specified." sys.exit(1) if len([opt for ...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/add_prefix
8,042
def add_prefix_from_pool(arg, opts): """ Add prefix using from-pool to NIPAP """ args = {} # sanity checking if 'from-pool' in opts: res = Pool.list({ 'name': opts['from-pool'] }) if len(res) == 0: print >> sys.stderr, "No pool named '%s' found." % opts['from-pool'] ...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/add_prefix_from_pool
8,043
def add_vrf(arg, opts, shell_opts): """ Add VRF to NIPAP """ v = VRF() v.rt = opts.get('rt') v.name = opts.get('name') v.description = opts.get('description') v.tags = list(csv.reader([opts.get('tags', '')], escapechar='\\'))[0] for avp in opts.get('extra-attribute', []): try: ...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/add_vrf
8,044
def add_pool(arg, opts, shell_opts): """ Add a pool. """ p = Pool() p.name = opts.get('name') p.description = opts.get('description') p.default_type = opts.get('default-type') p.ipv4_default_prefix_length = opts.get('ipv4_default_prefix_length') p.ipv6_default_prefix_length = opts.get('...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/add_pool
8,045
def view_vrf(arg, opts, shell_opts): """ View a single VRF """ if arg is None: print >> sys.stderr, "ERROR: Please specify the RT of the VRF to view." sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: v = VR...
IndexError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/view_vrf
8,046
def view_prefix(arg, opts, shell_opts): """ View a single prefix. """ # Internally, this function searches in the prefix column which means that # hosts have a prefix length of 32/128 while they are normally displayed # with the prefix length of the network they are in. To allow the user to # in...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/view_prefix
8,047
def modify_vrf(arg, opts, shell_opts): """ Modify a VRF with the options set in opts """ res = VRF.list({ 'rt': arg }) if len(res) < 1: print >> sys.stderr, "VRF with [RT: %s] not found." % arg sys.exit(1) v = res[0] if 'rt' in opts: v.rt = opts['rt'] if 'name' in ...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/modify_vrf
8,048
def modify_pool(arg, opts, shell_opts): """ Modify a pool with the options set in opts """ res = Pool.list({ 'name': arg }) if len(res) < 1: print >> sys.stderr, "No pool with name '%s' found." % arg sys.exit(1) p = res[0] if 'name' in opts: p.name = opts['name'] i...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/modify_pool
8,049
def modify_prefix(arg, opts, shell_opts): """ Modify the prefix 'arg' with the options 'opts' """ modify_confirmed = shell_opts.force spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print >> s...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/modify_prefix
8,050
def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print >> sys.stderr, "Prefix %s not found in %s." % (arg, vrf_format(v...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/prefix_attr_add
8,051
def vrf_attr_add(arg, opts, shell_opts): """ Add attributes to a VRF """ if arg is None: print >> sys.stderr, "ERROR: Please specify the RT of the VRF to view." sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None try: ...
IndexError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/vrf_attr_add
8,052
def vrf_attr_remove(arg, opts, shell_opts): """ Remove attributes from a prefix """ if arg is None: print >> sys.stderr, "ERROR: Please specify the RT of the VRF to view." sys.exit(1) # interpret as default VRF (ie, RT = None) if arg.lower() in ('-', 'none'): arg = None ...
KeyError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/vrf_attr_remove
8,053
def pool_attr_add(arg, opts, shell_opts): """ Add attributes to a pool """ res = Pool.list({ 'name': arg }) if len(res) < 1: print >> sys.stderr, "No pool with name '%s' found." % arg sys.exit(1) p = res[0] for avp in opts.get('extra-attribute', []): try: k...
ValueError
dataset/ETHPy150Open SpriteLink/NIPAP/nipap-cli/nipap_cli/nipap_cli.py/pool_attr_add
8,054
def _UploadFile(self, media_source, title, category, folder_or_uri=None): """Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. ...
AttributeError
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/docs/service.py/DocsService._UploadFile
8,055
def CreateFolder(self, title, folder_or_uri=None): """Creates a folder in the Document List feed. Args: title: string The title of the folder on the server after being created. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to ...
AttributeError
dataset/ETHPy150Open acil-bwh/SlicerCIP/Scripted/attic/PicasaSnap/gdata/docs/service.py/DocsService.CreateFolder
8,056
def __call__(self, argv): if not argv or not argv[0] or argv[0].startswith("_"): return 2 argv = self._expand_aliases(argv) # special escape characters... if argv[0].startswith("!"): # bang-escape reads pipe argv[0] = argv[0][1:] argv.insert(0, "pipe")...
ValueError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.__call__
8,057
def printenv(self, argv): """printenv [name ...] Shows the shell environment that processes will run with. """ if len(argv) == 1: names = self._environ.keys() names.sort() ms = reduce(max, map(len, names)) for name in names: value = se...
KeyError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.printenv
8,058
def help(self, argv): """help [-lLcia] [<commandname>]... Print a list of available commands, or information about a command, if the name is given. Options: -l Shows only local (object specific) commands. -c Shows only the dynamic commands. -L shows only local and dynamic comman...
AttributeError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.help
8,059
def alias(self, argv): """alias [newalias] With no argument prints the current set of aliases. With an argument of the form alias ..., sets a new alias. """ if len(argv) == 1: for name, val in self._aliases.items(): self._print("alias %s='%s'" % (name, " ".join(val))...
KeyError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.alias
8,060
def cycle(self, argv): """cycle <range> <command> [<arg>...] Cycle the % variable through range, and re-evaluate the command for each value. Range is of the form [start':']end[':' step] Where start defaults to zero and step defaults to one. Or, range is a list of values separated by ','.""...
ValueError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.cycle
8,061
def python(self, argv): import code ns = self._get_ns() console = code.InteractiveConsole(ns) console.raw_input = self._ui.user_input try: saveps1, saveps2 = sys.ps1, sys.ps2 except __HOLE__: saveps1, saveps2 = ">>> ", "... " sys.ps1, sys.p...
AttributeError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/BaseCommands.python
8,062
def complete(self, text, state): if state == 0: self.matches = [] if "." in text: for name, obj in self.namespace.items(): for key in dir(obj): if key.startswith("__"): continue ...
IndexError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/Completer.complete
8,063
def _rl_completer(self, text, state): if state == 0: curr = readline.get_line_buffer() b = readline.get_begidx() if b == 0: complist = self._cmd.get_completion_scope("commands") else: # complete based on scope keyed on previous word ...
IndexError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/CommandParser._rl_completer
8,064
def run_cli_wrapper(argv, wrappedclass=Shell, cliclass=GenericCLI, theme=None): """Instantiate a class object (the wrappedclass), and run a CLI wrapper on it.""" logfile = sourcefile = None paged = False try: optlist, longopts, args = getopt.getopt(argv[1:], "?hgs:") except getopt.GetoptErro...
TypeError
dataset/ETHPy150Open kdart/pycopia/fepy/pycopia/fepy/CLI.py/run_cli_wrapper
8,065
def status(name, sig=None): ''' Return the status for a service via s6, return pid if running CLI Example: .. code-block:: bash salt '*' s6.status <service name> ''' cmd = 's6-svstat {0}'.format(_service_path(name)) out = __salt__['cmd.run_stdout'](cmd) try: pid = re.s...
AttributeError
dataset/ETHPy150Open saltstack/salt/salt/modules/s6.py/status
8,066
def verify_token_string(self, token_string, action=None, timeout=None, current_time=None): """Generate a hash of the given token contents that can be verified. :param token_string: A string containing the hashed token (generated by `generate_token_string`). :param action: A string con...
ValueError
dataset/ETHPy150Open gregorynicholas/flask-xsrf/flask_xsrf.py/XSRFToken.verify_token_string
8,067
@classmethod def instance(cls, name, thread_count=1, idle_timeout=60): '''A convenience method for accessing shared instances of ``TaskQueue``. If ``name`` references an existing instance created with this method, that instance will be returned. Otherwise, a new ``TaskQueue`` will be instantiated with...
KeyError
dataset/ETHPy150Open JeremyOT/Toto/toto/tasks.py/TaskQueue.instance
8,068
def run(self): try: while 1: with self.condition: if not len(self.tasks): self.condition.wait(self.idle_timeout) try: task = self.tasks.popleft() except __HOLE__: logging.debug('Idle timeout: %s' % self.name) ...
IndexError
dataset/ETHPy150Open JeremyOT/Toto/toto/tasks.py/TaskQueue.__TaskLoop.run
8,069
def open_report_file(): try: FILE = open (reportfile,"r" ) entries = FILE.readlines() FILE.close() except __HOLE__: print "[+] Can not find report file:", reportfile sys.exit(1) return entries
IOError
dataset/ETHPy150Open mertsarica/hack4career/codes/vt_reporter.py/open_report_file
8,070
def convert_paramiko_errors(method): """Convert remote Paramiko errors to errors.RemoteError""" def wrapper(self, *args, **kw): try: return method(self, *args, **kw) except __HOLE__ as error: if error.errno == errno.ENOENT: raise errors.RemoteFileDoesNotEx...
IOError
dataset/ETHPy150Open ohmu/poni/poni/rcontrol_paramiko.py/convert_paramiko_errors
8,071
@convert_paramiko_errors def execute_command(self, cmd, pseudo_tty=False): def get_channel(ssh): channel = ssh.get_transport().open_session() if not channel: raise paramiko.SSHException("channel opening failed") return channel channel = self.get_ss...
IOError
dataset/ETHPy150Open ohmu/poni/poni/rcontrol_paramiko.py/ParamikoRemoteControl.execute_command
8,072
@convert_paramiko_errors def makedirs(self, dir_path): sftp = self.get_sftp() create_dirs = [] while 1: try: sftp.stat(dir_path) break # dir exists except (paramiko.SSHException, __HOLE__): create_dirs.insert(0, dir_path...
IOError
dataset/ETHPy150Open ohmu/poni/poni/rcontrol_paramiko.py/ParamikoRemoteControl.makedirs
8,073
def _pretty_frame(frame): """ Helper function for pretty-printing a frame. :param frame: The frame to be printed. :type frame: AttrDict :return: A nicely formated string representation of the frame. :rtype: str """ outstr = "" outstr += "frame ({0.ID}): {0.name}\n\n".format(frame)...
KeyError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/_pretty_frame
8,074
def _short_repr(self): if '_type' in self: if self['_type'].endswith('relation'): return self.__repr__() try: return "<{0} ID={1} name={2}>".format(self['_type'], self['ID'], self['name']) except __HOLE__: # no ID--e.g., for _type=lusubcorpu...
KeyError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/AttrDict._short_repr
8,075
def __repr__(self): parts = [] for k,v in sorted(self.items()): kv = repr(k)+': ' try: kv += v._short_repr() except __HOLE__: kv += repr(v) parts.append(kv) return '{'+(',\n ' if self._BREAK_LINES else ', ').join(par...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/PrettyDict.__repr__
8,076
def readme(self): """ Return the contents of the corpus README.txt (or README) file. """ try: return self.open("README.txt").read() except __HOLE__: return self.open("README").read()
IOError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.readme
8,077
def annotated_document(self, fn_docid): """ Returns the annotated document whose id number is ``fn_docid``. This id number can be obtained by calling the Documents() function. The dict that is returned from this function will contain the following keys: - '_type...
TypeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.annotated_document
8,078
def frame_by_id(self, fn_fid, ignorekeys=[]): """ Get the details for the specified Frame using the frame's id number. Usage examples: >>> from nltk.corpus import framenet as fn >>> f = fn.frame_by_id(256) >>> f.ID 256 >>> f.name 'Medical...
KeyError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.frame_by_id
8,079
def frame_by_name(self, fn_fname, ignorekeys=[], check_cache=True): """ Get the details for the specified Frame using the frame's name. Usage examples: >>> from nltk.corpus import framenet as fn >>> f = fn.frame_by_name('Medical_specialties') >>> f.ID 256 ...
IOError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.frame_by_name
8,080
def _lu_file(self, lu, ignorekeys=[]): """ Augment the LU information that was loaded from the frame file with additional information from the LU file. """ fn_luid = lu.ID fname = "lu{0}.xml".format(fn_luid) locpath = os.path.join("{0}".format(self._root), self._...
IOError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader._lu_file
8,081
def propagate_semtypes(self): """ Apply inference rules to distribute semtypes over relations between FEs. For FrameNet 1.5, this results in 1011 semtypes being propagated. (Not done by default because it requires loading all frame files, which takes several seconds. If this need...
AssertionError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.propagate_semtypes
8,082
def semtype(self, key): """ >>> from nltk.corpus import framenet as fn >>> fn.semtype(233).name 'Temperature' >>> fn.semtype(233).abbrev 'Temp' >>> fn.semtype('Temperature').ID 233 :param key: The name, abbreviation, or id number of the semantic t...
TypeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.semtype
8,083
def frames(self, name=None): """ Obtain details for a specific frame. >>> from nltk.corpus import framenet as fn >>> len(fn.frames()) 1019 >>> PrettyList(fn.frames(r'(?i)medical'), maxReprSize=0, breakLines=True) [<frame ID=256 name=Medical_specialties>, ...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.frames
8,084
def lus(self, name=None): """ Obtain details for a specific lexical unit. >>> from nltk.corpus import framenet as fn >>> len(fn.lus()) 11829 >>> PrettyList(fn.lus(r'(?i)a little'), maxReprSize=0, breakLines=True) [<lu ID=14744 name=a little bit.adv>, <lu...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.lus
8,085
def documents(self, name=None): """ Return a list of the annotated documents in Framenet. Details for a specific annotated document can be obtained using this class's annotated_document() function and pass it the value of the 'ID' field. >>> from nltk.corpus import framenet as ...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader.documents
8,086
def _load_xml_attributes(self, d, elt): """ Extracts a subset of the attributes from the given element and returns them in a dictionary. :param d: A dictionary in which to store the attributes. :type d: dict :param elt: An ElementTree Element :type elt: Element ...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader._load_xml_attributes
8,087
def _strip_tags(self, data): """ Gets rid of all tags and newline characters from the given input :return: A cleaned-up version of the input string :rtype: str """ try: data = data.replace('<t>', '') data = data.replace('</t>', '') da...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader._strip_tags
8,088
def _handle_lusubcorpus_elt(self, elt): """Load a subcorpus of a lexical unit from the given xml.""" sc = AttrDict() try: sc['name'] = elt.get('name') except __HOLE__: return None sc['_type'] = "lusubcorpus" sc['sentence'] = [] for sub in ...
AttributeError
dataset/ETHPy150Open nltk/nltk/nltk/corpus/reader/framenet.py/FramenetCorpusReader._handle_lusubcorpus_elt
8,089
def generate_data(self, count, offset): """ Generates training data in the CRF++ format for the ingredient tagging task """ df = pd.read_csv(self.opts.data_path) df = df.fillna("") start = int(offset) end = int(offset) + int(count) df_slice = df....
UnicodeDecodeError
dataset/ETHPy150Open NYTimes/ingredient-phrase-tagger/lib/training/cli.py/Cli.generate_data
8,090
def check_non_negative_int(value): try: value = int(value) except __HOLE__: raise argparse.ArgumentTypeError(_("invalid int value: %r") % value) if value < 0: raise argparse.ArgumentTypeError(_("input value %d is negative") % value) return...
ValueError
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/shell.py/check_non_negative_int
8,091
def _extend_shell_commands(self, name, module, version): classes = inspect.getmembers(module, inspect.isclass) for cls_name, cls in classes: if (issubclass(cls, client_extension.NeutronClientExtension) and hasattr(cls, 'shell_command')): cmd = cls.shell_co...
TypeError
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/shell.py/NeutronShell._extend_shell_commands
8,092
def run_subcommand(self, argv): subcommand = self.command_manager.find_command(argv) cmd_factory, cmd_name, sub_argv = subcommand cmd = cmd_factory(self, self.options) try: self.prepare_to_run_command(cmd) full_name = (cmd_name if self.int...
SystemExit
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/shell.py/NeutronShell.run_subcommand
8,093
def main(argv=sys.argv[1:]): try: return NeutronShell(NEUTRON_API_VERSION).run( list(map(encodeutils.safe_decode, argv))) except __HOLE__: print("... terminating neutron client", file=sys.stderr) return 130 except exc.NeutronClientException: return 1 except Ex...
KeyboardInterrupt
dataset/ETHPy150Open openstack/python-neutronclient/neutronclient/shell.py/main
8,094
def test_stress(repeat=1000): sdict = SortedDict((val, -val) for val in range(1000)) for rpt in range(repeat): action = random.choice(actions) action(sdict) try: sdict._check() except __HOLE__: print(action) raise start_len = len(sdi...
AssertionError
dataset/ETHPy150Open grantjenks/sorted_containers/tests/test_stress_sorteddict.py/test_stress
8,095
def rm_xmltag(statement): try: _t = statement.startswith(XMLTAG) except __HOLE__: statement = statement.decode("utf8") _t = statement.startswith(XMLTAG) if _t: statement = statement[len(XMLTAG):] if statement[0] == '\n': statement = statement[1:] elif...
TypeError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sigver.py/rm_xmltag
8,096
def get_xmlsec_binary(paths=None): """ Tries to find the xmlsec1 binary. :param paths: Non-system path paths which should be searched when looking for xmlsec1 :return: full name of the xmlsec1 binary found. If no binaries are found then an exception is raised. """ if os.name == ...
OSError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sigver.py/get_xmlsec_binary
8,097
def _make_vals(val, klass, seccont, klass_inst=None, prop=None, part=False, base64encode=False, elements_to_sign=None): """ Creates a class instance with a specified value, the specified class instance may be a value on a property in a defined class instance. :param val: The value :p...
ValueError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sigver.py/_make_vals
8,098
def active_cert(key): """ Verifies that a key is active that is present time is after not_before and before not_after. :param key: The Key :return: True if the key is active else False """ cert_str = pem_format(key) certificate = importKey(cert_str) try: not_before = to_time...
AssertionError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sigver.py/active_cert
8,099
def verify_redirect_signature(saml_msg, cert=None, sigkey=None): """ :param saml_msg: A dictionary with strings as values, *NOT* lists as produced by parse_qs. :param cert: A certificate to use when verifying the signature :return: True, if signature verified """ try: signer = SIGN...
KeyError
dataset/ETHPy150Open cloudera/hue/desktop/core/ext-py/pysaml2-2.4.0/src/saml2/sigver.py/verify_redirect_signature