Unnamed: 0
int64
0
10k
function
stringlengths
79
138k
label
stringclasses
20 values
info
stringlengths
42
261
2,100
def get_sections(self): SECTION_DIVIDER = '\f\n' sections = self.data.split(SECTION_DIVIDER) sections = [x for x in map(str.splitlines, sections)] try: # remove the SVN version number from the first line svn_version = int(sections[0].pop(0)) if not svn_version in self.known_svn_versions.values(): log.warn("Unknown subversion verson %d", svn_version) except __HOLE__: return self.sections = sections self.get_sections = self.__get_cached_sections return self.sections
ValueError
dataset/ETHPy150Open GeekTrainer/Flask/Work/Trivia - Module 5/env/Lib/site-packages/setuptools/svn_utils.py/SVNEntriesFileText.get_sections
2,101
def readme(): try: return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() except __HOLE__: return ''
IOError
dataset/ETHPy150Open vlasovskikh/convoread/setup.py/readme
2,102
def archive_month(request, year, month, queryset, date_field, allow_future=False, month_format='%b', **kwargs): try: date = datetime.date(*time.strptime(year+month, '%Y'+month_format)[:3]) except __HOLE__: raise Http404 now = datetime.datetime.now() # Calculate first and last day of month, for use in a date-range lookup. first_day = date.replace(day=1) if first_day.month == 12: last_day = first_day.replace(year=first_day.year + 1, month=1) else: last_day = first_day.replace(month=first_day.month + 1) lookup_kwargs = { '%s__gte' % date_field: first_day, '%s__lt' % date_field: last_day, } # Only bother to check current date if the month isn't in the past and future objects are requested. if last_day >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now queryset = queryset.filter(**lookup_kwargs).order_by('-' + date_field) return list_detail.object_list(request, queryset=queryset, **kwargs)
ValueError
dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_month
2,103
def archive_week(request, year, week, queryset, date_field, allow_future=False, **kwargs): try: date = datetime.date(*time.strptime(year+'-0-'+week, '%Y-%w-%U')[:3]) except __HOLE__: raise Http404 now = datetime.datetime.now() # Calculate first and last day of week, for use in a date-range lookup. first_day = date last_day = date + datetime.timedelta(days=7) lookup_kwargs = { '%s__gte' % date_field: first_day, '%s__lt' % date_field: last_day, } # Only bother to check current date if the week isn't in the past and future objects aren't requested. if last_day >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now queryset = queryset.filter(**lookup_kwargs).order_by('-' + date_field) return list_detail.object_list(request, queryset=queryset, **kwargs)
ValueError
dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_week
2,104
def archive_day(request, year, month, day, queryset, date_field, allow_future=False, month_format='%b', day_format='%d', **kwargs): try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except __HOLE__: raise Http404 model = queryset.model now = datetime.datetime.now() if isinstance(model._meta.get_field(date_field), DateTimeField): lookup_kwargs = {'%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} else: lookup_kwargs = {date_field: date} # Only bother to check current date if the date isn't in the past and future objects aren't requested. if date >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now queryset = queryset.filter(**lookup_kwargs).order_by('-' + date_field) return list_detail.object_list(request, queryset=queryset, **kwargs)
ValueError
dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/archive_day
2,105
def object_detail(request, year, month, day, queryset, date_field, allow_future=False, month_format='%b', day_format='%d', **kwargs): try: date = datetime.date(*time.strptime(year+month+day, '%Y'+month_format+day_format)[:3]) except __HOLE__: raise Http404 model = queryset.model now = datetime.datetime.now() if isinstance(model._meta.get_field(date_field), DateTimeField): lookup_kwargs = {'%s__range' % date_field: (datetime.datetime.combine(date, datetime.time.min), datetime.datetime.combine(date, datetime.time.max))} else: lookup_kwargs = {date_field: date} # Only bother to check current date if the date isn't in the past and future objects aren't requested. if date >= now.date() and not allow_future: lookup_kwargs['%s__lte' % date_field] = now queryset = queryset.filter(**lookup_kwargs).order_by('-' + date_field) return list_detail.object_detail(request, queryset=queryset, **kwargs)
ValueError
dataset/ETHPy150Open kylef-archive/lithium/lithium/views/date_based.py/object_detail
2,106
def checkout(self, url, version='', verbose=False, shallow=False, timeout=None): if url is None or url.strip() == '': raise ValueError('Invalid empty url : "%s"' % url) # make sure that the parent directory exists for #3497 base_path = os.path.split(self.get_path())[0] try: os.makedirs(base_path) except __HOLE__: # OSError thrown if directory already exists this is ok pass cmd = "hg clone %s %s" % (sanitized(url), self._path) value, _, msg = run_shell_command(cmd, shell=True, no_filter=True) if value != 0: if msg: sys.logger.error('%s' % msg) return False if version is not None and version.strip() != '': cmd = "hg checkout %s" % sanitized(version) value, _, msg = run_shell_command(cmd, cwd=self._path, shell=True, no_filter=True) if value != 0: if msg: sys.stderr.write('%s\n' % msg) return False return True
OSError
dataset/ETHPy150Open vcstools/vcstools/src/vcstools/hg.py/HgClient.checkout
2,107
def run(self, info): """ Set extended attributes on downloaded file (if xattr support is found). """ # This mess below finds the best xattr tool for the job and creates a # "write_xattr" function. try: # try the pyxattr module... import xattr def write_xattr(path, key, value): return xattr.setxattr(path, key, value) except ImportError: if os.name == 'nt': # Write xattrs to NTFS Alternate Data Streams: # http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29 def write_xattr(path, key, value): assert ':' not in key assert os.path.exists(path) ads_fn = path + ":" + key with open(ads_fn, "wb") as f: f.write(value) else: user_has_setfattr = check_executable("setfattr", ['--version']) user_has_xattr = check_executable("xattr", ['-h']) if user_has_setfattr or user_has_xattr: def write_xattr(path, key, value): if user_has_setfattr: cmd = ['setfattr', '-n', key, '-v', value, path] elif user_has_xattr: cmd = ['xattr', '-w', key, value, path] subprocess_check_output(cmd) else: # On Unix, and can't find pyxattr, setfattr, or xattr. if sys.platform.startswith('linux'): self._downloader.report_error( "Couldn't find a tool to set the xattrs. " "Install either the python 'pyxattr' or 'xattr' " "modules, or the GNU 'attr' package " "(which contains the 'setfattr' tool).") else: self._downloader.report_error( "Couldn't find a tool to set the xattrs. " "Install either the python 'xattr' module, " "or the 'xattr' binary.") # Write the metadata to the file's xattrs self._downloader.to_screen('[metadata] Writing metadata to file\'s xattrs') filename = info['filepath'] try: xattr_mapping = { 'user.xdg.referrer.url': 'webpage_url', # 'user.xdg.comment': 'description', 'user.dublincore.title': 'title', 'user.dublincore.date': 'upload_date', 'user.dublincore.description': 'description', 'user.dublincore.contributor': 'uploader', 'user.dublincore.format': 'format', } for xattrname, infoname in xattr_mapping.items(): value = info.get(infoname) if value: if infoname == "upload_date": value = hyphenate_date(value) byte_value = value.encode('utf-8') write_xattr(filename, xattrname, byte_value) return True, info except (subprocess.CalledProcessError, __HOLE__): self._downloader.report_error("This filesystem doesn't support extended attributes. (You may have to enable them in your /etc/fstab)") return False, info
OSError
dataset/ETHPy150Open yasoob/youtube-dl-GUI/youtube_dl/postprocessor/xattrpp.py/XAttrMetadataPP.run
2,108
def get_devices(self): try: return [IPDevice(iface) for iface in netifaces.interfaces()] except (__HOLE__, MemoryError): LOG.error(_LE("Failed to get network interfaces.")) return []
OSError
dataset/ETHPy150Open openstack/neutron/neutron/agent/windows/ip_lib.py/IPWrapper.get_devices
2,109
def device_has_ip(self, ip): try: device_addresses = netifaces.ifaddresses(self.device_name) except __HOLE__: # The device does not exist on the system return False try: addresses = [ip_addr['addr'] for ip_addr in device_addresses.get(netifaces.AF_INET, [])] return ip in addresses except OSError: LOG.error(_LE("Failed to get ip addresses for interface: %s."), self.device_name) return False
ValueError
dataset/ETHPy150Open openstack/neutron/neutron/agent/windows/ip_lib.py/IPDevice.device_has_ip
2,110
def _validate_recaptcha(self, response, remote_addr): """Performs the actual validation.""" try: private_key = current_app.config['RECAPTCHA_PRIVATE_KEY'] except __HOLE__: raise RuntimeError("No RECAPTCHA_PRIVATE_KEY config set") data = url_encode({ 'secret': private_key, 'remoteip': remote_addr, 'response': response }) http_response = http.urlopen(RECAPTCHA_VERIFY_SERVER, to_bytes(data)) if http_response.code != 200: return False json_resp = json.loads(to_unicode(http_response.read())) if json_resp["success"]: return True for error in json_resp.get("error-codes", []): if error in RECAPTCHA_ERROR_CODES: raise ValidationError(RECAPTCHA_ERROR_CODES[error]) return False
KeyError
dataset/ETHPy150Open lepture/flask-wtf/flask_wtf/recaptcha/validators.py/Recaptcha._validate_recaptcha
2,111
def perspectiveMessageReceived(self, broker, message, args, kw): """ This method is called when a network message is received. This will call:: self.perspective_%(message)s(*broker.unserialize(args), **broker.unserialize(kw)) to handle the method; subclasses of Avatar are expected to implement methods using this naming convention. """ args = broker.unserialize(args, self) kw = broker.unserialize(kw, self) method = getattr(self, "perspective_%s" % message) try: state = method(*args, **kw) except __HOLE__: log.msg("%s didn't accept %s and %s" % (method, args, kw)) raise return broker.serialize(state, self, method, args, kw)
TypeError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/spread/pb.py/Avatar.perspectiveMessageReceived
2,112
def dontNotifyOnDisconnect(self, notifier): """Remove a callback from list of disconnect callbacks.""" try: self.disconnects.remove(notifier) except __HOLE__: pass
ValueError
dataset/ETHPy150Open nlloyd/SubliminalCollaborator/libs/twisted/spread/pb.py/Broker.dontNotifyOnDisconnect
2,113
def validate_options(options): """Validates options.""" kwcase = options.get('keyword_case', None) if kwcase not in [None, 'upper', 'lower', 'capitalize']: raise SQLParseError('Invalid value for keyword_case: %r' % kwcase) idcase = options.get('identifier_case', None) if idcase not in [None, 'upper', 'lower', 'capitalize']: raise SQLParseError('Invalid value for identifier_case: %r' % idcase) ofrmt = options.get('output_format', None) if ofrmt not in [None, 'sql', 'python', 'php']: raise SQLParseError('Unknown output format: %r' % ofrmt) strip_comments = options.get('strip_comments', False) if strip_comments not in [True, False]: raise SQLParseError('Invalid value for strip_comments: %r' % strip_comments) strip_ws = options.get('strip_whitespace', False) if strip_ws not in [True, False]: raise SQLParseError('Invalid value for strip_whitespace: %r' % strip_ws) truncate_strings = options.get('truncate_strings', None) if truncate_strings is not None: try: truncate_strings = int(truncate_strings) except (__HOLE__, TypeError): raise SQLParseError('Invalid value for truncate_strings: %r' % truncate_strings) if truncate_strings <= 1: raise SQLParseError('Invalid value for truncate_strings: %r' % truncate_strings) options['truncate_strings'] = truncate_strings options['truncate_char'] = options.get('truncate_char', '[...]') reindent = options.get('reindent', False) if reindent not in [True, False]: raise SQLParseError('Invalid value for reindent: %r' % reindent) elif reindent: options['strip_whitespace'] = True indent_tabs = options.get('indent_tabs', False) if indent_tabs not in [True, False]: raise SQLParseError('Invalid value for indent_tabs: %r' % indent_tabs) elif indent_tabs: options['indent_char'] = '\t' else: options['indent_char'] = ' ' indent_width = options.get('indent_width', 2) try: indent_width = int(indent_width) except (TypeError, ValueError): raise SQLParseError('indent_width requires an integer') if indent_width < 1: raise SQLParseError('indent_width requires an positive integer') options['indent_width'] = indent_width right_margin = options.get('right_margin', None) if right_margin is not None: try: right_margin = int(right_margin) except (TypeError, ValueError): raise SQLParseError('right_margin requires an integer') if right_margin < 10: raise SQLParseError('right_margin requires an integer > 10') options['right_margin'] = right_margin return options
ValueError
dataset/ETHPy150Open andialbrecht/sqlparse/sqlparse/formatter.py/validate_options
2,114
def main(): import os.path import argparse from argparse import ArgumentParser opener = URLOpener() def get_spec(value): if value not in SPECS: raise argparse.ArgumentTypeError('Unknown specification') spec_cls = SPECS[value] if os.path.exists(value + '.xml'): logger.info('using local specification: \'%s.xml\'', value) return spec_cls.from_file(value + '.xml') logger.info('getting \'%s\' specification from SVN', value) return spec_cls.from_svn(opener=opener) def ext_file(value): msg = 'Invalid extensions argument' if os.path.exists(value): msg = 'Invalid extensions file' try: with open(value, 'r') as f: return f.read().split() except __HOLE__: pass else: return [v.strip() for v in value.split(',') if v] raise argparse.ArgumentTypeError(msg) def version(value): if value is None or len(value.strip()) == 0: return None v = value if '.' not in v: v = '{}.0'.format(v) try: return Version(*map(int, v.split('.'))) except ValueError: pass raise argparse.ArgumentTypeError('Invalid version: "{}"'.format(value)) def cmdapi(value): try: return dict((p[0], version(p[1])) for p in (list(map(str.strip, e.split('='))) for e in filter(bool, map(str.strip, value.split(','))))) except IndexError: pass raise argparse.ArgumentTypeError( 'Invalid api-string: "{}"'.format(value) ) description = __doc__ parser = ArgumentParser(description=description) parser.add_argument('--profile', dest='profile', choices=['core', 'compatibility'], default='compatibility', help='OpenGL profile (defaults to compatibility)') parser.add_argument('--out-path', dest='out', required=True, help='Output path for loader') parser.add_argument('--api', dest='api', type=cmdapi, help='API type/version pairs, like "gl=3.2,gles=", ' 'no version means latest') parser.add_argument('--generator', dest='generator', default='d', choices=['c', 'c-debug', 'd', 'nim', 'volt'], required=True, help='Language to generate the binding for') parser.add_argument('--extensions', dest='extensions', default=None, type=ext_file, help='Path to extensions file or comma separated ' 'list of extensions, if missing ' 'all extensions are included') parser.add_argument('--spec', dest='spec', default='gl', choices=['gl', 'egl', 'glx', 'wgl'], help='Name of the spec') parser.add_argument('--no-loader', dest='no_loader', action='store_true') parser.add_argument('--quiet', dest='quiet', action='store_true') ns = parser.parse_args() if not ns.quiet: logging.basicConfig( format='[%(asctime)s][%(levelname)s\t][%(name)-7s\t]: %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.DEBUG ) spec = get_spec(ns.spec) if spec.NAME == 'gl': spec.profile = ns.profile api = ns.api if api is None or len(api.keys()) == 0: api = {spec.NAME: None} generator_cls, loader_cls = glad.lang.get_generator( ns.generator, spec.NAME.lower() ) if loader_cls is None: return parser.error('API/Spec not yet supported') loader = loader_cls(api) loader.disabled = ns.no_loader logger.info('generating \'%s\' bindings', spec.NAME) with generator_cls(ns.out, spec, api, ns.extensions, loader=loader, opener=opener) as generator: generator.generate() logger.info('generating \'%s\' bindings - done', spec.NAME)
IOError
dataset/ETHPy150Open Dav1dde/glad/glad/__main__.py/main
2,115
def get(self, key, default=None): try: return self[key] except __HOLE__: return default
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/Mapping.get
2,116
def __contains__(self, key): try: self[key] except __HOLE__: return False else: return True
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/Mapping.__contains__
2,117
def pop(self, key, default=__marker): try: value = self[key] except __HOLE__: if default is self.__marker: raise return default else: del self[key] return value
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.pop
2,118
def popitem(self): try: key = next(iter(self)) except __HOLE__: raise KeyError value = self[key] del self[key] return key, value
StopIteration
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.popitem
2,119
def clear(self): try: while True: self.popitem() except __HOLE__: pass
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.clear
2,120
def setdefault(self, key, default=None): try: return self[key] except __HOLE__: self[key] = default return default
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MutableMapping.setdefault
2,121
def extend(self, elem_seq): """Extends by appending the given iterable. Similar to list.extend().""" if elem_seq is None: return try: elem_seq_iter = iter(elem_seq) except __HOLE__: if not elem_seq: # silently ignore falsy inputs :-/. # TODO(ptucker): Deprecate this behavior. b/18413862 return raise new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter] if new_values: self._values.extend(new_values) self._message_listener.Modified()
TypeError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/RepeatedScalarFieldContainer.extend
2,122
def __getitem__(self, key): try: return self._values[key] except __HOLE__: key = self._key_checker.CheckValue(key) val = self._value_checker.DefaultValue() self._values[key] = val return val
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/ScalarMap.__getitem__
2,123
def __getitem__(self, key): try: return self._values[key] except __HOLE__: key = self._key_checker.CheckValue(key) new_element = self._message_descriptor._concrete_class() new_element._SetListener(self._message_listener) self._values[key] = new_element self._message_listener.Modified() return new_element
KeyError
dataset/ETHPy150Open sklearn-theano/sklearn-theano/sklearn_theano/externals/google/protobuf/internal/containers.py/MessageMap.__getitem__
2,124
def peek(self, index=0): try: return self.buffer[self.pointer + index] except __HOLE__: self.update(index + 1) return self.buffer[self.pointer + index]
IndexError
dataset/ETHPy150Open powerline/powerline/powerline/lint/markedjson/reader.py/Reader.peek
2,125
def update(self, length): if self.raw_buffer is None: return self.buffer = self.buffer[self.pointer:] self.pointer = 0 while len(self.buffer) < length: if not self.eof: self.update_raw() try: data, converted = self.raw_decode(self.raw_buffer, 'strict', self.eof) except __HOLE__ as exc: character = self.raw_buffer[exc.start] position = self.stream_pointer - len(self.raw_buffer) + exc.start data, converted = self.raw_decode(self.raw_buffer[:exc.start], 'strict', self.eof) self.buffer += data self.full_buffer += data + '<' + str(ord(character)) + '>' self.raw_buffer = self.raw_buffer[converted:] self.update_pointer(exc.start - 1) raise ReaderError( 'while reading from stream', None, 'found character #x%04x that cannot be decoded by UTF-8 codec' % ord(character), Mark(self.name, self.line, self.column, self.full_buffer, position) ) self.buffer += data self.full_buffer += data self.raw_buffer = self.raw_buffer[converted:] self.check_printable(data) if self.eof: self.buffer += '\0' self.raw_buffer = None break
UnicodeDecodeError
dataset/ETHPy150Open powerline/powerline/powerline/lint/markedjson/reader.py/Reader.update
2,126
def StopDaemon(self, require_running=True): """Stops any currently running daemon process on the system.""" current_pid = self._get_current_pid() if require_running and current_pid is None: raise DaemonError('Daemon process was not running.') try: os.kill(current_pid, signal.SIGTERM) except __HOLE__, exc: raise DaemonError('Failed to stop daemon process %d: %s' % (current_pid, exc))
OSError
dataset/ETHPy150Open viewfinderco/viewfinder/backend/base/daemon.py/DaemonManager.StopDaemon
2,127
def _get_current_pid(self): """Get the process ID of any currently running daemon process. Returns None if no process is running. """ current_pid = None if self.lockfile.is_locked(): current_pid = self.lockfile.read_pid() if current_pid is not None: try: # A 0 signal will do nothing if the process exists. os.kill(current_pid, 0) except __HOLE__, exc: if exc.errno == errno.ESRCH: # PID file was stale, delete it. current_pid = None self.lockfile.break_lock() return current_pid
OSError
dataset/ETHPy150Open viewfinderco/viewfinder/backend/base/daemon.py/DaemonManager._get_current_pid
2,128
def forwards(self, orm): "Write your forwards methods here." try: role = orm["auth.Group"].objects.get(name="Test Manager") perm = orm["auth.Permission"].objects.get(codename="manage_products") except __HOLE__: pass else: role.permissions.add(perm)
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/moztrap/moztrap/model/core/migrations/0005_add_manage_products_permission_for_test_managers.py/Migration.forwards
2,129
def __init__(self, resp=None): self.scope = [] self.token_expiration_time = 0 self.access_token = None self.refresh_token = None self.token_type = None self.replaced = False if resp: for prop, val in resp.items(): setattr(self, prop, val) try: _expires_in = resp["expires_in"] except __HOLE__: return if _expires_in: _tet = utc_time_sans_frac() + int(_expires_in) else: _tet = 0 self.token_expiration_time = int(_tet)
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oauth2/grant.py/Token.__init__
2,130
def add_code(self, resp): try: self.code = resp["code"] self.grant_expiration_time = utc_time_sans_frac() + self.exp_in except __HOLE__: pass
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/oauth2/grant.py/Grant.add_code
2,131
def ParseArguments(argv): """Parses command-line arguments. Args: argv: Command-line arguments, including the executable name, used to execute this application. Returns: Tuple (args, option_dict) where: args: List of command-line arguments following the executable name. option_dict: Dictionary of parsed flags that maps keys from DEFAULT_ARGS to their values, which are either pulled from the defaults, or from command-line flags. """ option_dict = DEFAULT_ARGS.copy() try: opts, args = getopt.gnu_getopt( argv[1:], 'a:cdhp:', [ 'address=', 'admin_console_server=', 'admin_console_host=', 'allow_skipped_files', 'auth_domain=', 'clear_datastore', 'blobstore_path=', 'datastore_path=', 'debug', 'debug_imports', 'enable_sendmail', 'disable_static_caching', 'show_mail_body', 'help', 'history_path=', 'port=', 'require_indexes', 'smtp_host=', 'smtp_password=', 'smtp_port=', 'smtp_user=', 'template_dir=', 'trusted', ]) except getopt.GetoptError, e: print >>sys.stderr, 'Error: %s' % e PrintUsageExit(1) for option, value in opts: if option in ('-h', '--help'): PrintUsageExit(0) if option in ('-d', '--debug'): option_dict[ARG_LOG_LEVEL] = logging.DEBUG if option in ('-p', '--port'): try: option_dict[ARG_PORT] = int(value) if not (65535 > option_dict[ARG_PORT] > 0): raise ValueError except ValueError: print >>sys.stderr, 'Invalid value supplied for port' PrintUsageExit(1) if option in ('-a', '--address'): option_dict[ARG_ADDRESS] = value if option == '--blobstore_path': option_dict[ARG_BLOBSTORE_PATH] = os.path.abspath(value) if option == '--datastore_path': option_dict[ARG_DATASTORE_PATH] = os.path.abspath(value) if option == '--history_path': option_dict[ARG_HISTORY_PATH] = os.path.abspath(value) if option in ('-c', '--clear_datastore'): option_dict[ARG_CLEAR_DATASTORE] = True if option == '--require_indexes': option_dict[ARG_REQUIRE_INDEXES] = True if option == '--smtp_host': option_dict[ARG_SMTP_HOST] = value if option == '--smtp_port': try: option_dict[ARG_SMTP_PORT] = int(value) if not (65535 > option_dict[ARG_SMTP_PORT] > 0): raise ValueError except __HOLE__: print >>sys.stderr, 'Invalid value supplied for SMTP port' PrintUsageExit(1) if option == '--smtp_user': option_dict[ARG_SMTP_USER] = value if option == '--smtp_password': option_dict[ARG_SMTP_PASSWORD] = value if option == '--enable_sendmail': option_dict[ARG_ENABLE_SENDMAIL] = True if option == '--show_mail_body': option_dict[ARG_SHOW_MAIL_BODY] = True if option == '--auth_domain': option_dict['_DEFAULT_ENV_AUTH_DOMAIN'] = value if option == '--debug_imports': option_dict['_ENABLE_LOGGING'] = True if option == '--template_dir': option_dict[ARG_TEMPLATE_DIR] = value if option == '--admin_console_server': option_dict[ARG_ADMIN_CONSOLE_SERVER] = value.strip() if option == '--admin_console_host': option_dict[ARG_ADMIN_CONSOLE_HOST] = value if option == '--allow_skipped_files': option_dict[ARG_ALLOW_SKIPPED_FILES] = True if option == '--disable_static_caching': option_dict[ARG_STATIC_CACHING] = False if option == '--trusted': option_dict[ARG_TRUSTED] = True return args, option_dict
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_main.py/ParseArguments
2,132
def main(argv): """Runs the development application server.""" args, option_dict = ParseArguments(argv) if len(args) != 1: print >>sys.stderr, 'Invalid arguments' PrintUsageExit(1) root_path = args[0] if '_DEFAULT_ENV_AUTH_DOMAIN' in option_dict: auth_domain = option_dict['_DEFAULT_ENV_AUTH_DOMAIN'] dev_appserver.DEFAULT_ENV['AUTH_DOMAIN'] = auth_domain if '_ENABLE_LOGGING' in option_dict: enable_logging = option_dict['_ENABLE_LOGGING'] dev_appserver.HardenedModulesHook.ENABLE_LOGGING = enable_logging log_level = option_dict[ARG_LOG_LEVEL] port = option_dict[ARG_PORT] blobstore_path = option_dict[ARG_BLOBSTORE_PATH] datastore_path = option_dict[ARG_DATASTORE_PATH] login_url = option_dict[ARG_LOGIN_URL] template_dir = option_dict[ARG_TEMPLATE_DIR] serve_address = option_dict[ARG_ADDRESS] require_indexes = option_dict[ARG_REQUIRE_INDEXES] allow_skipped_files = option_dict[ARG_ALLOW_SKIPPED_FILES] static_caching = option_dict[ARG_STATIC_CACHING] option_dict['root_path'] = os.path.realpath(root_path) logging.getLogger().setLevel(log_level) config = None try: config, matcher = dev_appserver.LoadAppConfig(root_path, {}) except yaml_errors.EventListenerError, e: logging.error('Fatal error when loading application configuration:\n' + str(e)) return 1 except dev_appserver.InvalidAppConfigError, e: logging.error('Application configuration file invalid:\n%s', e) return 1 if option_dict[ARG_ADMIN_CONSOLE_SERVER] != '': server = MakeRpcServer(option_dict) update_check = appcfg.UpdateCheck(server, config) update_check.CheckSupportedVersion() if update_check.AllowedToCheckForUpdates(): update_check.CheckForUpdates() try: dev_appserver.SetupStubs(config.application, **option_dict) except: exc_type, exc_value, exc_traceback = sys.exc_info() logging.error(str(exc_type) + ': ' + str(exc_value)) logging.debug(''.join(traceback.format_exception( exc_type, exc_value, exc_traceback))) return 1 http_server = dev_appserver.CreateServer( root_path, login_url, port, template_dir, sdk_dir=SDK_PATH, serve_address=serve_address, require_indexes=require_indexes, allow_skipped_files=allow_skipped_files, static_caching=static_caching) signal.signal(signal.SIGTERM, SigTermHandler) logging.info('Running application %s on port %d: http://%s:%d', config.application, port, serve_address, port) try: try: http_server.serve_forever() except __HOLE__: logging.info('Server interrupted by user, terminating') except: exc_info = sys.exc_info() info_string = '\n'.join(traceback.format_exception(*exc_info)) logging.error('Error encountered:\n%s\nNow terminating.', info_string) return 1 finally: http_server.server_close() return 0
KeyboardInterrupt
dataset/ETHPy150Open CollabQ/CollabQ/.google_appengine/google/appengine/tools/dev_appserver_main.py/main
2,133
def handle_label(self, app_name, directory=None, **options): if directory is None: directory = os.getcwd() # Determine the project_name by using the basename of directory, # which should be the full path of the project directory (or the # current directory if no directory was passed). project_name = os.path.basename(directory) if app_name == project_name: raise CommandError("You cannot create an app with the same name" " (%r) as your project." % app_name) # Check that the app_name cannot be imported. try: import_module(app_name) except __HOLE__: pass else: raise CommandError("%r conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name." % app_name) copy_helper(self.style, 'app', app_name, directory, project_name)
ImportError
dataset/ETHPy150Open AppScale/appscale/AppServer/google/appengine/_internal/django/core/management/commands/startapp.py/Command.handle_label
2,134
def get_index_tags(self, index, results, index_tags, column_tags): ''' Gather the tags for this row of the table (index) based on the results (all the results from the query). index_tags and column_tags are the tags to gather. - Those specified in index_tags contain the tag_group name and the index of the value we want to extract from the index tuple. cf. 1 for ipVersion in the IP-MIB::ipSystemStatsTable for example - Those specified in column_tags contain the name of a column, which could be a potential result, to use as a tage cf. ifDescr in the IF-MIB::ifTable for example ''' tags = [] for idx_tag in index_tags: tag_group = idx_tag[0] try: tag_value = index[idx_tag[1] - 1].prettyPrint() except IndexError: self.log.warning("Not enough indexes, skipping this tag") continue tags.append("{0}:{1}".format(tag_group, tag_value)) for col_tag in column_tags: tag_group = col_tag[0] try: tag_value = results[col_tag[1]][index] except __HOLE__: self.log.warning("Column %s not present in the table, skipping this tag", col_tag[1]) continue if reply_invalid(tag_value): self.log.warning("Can't deduct tag from column for tag %s", tag_group) continue tag_value = tag_value.prettyPrint() tags.append("{0}:{1}".format(tag_group, tag_value)) return tags
KeyError
dataset/ETHPy150Open serverdensity/sd-agent/checks.d/snmp.py/SnmpCheck.get_index_tags
2,135
def stream_in(p, data): """ Streams to dat from the given command into python Parameters ---------- cmd: str the command to execute parse: boolean TODO: if true, will try to parse the output from python generator or list """ if isinstance(data, str): data = data.encode() stdout, stderr = p.communicate(input=data) if p.returncode == 1: raise DatException('Node.js error: ' + stderr) elif p.returncode == 127: raise DatException("It looks like `dat` commandline is missing from PATH.\n", "Are you sure you installed it?\n" "Check http://dat-data.com for instructions") else: try: res = json.loads(stdout.decode()) if type(res) == dict and res.get('error'): return on_error(res) except __HOLE__: res = {'stdout': stdout, 'stderr': stderr} return res
ValueError
dataset/ETHPy150Open karissa/datpy/datpy.py/stream_in
2,136
def stream_out(p, parse=True): """ Streams the stdout from the given command into python Parameters ---------- cmd: str the command to execute parse: boolean to parse the file into json """ res = [] for line in iter(p.stdout.readline, b''): try: line = line.decode() if parse: line = json.loads(line.rstrip()) except __HOLE__: line = pickle.loads(line) parse = True res.append(line) if len(res) == 1: res = res[0] if type(res) == dict and res.get('error'): return on_error(res) if not parse: res = ''.join(res) subprocess.Popen.terminate(p) return res
UnicodeDecodeError
dataset/ETHPy150Open karissa/datpy/datpy.py/stream_out
2,137
@classmethod def bench(cls, text, loops=1000): print('Parsing the Markdown Syntax document %d times...' % loops) for name, func in cls.suites: try: total = func(text, loops=loops) print('{0}: {1}'.format(name, total)) except __HOLE__: print('{0} is not available'.format(name))
ImportError
dataset/ETHPy150Open MikeCoder/markdown-preview.vim/pythonx/tests/bench.py/benchmark.bench
2,138
def get_output(self, cmd): try: process = subprocess.Popen(cmd, stdout=subprocess.PIPE) except (__HOLE__, EnvironmentError): # can't use FileNotFoundError in Python 2 return False out, err = process.communicate() return out
OSError
dataset/ETHPy150Open richrd/suplemon/suplemon/modules/system_clipboard.py/SystemClipboard.get_output
2,139
def _addressed(nick, msg, prefixChars=None, nicks=None, prefixStrings=None, whenAddressedByNick=None, whenAddressedByNickAtEnd=None): def get(group): if ircutils.isChannel(target): group = group.get(target) return group() def stripPrefixStrings(payload): for prefixString in prefixStrings: if payload.startswith(prefixString): payload = payload[len(prefixString):].lstrip() return payload assert msg.command == 'PRIVMSG' (target, payload) = msg.args if not payload: return '' if prefixChars is None: prefixChars = get(conf.supybot.reply.whenAddressedBy.chars) if whenAddressedByNick is None: whenAddressedByNick = get(conf.supybot.reply.whenAddressedBy.nick) if whenAddressedByNickAtEnd is None: r = conf.supybot.reply.whenAddressedBy.nick.atEnd whenAddressedByNickAtEnd = get(r) if prefixStrings is None: prefixStrings = get(conf.supybot.reply.whenAddressedBy.strings) # We have to check this before nicks -- try "@google supybot" with supybot # and whenAddressedBy.nick.atEnd on to see why. if any(payload.startswith, prefixStrings): return stripPrefixStrings(payload) elif payload[0] in prefixChars: return payload[1:].strip() if nicks is None: nicks = get(conf.supybot.reply.whenAddressedBy.nicks) nicks = list(map(ircutils.toLower, nicks)) else: nicks = list(nicks) # Just in case. nicks.insert(0, ircutils.toLower(nick)) # Ok, let's see if it's a private message. if ircutils.nickEqual(target, nick): payload = stripPrefixStrings(payload) while payload and payload[0] in prefixChars: payload = payload[1:].lstrip() return payload # Ok, not private. Does it start with our nick? elif whenAddressedByNick: for nick in nicks: lowered = ircutils.toLower(payload) if lowered.startswith(nick): try: (maybeNick, rest) = payload.split(None, 1) toContinue = False while not ircutils.isNick(maybeNick, strictRfc=True): if maybeNick[-1].isalnum(): toContinue = True break maybeNick = maybeNick[:-1] if toContinue: continue if ircutils.nickEqual(maybeNick, nick): return rest else: continue except __HOLE__: # split didn't work. continue elif whenAddressedByNickAtEnd and lowered.endswith(nick): rest = payload[:-len(nick)] possiblePayload = rest.rstrip(' \t,;') if possiblePayload != rest: # There should be some separator between the nick and the # previous alphanumeric character. return possiblePayload if get(conf.supybot.reply.whenNotAddressed): return payload else: return ''
ValueError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/_addressed
2,140
def tokenize(s, channel=None): """A utility function to create a Tokenizer and tokenize a string.""" pipe = False brackets = '' nested = conf.supybot.commands.nested if nested(): brackets = conf.get(nested.brackets, channel) if conf.get(nested.pipeSyntax, channel): # No nesting, no pipe. pipe = True quotes = conf.get(conf.supybot.commands.quotes, channel) try: ret = Tokenizer(brackets=brackets,pipe=pipe,quotes=quotes).tokenize(s) return ret except __HOLE__ as e: raise SyntaxError(str(e))
ValueError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/tokenize
2,141
def checkCommandCapability(msg, cb, commandName): if not isinstance(commandName, minisix.string_types): commandName = '.'.join(commandName) plugin = cb.name().lower() pluginCommand = '%s.%s' % (plugin, commandName) def checkCapability(capability): assert ircdb.isAntiCapability(capability) if ircdb.checkCapability(msg.prefix, capability): log.info('Preventing %s from calling %s because of %s.', msg.prefix, pluginCommand, capability) raise RuntimeError(capability) try: antiPlugin = ircdb.makeAntiCapability(plugin) antiCommand = ircdb.makeAntiCapability(commandName) antiPluginCommand = ircdb.makeAntiCapability(pluginCommand) checkCapability(antiPlugin) checkCapability(antiCommand) checkCapability(antiPluginCommand) checkAtEnd = [commandName, pluginCommand] default = conf.supybot.capabilities.default() if ircutils.isChannel(msg.args[0]): channel = msg.args[0] checkCapability(ircdb.makeChannelCapability(channel, antiCommand)) checkCapability(ircdb.makeChannelCapability(channel, antiPlugin)) checkCapability(ircdb.makeChannelCapability(channel, antiPluginCommand)) chanPlugin = ircdb.makeChannelCapability(channel, plugin) chanCommand = ircdb.makeChannelCapability(channel, commandName) chanPluginCommand = ircdb.makeChannelCapability(channel, pluginCommand) checkAtEnd += [chanCommand, chanPlugin, chanPluginCommand] default &= ircdb.channels.getChannel(channel).defaultAllow return not (default or \ any(lambda x: ircdb.checkCapability(msg.prefix, x), checkAtEnd)) except __HOLE__ as e: s = ircdb.unAntiCapability(str(e)) return s
RuntimeError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/checkCommandCapability
2,142
def errorNoCapability(self, capability, s='', **kwargs): if 'Raise' not in kwargs: kwargs['Raise'] = True log.warning('Denying %s for lacking %q capability.', self.msg.prefix, capability) # noCapability means "don't send a specific capability error # message" not "don't send a capability error message at all", like # one would think if self._getConfig(conf.supybot.reply.error.noCapability) or \ capability in conf.supybot.capabilities.private(): v = self._getConfig(conf.supybot.replies.genericNoCapability) else: v = self._getConfig(conf.supybot.replies.noCapability) try: v %= capability except __HOLE__: # No %s in string pass s = self.__makeReply(v, s) if s: return self._error(s, **kwargs)
TypeError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/RichReplyMethods.errorNoCapability
2,143
def errorNoUser(self, s='', name='that user', **kwargs): if 'Raise' not in kwargs: kwargs['Raise'] = True v = self._getConfig(conf.supybot.replies.noUser) try: v = v % name except __HOLE__: log.warning('supybot.replies.noUser should have one "%s" in it.') return self._error(self.__makeReply(v, s), **kwargs)
TypeError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/RichReplyMethods.errorNoUser
2,144
def reply(self, s, noLengthCheck=False, prefixNick=None, action=None, private=None, notice=None, to=None, msg=None, sendImmediately=False): """ Keyword arguments: * `noLengthCheck=False`: True if the length shouldn't be checked (used for 'more' handling) * `prefixNick=True`: False if the nick shouldn't be prefixed to the reply. * `action=False`: True if the reply should be an action. * `private=False`: True if the reply should be in private. * `notice=False`: True if the reply should be noticed when the bot is configured to do so. * `to=<nick|channel>`: The nick or channel the reply should go to. Defaults to msg.args[0] (or msg.nick if private) * `sendImmediately=False`: True if the reply should use sendMsg() which bypasses conf.supybot.protocols.irc.throttleTime and gets sent before any queued messages """ # These use and or or based on whether or not they default to True or # False. Those that default to True use and; those that default to # False use or. assert not isinstance(s, ircmsgs.IrcMsg), \ 'Old code alert: there is no longer a "msg" argument to reply.' self.repliedTo = True if sendImmediately: sendMsg = self.irc.sendMsg else: sendMsg = self.irc.queueMsg if msg is None: msg = self.msg if prefixNick is not None: self.prefixNick = prefixNick if action is not None: self.action = self.action or action if action: self.prefixNick = False if notice is not None: self.notice = self.notice or notice if private is not None: self.private = self.private or private if to is not None: self.to = self.to or to # action=True implies noLengthCheck=True and prefixNick=False self.noLengthCheck=noLengthCheck or self.noLengthCheck or self.action target = self.private and self.to or self.msg.args[0] if not isinstance(s, minisix.string_types): # avoid trying to str() unicode s = str(s) # Allow non-string esses. if self.finalEvaled: try: if isinstance(self.irc, self.__class__): s = s[:conf.supybot.reply.maximumLength()] return self.irc.reply(s, to=self.to, notice=self.notice, action=self.action, private=self.private, prefixNick=self.prefixNick, noLengthCheck=self.noLengthCheck) elif self.noLengthCheck: # noLengthCheck only matters to NestedCommandsIrcProxy, so # it's not used here. Just in case you were wondering. m = reply(msg, s, to=self.to, notice=self.notice, action=self.action, private=self.private, prefixNick=self.prefixNick) sendMsg(m) return m else: s = ircutils.safeArgument(s) allowedLength = conf.get(conf.supybot.reply.mores.length, target) if not allowedLength: # 0 indicates this. allowedLength = 470 - len(self.irc.prefix) allowedLength -= len(msg.nick) # The '(XX more messages)' may have not the same # length in the current locale allowedLength -= len(_('(XX more messages)')) maximumMores = conf.get(conf.supybot.reply.mores.maximum, target) maximumLength = allowedLength * maximumMores if len(s) > maximumLength: log.warning('Truncating to %s bytes from %s bytes.', maximumLength, len(s)) s = s[:maximumLength] s_too_long = len(s.encode()) < allowedLength \ if minisix.PY3 else len(s) < allowedLength if s_too_long or \ not conf.get(conf.supybot.reply.mores, target): # In case we're truncating, we add 20 to allowedLength, # because our allowedLength is shortened for the # "(XX more messages)" trailer. if minisix.PY3: appended = _('(XX more messages)').encode() s = s.encode()[:allowedLength+len(appended)] s = s.decode('utf8', 'ignore') else: appended = _('(XX more messages)') s = s[:allowedLength+len(appended)] # There's no need for action=self.action here because # action implies noLengthCheck, which has already been # handled. Let's stick an assert in here just in case. assert not self.action m = reply(msg, s, to=self.to, notice=self.notice, private=self.private, prefixNick=self.prefixNick) sendMsg(m) return m msgs = ircutils.wrap(s, allowedLength, break_long_words=True) msgs.reverse() instant = conf.get(conf.supybot.reply.mores.instant,target) while instant > 1 and msgs: instant -= 1 response = msgs.pop() m = reply(msg, response, to=self.to, notice=self.notice, private=self.private, prefixNick=self.prefixNick) sendMsg(m) # XXX We should somehow allow these to be returned, but # until someone complains, we'll be fine :) We # can't return from here, though, for obvious # reasons. # return m if not msgs: return response = msgs.pop() if msgs: if len(msgs) == 1: more = _('more message') else: more = _('more messages') n = ircutils.bold('(%i %s)' % (len(msgs), more)) response = '%s %s' % (response, n) prefix = msg.prefix if self.to and ircutils.isNick(self.to): try: state = self.getRealIrc().state prefix = state.nickToHostmask(self.to) except __HOLE__: pass # We'll leave it as it is. mask = prefix.split('!', 1)[1] self._mores[mask] = msgs public = ircutils.isChannel(msg.args[0]) private = self.private or not public self._mores[msg.nick] = (private, msgs) m = reply(msg, response, to=self.to, action=self.action, notice=self.notice, private=self.private, prefixNick=self.prefixNick) sendMsg(m) return m finally: self._resetReplyAttributes() else: if msg.ignored: # Since the final reply string is constructed via # ' '.join(self.args), the args index for ignored commands # needs to be popped to avoid extra spaces in the final reply. self.args.pop(self.counter) msg.tag('ignored', False) else: self.args[self.counter] = s self.evalArgs()
KeyError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/NestedCommandsIrcProxy.reply
2,145
def userValue(self, name, prefixOrName, default=None): try: id = str(ircdb.users.getUserId(prefixOrName)) except __HOLE__: return None plugin = self.name() group = conf.users.plugins.get(plugin) names = registry.split(name) for name in names: group = group.get(name) return group.get(id)()
KeyError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/PluginMixin.userValue
2,146
def setUserValue(self, name, prefixOrName, value, ignoreNoUser=True, setValue=True): try: id = str(ircdb.users.getUserId(prefixOrName)) except __HOLE__: if ignoreNoUser: return else: raise plugin = self.name() group = conf.users.plugins.get(plugin) names = registry.split(name) for name in names: group = group.get(name) group = group.get(id) if setValue: group.setValue(value) else: group.set(value)
KeyError
dataset/ETHPy150Open ProgVal/Limnoria/src/callbacks.py/PluginMixin.setUserValue
2,147
def find_template(self, name, context, peeking=False): """ Replacement for Django's ``find_template`` that uses the current template context to keep track of which template directories it has used when finding a template. This allows multiple templates with the same relative name/path to be discovered, so that circular template inheritance can occur. """ # These imports want settings, which aren't available when this # module is imported to ``add_to_builtins``, so do them here. from django.conf import settings # Find the app_template_dirs (moved in Django 1.8) import django.template.loaders.app_directories as app_directories try: # Django >= 1.8 get_app_template_dirs = app_directories.get_app_template_dirs app_template_dirs = get_app_template_dirs('templates') except AttributeError: # Django <= 1.7 app_template_dirs = app_directories.app_template_dirs # Find the find_template_loader function, and appropriate template # settings (changed in Django 1.8) try: # Django >= 1.8 find_template_loader = context.template.engine.find_template_loader template_dirs = context.template.engine.dirs template_loaders = context.template.engine.loaders except __HOLE__: # Django <= 1.7 from django.template.loader import find_template_loader template_dirs = list(settings.TEMPLATE_DIRS) template_loaders = settings.TEMPLATE_LOADERS # Store a dictionary in the template context mapping template # names to the lists of template directories available to # search for that template. Each time a template is loaded, its # origin directory is removed from its directories list. context_name = "OVEREXTENDS_DIRS" if context_name not in context: context[context_name] = {} if name not in context[context_name]: all_dirs = template_dirs + list(app_template_dirs) # os.path.abspath is needed under uWSGI, and also ensures we # have consistent path separators across different OSes. context[context_name][name] = list(map(os.path.abspath, all_dirs)) # Build a list of template loaders to use. For loaders that wrap # other loaders like the ``cached`` template loader, unwind its # internal loaders and add those instead. loaders = [] for loader_name in template_loaders: loader = find_template_loader(loader_name) loaders.extend(getattr(loader, "loaders", [loader])) # Go through the loaders and try to find the template. When # found, removed its absolute path from the context dict so # that it won't be used again when the same relative name/path # is requested. for loader in loaders: dirs = context[context_name][name] if not dirs: break try: source, path = loader.load_template_source(name, dirs) except TemplateDoesNotExist: pass else: # Only remove the absolute path for the initial call in # get_parent, and not when we're peeking during the # second call. if not peeking: remove_path = os.path.abspath(path[:-len(name) - 1]) context[context_name][name].remove(remove_path) return Template(source) raise TemplateDoesNotExist(name)
AttributeError
dataset/ETHPy150Open stephenmcd/django-overextends/overextends/templatetags/overextends_tags.py/OverExtendsNode.find_template
2,148
def checkFilingDTS(val, modelDocument, isEFM, isGFM, visited): global targetNamespaceDatePattern, efmFilenamePattern, htmlFileNamePattern, roleTypePattern, arcroleTypePattern, \ arcroleDefinitionPattern, namePattern, linkroleDefinitionBalanceIncomeSheet, \ namespacesConflictPattern if targetNamespaceDatePattern is None: targetNamespaceDatePattern = re.compile(r"/([12][0-9]{3})-([01][0-9])-([0-3][0-9])|" r"/([12][0-9]{3})([01][0-9])([0-3][0-9])|") efmFilenamePattern = re.compile(r"^[a-z0-9][a-zA-Z0-9_\.\-]*(\.xsd|\.xml|\.htm)$") htmlFileNamePattern = re.compile(r"^[a-zA-Z0-9][._a-zA-Z0-9-]*(\.htm)$") roleTypePattern = re.compile(r"^.*/role/[^/\s]+$") arcroleTypePattern = re.compile(r"^.*/arcrole/[^/\s]+$") arcroleDefinitionPattern = re.compile(r"^.*[^\\s]+.*$") # at least one non-whitespace character namePattern = re.compile("[][()*+?\\\\/^{}|@#%^=~`\"';:,<>&$\u00a3\u20ac]") # u20ac=Euro, u00a3=pound sterling linkroleDefinitionBalanceIncomeSheet = re.compile(r"[^-]+-\s+Statement\s+-\s+.*(income|balance|financial\W+position)", re.IGNORECASE) namespacesConflictPattern = re.compile(r"http://(xbrl\.us|fasb\.org|xbrl\.sec\.gov)/(dei|us-types|us-roles|rr)/([0-9]{4}-[0-9]{2}-[0-9]{2})$") nonDomainItemNameProblemPattern = re.compile( r"({0})|(FirstQuarter|SecondQuarter|ThirdQuarter|FourthQuarter|[1-4]Qtr|Qtr[1-4]|ytd|YTD|HalfYear)(?:$|[A-Z\W])" .format(re.sub(r"\W", "", (val.entityRegistrantName or "").title()))) visited.append(modelDocument) for referencedDocument, modelDocumentReference in modelDocument.referencesDocument.items(): #6.07.01 no includes if modelDocumentReference.referenceType == "include": val.modelXbrl.error(("EFM.6.07.01", "GFM.1.03.01"), _("Taxonomy schema %(schema)s includes %(include)s, only import is allowed"), modelObject=modelDocumentReference.referringModelObject, schema=os.path.basename(modelDocument.uri), include=os.path.basename(referencedDocument.uri)) if referencedDocument not in visited and referencedDocument.inDTS: # ignore EdgarRenderer added non-DTS documents checkFilingDTS(val, referencedDocument, isEFM, isGFM, visited) if val.disclosureSystem.standardTaxonomiesDict is None: pass if isEFM: if modelDocument.uri in val.disclosureSystem.standardTaxonomiesDict: if modelDocument.targetNamespace: # check for duplicates of us-types, dei, and rr taxonomies match = namespacesConflictPattern.match(modelDocument.targetNamespace) if match is not None: val.standardNamespaceConflicts[match.group(2)].add(modelDocument) else: if len(modelDocument.basename) > 32: val.modelXbrl.error("EFM.5.01.01.tooManyCharacters", _("Document file name %(filename)s must not exceed 32 characters."), modelObject=modelDocument, filename=modelDocument.basename) if modelDocument.type == ModelDocument.Type.INLINEXBRL: if not htmlFileNamePattern.match(modelDocument.basename): val.modelXbrl.error("EFM.5.01.01", _("Document file name %(filename)s must start with a-z or 0-9, contain upper or lower case letters, ., -, _, and end with .htm."), modelObject=modelDocument, filename=modelDocument.basename) elif not efmFilenamePattern.match(modelDocument.basename): val.modelXbrl.error("EFM.5.01.01", _("Document file name %(filename)s must start with a-z or 0-9, contain upper or lower case letters, ., -, _, and end with .xsd or .xml."), modelObject=modelDocument, filename=modelDocument.basename) if (modelDocument.type == ModelDocument.Type.SCHEMA and modelDocument.targetNamespace not in val.disclosureSystem.baseTaxonomyNamespaces and modelDocument.uri.startswith(val.modelXbrl.uriDir)): val.hasExtensionSchema = True # check schema contents types # 6.7.3 check namespace for standard authority targetNamespaceAuthority = UrlUtil.authority(modelDocument.targetNamespace) if targetNamespaceAuthority in val.disclosureSystem.standardAuthorities: val.modelXbrl.error(("EFM.6.07.03", "GFM.1.03.03"), _("Taxonomy schema %(schema)s namespace %(targetNamespace)s is a disallowed authority"), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace, targetNamespaceAuthority=UrlUtil.authority(modelDocument.targetNamespace, includeScheme=False)) # 6.7.4 check namespace format if modelDocument.targetNamespace is None or not modelDocument.targetNamespace.startswith("http://"): match = None else: targetNamespaceDate = modelDocument.targetNamespace[len(targetNamespaceAuthority):] match = targetNamespaceDatePattern.match(targetNamespaceDate) if match is not None: try: if match.lastindex == 3: date = datetime.date(int(match.group(1)),int(match.group(2)),int(match.group(3))) elif match.lastindex == 6: date = datetime.date(int(match.group(4)),int(match.group(5)),int(match.group(6))) else: match = None except ValueError: match = None if match is None: val.modelXbrl.error(("EFM.6.07.04", "GFM.1.03.04"), _("Taxonomy schema %(schema)s namespace %(targetNamespace)s must have format http://{authority}/{versionDate}"), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace) elif val.fileNameDate and date > val.fileNameDate: val.modelXbrl.info(("EFM.6.07.06", "GFM.1.03.06"), _("Warning: Taxonomy schema %(schema)s namespace %(targetNamespace)s has date later than document name date %(docNameDate)s"), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace, docNameDate=val.fileNameDate) if modelDocument.targetNamespace is not None: # 6.7.5 check prefix for _ authority = UrlUtil.authority(modelDocument.targetNamespace) if not re.match(r"(http://|https://|ftp://|urn:)\w+",authority): val.modelXbrl.error(("EFM.6.07.05", "GFM.1.03.05"), _("Taxonomy schema %(schema)s namespace %(targetNamespace)s must be a valid URL with a valid authority for the namespace."), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace) prefix = XmlUtil.xmlnsprefix(modelDocument.xmlRootElement,modelDocument.targetNamespace) if not prefix: val.modelXbrl.error(("EFM.6.07.07", "GFM.1.03.07"), _("Taxonomy schema %(schema)s namespace %(targetNamespace)s missing prefix for the namespace."), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace) elif "_" in prefix: val.modelXbrl.error(("EFM.6.07.07", "GFM.1.03.07"), _("Taxonomy schema %(schema)s namespace %(targetNamespace)s prefix %(prefix)s must not have an '_'"), modelObject=modelDocument, schema=os.path.basename(modelDocument.uri), targetNamespace=modelDocument.targetNamespace, prefix=prefix) for modelConcept in modelDocument.xmlRootElement.iterdescendants(tag="{http://www.w3.org/2001/XMLSchema}element"): if isinstance(modelConcept,ModelConcept): # 6.7.16 name not duplicated in standard taxonomies name = modelConcept.get("name") if name is None: name = "" if modelConcept.get("ref") is not None: continue # don't validate ref's here for c in val.modelXbrl.nameConcepts.get(name, []): if c.modelDocument != modelDocument: if not c.modelDocument.uri.startswith(val.modelXbrl.uriDir): val.modelXbrl.error(("EFM.6.07.16", "GFM.1.03.18"), _("Concept %(concept)s is also defined in standard taxonomy schema schema %(standardSchema)s"), modelObject=(modelConcept,c), concept=modelConcept.qname, standardSchema=os.path.basename(c.modelDocument.uri), standardConcept=c.qname) # 6.7.17 id properly formed _id = modelConcept.id requiredId = (prefix if prefix is not None else "") + "_" + name if _id != requiredId: val.modelXbrl.error(("EFM.6.07.17", "GFM.1.03.19"), _("Concept %(concept)s id %(id)s should be %(requiredId)s"), modelObject=modelConcept, concept=modelConcept.qname, id=_id, requiredId=requiredId) # 6.7.18 nillable is true nillable = modelConcept.get("nillable") if nillable != "true" and modelConcept.isItem: val.modelXbrl.error(("EFM.6.07.18", "GFM.1.03.20"), _("Taxonomy schema %(schema)s element %(concept)s nillable %(nillable)s should be 'true'"), modelObject=modelConcept, schema=os.path.basename(modelDocument.uri), concept=name, nillable=nillable) # 6.7.19 not tuple if modelConcept.isTuple: val.modelXbrl.error(("EFM.6.07.19", "GFM.1.03.21"), _("Concept %(concept)s is a tuple"), modelObject=modelConcept, concept=modelConcept.qname) # 6.7.20 no typed domain ref if modelConcept.isTypedDimension: val.modelXbrl.error(("EFM.6.07.20", "GFM.1.03.22"), _("Concept %(concept)s has typedDomainRef %(typedDomainRef)s"), modelObject=modelConcept, concept=modelConcept.qname, typedDomainRef=modelConcept.typedDomainElement.qname if modelConcept.typedDomainElement is not None else modelConcept.typedDomainRef) # 6.7.21 abstract must be duration isDuration = modelConcept.periodType == "duration" if modelConcept.isAbstract and not isDuration: val.modelXbrl.error(("EFM.6.07.21", "GFM.1.03.23"), _("Taxonomy schema %(schema)s element %(concept)s is abstract but period type is not duration"), modelObject=modelConcept, schema=os.path.basename(modelDocument.uri), concept=modelConcept.qname) # 6.7.22 abstract must be stringItemType ''' removed SEC EFM v.17, Edgar release 10.4, and GFM 2011-04-08 if modelConcept.abstract == "true" and modelConcept.typeQname != XbrlConst. qnXbrliStringItemType: val.modelXbrl.error(("EFM.6.07.22", "GFM.1.03.24"), _("Concept %(concept)s is abstract but type is not xbrli:stringItemType"), modelObject=modelConcept, concept=modelConcept.qname) ''' substitutionGroupQname = modelConcept.substitutionGroupQname # 6.7.23 Axis must be subs group dimension if name.endswith("Axis") ^ (substitutionGroupQname == XbrlConst.qnXbrldtDimensionItem): val.modelXbrl.error(("EFM.6.07.23", "GFM.1.03.25"), _("Concept %(concept)s must end in Axis to be in xbrldt:dimensionItem substitution group"), modelObject=modelConcept, concept=modelConcept.qname) # 6.7.24 Table must be subs group hypercube if name.endswith("Table") ^ (substitutionGroupQname == XbrlConst.qnXbrldtHypercubeItem): val.modelXbrl.error(("EFM.6.07.24", "GFM.1.03.26"), _("Concept %(concept)s must end in Table to be in xbrldt:hypercubeItem substitution group"), modelObject=modelConcept, schema=os.path.basename(modelDocument.uri), concept=modelConcept.qname) # 6.7.25 if neither hypercube or dimension, substitution group must be item if substitutionGroupQname not in (None, XbrlConst.qnXbrldtDimensionItem, XbrlConst.qnXbrldtHypercubeItem, XbrlConst.qnXbrliItem): val.modelXbrl.error(("EFM.6.07.25", "GFM.1.03.27"), _("Concept %(concept)s has disallowed substitution group %(substitutionGroup)s"), modelObject=modelConcept, concept=modelConcept.qname, substitutionGroup=modelConcept.substitutionGroupQname) # 6.7.26 Table must be subs group hypercube if name.endswith("LineItems") and modelConcept.abstract != "true": val.modelXbrl.error(("EFM.6.07.26", "GFM.1.03.28"), _("Concept %(concept)s is a LineItems but not abstract"), modelObject=modelConcept, concept=modelConcept.qname) # 6.7.27 type domainMember must end with Domain or Member conceptType = modelConcept.type isDomainItemType = conceptType is not None and conceptType.isDomainItemType endsWithDomainOrMember = name.endswith("Domain") or name.endswith("Member") if isDomainItemType != endsWithDomainOrMember: val.modelXbrl.error(("EFM.6.07.27", "GFM.1.03.29"), _("Concept %(concept)s must end with Domain or Member for type of domainItemType"), modelObject=modelConcept, concept=modelConcept.qname) # 6.7.28 domainItemType must be duration if isDomainItemType and not isDuration: val.modelXbrl.error(("EFM.6.07.28", "GFM.1.03.30"), _("Concept %(concept)s is a domainItemType and must be periodType duration"), modelObject=modelConcept, concept=modelConcept.qname) #6.7.31 (version 27) fractions if modelConcept.isFraction: val.modelXbrl.error("EFM.6.07.31", _("Concept %(concept)s is a fraction"), modelObject=modelConcept, concept=modelConcept.qname) #6.7.32 (version 27) instant non numeric if modelConcept.isItem and (not modelConcept.isNumeric and not isDuration and not modelConcept.isAbstract and not isDomainItemType): val.modelXbrl.error("EFM.6.07.32", _("Taxonomy schema %(schema)s element %(concept)s is non-numeric but period type is not duration"), modelObject=modelConcept, schema=os.path.basename(modelDocument.uri), concept=modelConcept.qname) # 6.8.5 semantic check, check LC3 name if name: if not name[0].isupper(): val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.05.firstLetter", "GFM.2.03.05.firstLetter"), _("Concept %(concept)s name must start with a capital letter"), modelObject=modelConcept, concept=modelConcept.qname) if namePattern.search(name): val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.05.disallowedCharacter", "GFM.2.03.05.disallowedCharacter"), _("Concept %(concept)s has disallowed name character"), modelObject=modelConcept, concept=modelConcept.qname) if len(name) > 200: val.modelXbrl.log("ERROR-SEMANTIC", "EFM.6.08.05.nameLength", _("Concept %(concept)s name length %(namelength)s exceeds 200 characters"), modelObject=modelConcept, concept=modelConcept.qname, namelength=len(name)) if isEFM: label = modelConcept.label(lang="en-US", fallbackToQname=False) if label: # allow Joe's Bar, N.A. to be JoesBarNA -- remove ', allow A. as not article "a" lc3name = ''.join(re.sub(r"['.-]", "", (w[0] or w[2] or w[3] or w[4])).title() for w in re.findall(r"((\w+')+\w+)|(A[.-])|([.-]A(?=\W|$))|(\w+)", label) # EFM implies this should allow - and . re.findall(r"[\w\-\.]+", label) if w[4].lower() not in ("the", "a", "an")) if not(name == lc3name or (name and lc3name and lc3name[0].isdigit() and name[1:] == lc3name and (name[0].isalpha() or name[0] == '_'))): val.modelXbrl.log("WARNING-SEMANTIC", "EFM.6.08.05.LC3", _("Concept %(concept)s should match expected LC3 composition %(lc3name)s"), modelObject=modelConcept, concept=modelConcept.qname, lc3name=lc3name) if conceptType is not None: # 6.8.6 semantic check if not isDomainItemType and conceptType.qname != XbrlConst.qnXbrliDurationItemType: nameProblems = nonDomainItemNameProblemPattern.findall(name) if any(any(t) for t in nameProblems): # list of tuples with possibly nonempty strings val.modelXbrl.log("WARNING-SEMANTIC", ("EFM.6.08.06", "GFM.2.03.06"), _("Concept %(concept)s should not contain company or period information, found: %(matches)s"), modelObject=modelConcept, concept=modelConcept.qname, matches=", ".join(''.join(t) for t in nameProblems)) if conceptType.qname == XbrlConst.qnXbrliMonetaryItemType: if not modelConcept.balance: # 6.8.11 may not appear on a income or balance statement if any(linkroleDefinitionBalanceIncomeSheet.match(roleType.definition) for rel in val.modelXbrl.relationshipSet(XbrlConst.parentChild).toModelObject(modelConcept) for roleType in val.modelXbrl.roleTypes.get(rel.linkrole,())): val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.11", "GFM.2.03.11"), _("Concept %(concept)s must have a balance because it appears in a statement of income or balance sheet"), modelObject=modelConcept, concept=modelConcept.qname) # 6.11.5 semantic check, must have a documentation label stdLabel = modelConcept.label(lang="en-US", fallbackToQname=False) defLabel = modelConcept.label(preferredLabel=XbrlConst.documentationLabel, lang="en-US", fallbackToQname=False) if not defLabel or ( # want different words than std label stdLabel and re.findall(r"\w+", stdLabel) == re.findall(r"\w+", defLabel)): val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.11.05", "GFM.2.04.04"), _("Concept %(concept)s is monetary without a balance and must have a documentation label that disambiguates its sign"), modelObject=modelConcept, concept=modelConcept.qname) # 6.8.16 semantic check if conceptType.qname == XbrlConst.qnXbrliDateItemType and modelConcept.periodType != "duration": val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.16", "GFM.2.03.16"), _("Concept %(concept)s of type xbrli:dateItemType must have periodType duration"), modelObject=modelConcept, concept=modelConcept.qname) # 6.8.17 semantic check if conceptType.qname == XbrlConst.qnXbrliStringItemType and modelConcept.periodType != "duration": val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.17", "GFM.2.03.17"), _("Concept %(concept)s of type xbrli:stringItemType must have periodType duration"), modelObject=modelConcept, concept=modelConcept.qname) # 6.7.8 check for embedded linkbase for e in modelDocument.xmlRootElement.iterdescendants(tag="{http://www.xbrl.org/2003/linkbase}linkbase"): if isinstance(e,ModelObject): val.modelXbrl.error(("EFM.6.07.08", "GFM.1.03.08"), _("Taxonomy schema %(schema)s contains an embedded linkbase"), modelObject=e, schema=modelDocument.basename) break requiredUsedOns = {XbrlConst.qnLinkPresentationLink, XbrlConst.qnLinkCalculationLink, XbrlConst.qnLinkDefinitionLink} standardUsedOns = {XbrlConst.qnLinkLabel, XbrlConst.qnLinkReference, XbrlConst.qnLinkDefinitionArc, XbrlConst.qnLinkCalculationArc, XbrlConst.qnLinkPresentationArc, XbrlConst.qnLinkLabelArc, XbrlConst.qnLinkReferenceArc, # per WH, private footnote arc and footnore resource roles are not allowed XbrlConst.qnLinkFootnoteArc, XbrlConst.qnLinkFootnote, } # 6.7.9 role types authority for e in modelDocument.xmlRootElement.iterdescendants(tag="{http://www.xbrl.org/2003/linkbase}roleType"): if isinstance(e,ModelObject): roleURI = e.get("roleURI") if targetNamespaceAuthority != UrlUtil.authority(roleURI): val.modelXbrl.error(("EFM.6.07.09", "GFM.1.03.09"), _("RoleType %(roleType)s does not match authority %(targetNamespaceAuthority)s"), modelObject=e, roleType=roleURI, targetNamespaceAuthority=targetNamespaceAuthority, targetNamespace=modelDocument.targetNamespace) # 6.7.9 end with .../role/lc3 name if not roleTypePattern.match(roleURI): val.modelXbrl.warning(("EFM.6.07.09.roleEnding", "GFM.1.03.09"), "RoleType %(roleType)s should end with /role/{LC3name}", modelObject=e, roleType=roleURI) # 6.7.10 only one role type declaration in DTS modelRoleTypes = val.modelXbrl.roleTypes.get(roleURI) if modelRoleTypes is not None: modelRoleType = modelRoleTypes[0] definition = modelRoleType.definitionNotStripped usedOns = modelRoleType.usedOns if len(modelRoleTypes) == 1: # 6.7.11 used on's for pre, cal, def if any has a used on if not usedOns.isdisjoint(requiredUsedOns) and len(requiredUsedOns - usedOns) > 0: val.modelXbrl.error(("EFM.6.07.11", "GFM.1.03.11"), _("RoleType %(roleType)s missing used on %(usedOn)s"), modelObject=e, roleType=roleURI, usedOn=requiredUsedOns - usedOns) # 6.7.12 definition match pattern if (val.disclosureSystem.roleDefinitionPattern is not None and (definition is None or not val.disclosureSystem.roleDefinitionPattern.match(definition))): val.modelXbrl.error(("EFM.6.07.12", "GFM.1.03.12-14"), _("RoleType %(roleType)s definition \"%(definition)s\" must match {Sortcode} - {Type} - {Title}"), modelObject=e, roleType=roleURI, definition=(definition or "")) if usedOns & standardUsedOns: # semantics check val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.03", "GFM.2.03.03"), _("RoleType %(roleuri)s is defined using role types already defined by standard roles for: %(qnames)s"), modelObject=e, roleuri=roleURI, qnames=', '.join(str(qn) for qn in usedOns & standardUsedOns)) # 6.7.13 arcrole types authority for e in modelDocument.xmlRootElement.iterdescendants(tag="{http://www.xbrl.org/2003/linkbase}arcroleType"): if isinstance(e,ModelObject): arcroleURI = e.get("arcroleURI") if targetNamespaceAuthority != UrlUtil.authority(arcroleURI): val.modelXbrl.error(("EFM.6.07.13", "GFM.1.03.15"), _("ArcroleType %(arcroleType)s does not match authority %(targetNamespaceAuthority)s"), modelObject=e, arcroleType=arcroleURI, targetNamespaceAuthority=targetNamespaceAuthority, targetNamespace=modelDocument.targetNamespace) # 6.7.13 end with .../arcrole/lc3 name if not arcroleTypePattern.match(arcroleURI): val.modelXbrl.warning(("EFM.6.07.13.arcroleEnding", "GFM.1.03.15"), _("ArcroleType %(arcroleType)s should end with /arcrole/{LC3name}"), modelObject=e, arcroleType=arcroleURI) # 6.7.15 definition match pattern modelRoleTypes = val.modelXbrl.arcroleTypes[arcroleURI] definition = modelRoleTypes[0].definition if definition is None or not arcroleDefinitionPattern.match(definition): val.modelXbrl.error(("EFM.6.07.15", "GFM.1.03.17"), _("ArcroleType %(arcroleType)s definition must be non-empty"), modelObject=e, arcroleType=arcroleURI) # semantic checks usedOns = modelRoleTypes[0].usedOns if usedOns & standardUsedOns: # semantics check val.modelXbrl.log("ERROR-SEMANTIC", ("EFM.6.08.03", "GFM.2.03.03"), _("ArcroleType %(arcroleuri)s is defined using role types already defined by standard arcroles for: %(qnames)s"), modelObject=e, arcroleuri=arcroleURI, qnames=', '.join(str(qn) for qn in usedOns & standardUsedOns)) #6.3.3 filename check m = re.match(r"^\w+-([12][0-9]{3}[01][0-9][0-3][0-9]).xsd$", modelDocument.basename) if m: try: # check date value datetime.datetime.strptime(m.group(1),"%Y%m%d").date() # date and format are ok, check "should" part of 6.3.3 if val.fileNameBasePart: expectedFilename = "{0}-{1}.xsd".format(val.fileNameBasePart, val.fileNameDatePart) if modelDocument.basename != expectedFilename: val.modelXbrl.log("WARNING-SEMANTIC", ("EFM.6.03.03.matchInstance", "GFM.1.01.01.matchInstance"), _('Schema file name warning: %(filename)s, should match %(expectedFilename)s'), modelObject=modelDocument, filename=modelDocument.basename, expectedFilename=expectedFilename) except __HOLE__: val.modelXbrl.error((val.EFM60303, "GFM.1.01.01"), _('Invalid schema file base name part (date) in "{base}-{yyyymmdd}.xsd": %(filename)s'), modelObject=modelDocument, filename=modelDocument.basename, messageCodes=("EFM.6.03.03", "EFM.6.23.01", "GFM.1.01.01")) else: val.modelXbrl.error((val.EFM60303, "GFM.1.01.01"), _('Invalid schema file name, must match "{base}-{yyyymmdd}.xsd": %(filename)s'), modelObject=modelDocument, filename=modelDocument.basename, messageCodes=("EFM.6.03.03", "EFM.6.23.01", "GFM.1.01.01")) elif modelDocument.type == ModelDocument.Type.LINKBASE: # if it is part of the submission (in same directory) check name labelRels = None if modelDocument.filepath.startswith(val.modelXbrl.modelDocument.filepathdir): #6.3.3 filename check extLinkElt = XmlUtil.descendant(modelDocument.xmlRootElement, XbrlConst.link, "*", "{http://www.w3.org/1999/xlink}type", "extended") if extLinkElt is None:# no ext link element val.modelXbrl.error((val.EFM60303 + ".noLinkElement", "GFM.1.01.01.noLinkElement"), _('Invalid linkbase file name: %(filename)s, has no extended link element, cannot determine link type.'), modelObject=modelDocument, filename=modelDocument.basename, messageCodes=("EFM.6.03.03.noLinkElement", "EFM.6.23.01.noLinkElement", "GFM.1.01.01.noLinkElement")) elif extLinkElt.localName not in extLinkEltFileNameEnding: val.modelXbrl.error("EFM.6.03.02", _('Invalid linkbase link element %(linkElement)s in %(filename)s'), modelObject=modelDocument, linkElement=extLinkElt.localName, filename=modelDocument.basename) else: m = re.match(r"^\w+-([12][0-9]{3}[01][0-9][0-3][0-9])(_[a-z]{3}).xml$", modelDocument.basename) expectedSuffix = extLinkEltFileNameEnding[extLinkElt.localName] if m and m.group(2) == expectedSuffix: try: # check date value datetime.datetime.strptime(m.group(1),"%Y%m%d").date() # date and format are ok, check "should" part of 6.3.3 if val.fileNameBasePart: expectedFilename = "{0}-{1}{2}.xml".format(val.fileNameBasePart, val.fileNameDatePart, expectedSuffix) if modelDocument.basename != expectedFilename: val.modelXbrl.log("WARNING-SEMANTIC", ("EFM.6.03.03.matchInstance", "GFM.1.01.01.matchInstance"), _('Linkbase name warning: %(filename)s should match %(expectedFilename)s'), modelObject=modelDocument, filename=modelDocument.basename, expectedFilename=expectedFilename) except ValueError: val.modelXbrl.error((val.EFM60303, "GFM.1.01.01"), _('Invalid linkbase base file name part (date) in "{base}-{yyyymmdd}_{suffix}.xml": %(filename)s'), modelObject=modelDocument, filename=modelDocument.basename, messageCodes=("EFM.6.03.03", "EFM.6.23.01", "GFM.1.01.01")) else: val.modelXbrl.error((val.EFM60303, "GFM.1.01.01"), _('Invalid linkbase name, must match "{base}-{yyyymmdd}%(expectedSuffix)s.xml": %(filename)s'), modelObject=modelDocument, filename=modelDocument.basename, expectedSuffix=expectedSuffix, messageCodes=("EFM.6.03.03", "EFM.6.23.01", "GFM.1.01.01")) if extLinkElt.localName == "labelLink": if labelRels is None: labelRels = val.modelXbrl.relationshipSet(XbrlConst.conceptLabel) for labelElt in XmlUtil.children(extLinkElt, XbrlConst.link, "label"): # 6.10.9 if XbrlConst.isNumericRole(labelElt.role): for rel in labelRels.toModelObject(labelElt): if rel.fromModelObject is not None and not rel.fromModelObject.isNumeric: val.modelXbrl.error("EFM.6.10.09", _("Label of non-numeric concept %(concept)s has a numeric role: %(role)s"), modelObject=(labelElt, rel.fromModelObject), concept=rel.fromModelObject.qname, role=labelElt.role)
ValueError
dataset/ETHPy150Open Arelle/Arelle/arelle/plugin/validate/EFM/DTS.py/checkFilingDTS
2,149
def _validate_date_part(self, value): daypart, monthpart, yearpart = int(value[:2]), int(value[2:4]), int(value[4:7]) if yearpart >= 800: yearpart += 1000 else: yearpart += 2000 try: date = datetime.datetime(year = yearpart, month = monthpart, day = daypart).date() except __HOLE__: return False if date >= datetime.datetime.now().date(): return False return True
ValueError
dataset/ETHPy150Open AppScale/appscale/AppServer/lib/django-1.5/django/contrib/localflavor/mk/forms.py/UMCNField._validate_date_part
2,150
def build_cipher(key, iv, alg="aes_128_cbc"): """ :param key: encryption key :param iv: init vector :param alg: cipher algorithm :return: A Cipher instance """ typ, bits, cmode = alg.split("_") if not iv: iv = Random.new().read(AES.block_size) else: assert len(iv) == AES.block_size if bits not in ["128", "192", "256"]: raise AESError("Unsupported key length") try: assert len(key) == int(bits) >> 3 except AssertionError: raise AESError("Wrong Key length") try: return AES.new(tobytes(key), POSTFIX_MODE[cmode], tobytes(iv)), iv except __HOLE__: raise AESError("Unsupported chaining mode")
KeyError
dataset/ETHPy150Open rohe/pyoidc/src/oic/utils/aes.py/build_cipher
2,151
def __new__(cls, meth, callback=None): try: obj = meth.__self__ func = meth.__func__ except __HOLE__: raise TypeError("argument should be a bound method, not {}" .format(type(meth))) def _cb(arg): # The self-weakref trick is needed to avoid creating a # reference cycle. self = self_wr() if self._alive: self._alive = False if callback is not None: callback(self) self = ref.__new__(cls, obj, _cb) self._func_ref = ref(func, _cb) self._meth_type = type(meth) self._alive = True self_wr = ref(self) return self
AttributeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/WeakMethod.__new__
2,152
def __init__(self, fn): try: self._obj = ref(fn.im_self) self._meth = fn.im_func except __HOLE__: # It's not a bound method. self._obj = None self._meth = fn
AttributeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/WeakMethod.__init__
2,153
def __init__(self, parent, port, worker_class_or_function, args, on_receive=None): super(JsonTcpClient, self).__init__(parent) self._port = port self._worker = worker_class_or_function self._args = args self._header_complete = False self._header_buf = bytes() self._to_read = 0 self._data_buf = bytes() if on_receive: try: self._callback = WeakMethod(on_receive) except __HOLE__: # unbound method (i.e. free function) self._callback = ref(on_receive) else: self._callback = None self.is_connected = False self._closed = False self.connected.connect(self._on_connected) self.error.connect(self._on_error) self.disconnected.connect(self._on_disconnected) self.readyRead.connect(self._on_ready_read) self._connect()
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient.__init__
2,154
def _on_disconnected(self): try: comm('disconnected from backend: %s:%d', self.peerName(), self.peerPort()) except (AttributeError, RuntimeError): # logger might be None if for some reason qt deletes the socket # after python global exit pass try: self.is_connected = False except __HOLE__: pass
AttributeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._on_disconnected
2,155
def _read_header(self): comm('reading header') self._header_buf += self.read(4) if len(self._header_buf) == 4: self._header_complete = True try: header = struct.unpack('=I', self._header_buf) except __HOLE__: # pyside header = struct.unpack('=I', self._header_buf.data()) self._to_read = header[0] self._header_buf = bytes() comm('header content: %d', self._to_read)
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._read_header
2,156
def _read_payload(self): """ Reads the payload (=data) """ comm('reading payload data') comm('remaining bytes to read: %d', self._to_read) data_read = self.read(self._to_read) nb_bytes_read = len(data_read) comm('%d bytes read', nb_bytes_read) self._data_buf += data_read self._to_read -= nb_bytes_read if self._to_read <= 0: try: data = self._data_buf.decode('utf-8') except AttributeError: data = bytes(self._data_buf.data()).decode('utf-8') comm('payload read: %r', data) comm('payload length: %r', len(self._data_buf)) comm('decoding payload as json object') obj = json.loads(data) comm('response received: %r', obj) try: results = obj['results'] except (__HOLE__, TypeError): results = None # possible callback if self._callback and self._callback(): self._callback()(results) self._header_complete = False self._data_buf = bytes() self.finished.emit(self)
KeyError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/JsonTcpClient._read_payload
2,157
def _on_process_finished(self, exit_code): """ Logs process exit status """ comm('backend process finished with exit code %d', exit_code) try: self.running = False except __HOLE__: pass
AttributeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_finished
2,158
def _on_process_stdout_ready(self): """ Logs process output """ if not self: return o = self.readAllStandardOutput() try: output = bytes(o).decode(self._encoding) except __HOLE__: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.log(1, line)
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_stdout_ready
2,159
def _on_process_stderr_ready(self): """ Logs process output (stderr) """ if not self: return o = self.readAllStandardError() try: output = bytes(o).decode(self._encoding) except __HOLE__: output = bytes(o.data()).decode(self._encoding) for line in output.splitlines(): self._srv_logger.error(line)
TypeError
dataset/ETHPy150Open OpenCobolIDE/OpenCobolIDE/open_cobol_ide/extlibs/pyqode/core/api/client.py/BackendProcess._on_process_stderr_ready
2,160
@classmethod def get_result(cls, request): """ Get the result (or None) of a transparent redirect given a Django Request object. >>> result = MyForm.get_result(request) >>> if result.is_success: take_some_action() This method uses the request.META["QUERY_STRING"] parameter to get the HTTP query string. """ try: result = braintree.TransparentRedirect.confirm(request.META["QUERY_STRING"]) except (__HOLE__, braintree.exceptions.not_found_error.NotFoundError): result = None return result
KeyError
dataset/ETHPy150Open danielgtaylor/braintree_django/django_braintree/forms.py/BraintreeForm.get_result
2,161
def construct_response(scenario_name): # load up response data data = json.load(open('scenario.cache','r')) lookup = TemplateLookup(directories=['./scenarios']) for path in glob2.glob('./scenarios/**/request.mako'): if path != scenario_name: continue event_name = path.split('/')[-2] template = Template("${response}") try: response = data[event_name].get('response', {}) text = template.render(response=response).strip() response = json.loads(text) del response["links"] for key, value in response.items(): response = value[0] type = key resource = balanced.Resource() object_type = resource.registry[type] object_instance = object_type() for key, value in response.items(): setattr(object_instance, key, value) text = template.render(response=object_instance) except __HOLE__: text = '' return text
KeyError
dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/construct_response
2,162
def render_executables(): # load up scenario data data = json.load(open('scenario.cache','r')) lookup = TemplateLookup(directories=['./scenarios']) for path in glob2.glob('./scenarios/**/request.mako'): event_name = path.split('/')[-2] template = Template(filename=path, lookup=lookup,) try: request = data[event_name].get('request', {}) payload = request.get('payload') text = template.render(api_key=data['api_key'], request=request, payload=payload).strip() except __HOLE__: text = '' print colors.YELLOW + "WARN: Skipped {} since {} not in scenario.cache".format( path, event_name) + colors.RESET with open(os.path.join(os.path.dirname(path), 'executable.py'), 'w+') as write_to: write_to.write(text)
KeyError
dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/render_executables
2,163
def fetch_scenario_cache(): try: os.remove('scenario.cache') except __HOLE__: pass with open('scenario.cache', 'wb') as fo: response = requests.get(SCENARIO_CACHE_URL) if not response.ok: sys.exit() for block in response.iter_content(): fo.write(block)
OSError
dataset/ETHPy150Open balanced/balanced-python/render_scenarios.py/fetch_scenario_cache
2,164
def list_devices(self, number): if number: try: number = number.strip() number = int(number) except __HOLE__: text = '{} is not a number, now is it. You see, it needs to be.'.format(number) return text devices = self.device.list() if number: devices_trunc = devices[:number] else: devices_trunc = devices[:5] return self._format_devices(devices_trunc)
ValueError
dataset/ETHPy150Open serverdensity/sdbot/limbo/plugins/devices.py/Wrapper.list_devices
2,165
def load_sanders_data(dirname=".", line_count=-1): count = 0 topics = [] labels = [] tweets = [] with open(os.path.join(DATA_DIR, dirname, "corpus.csv"), "r") as csvfile: metareader = csv.reader(csvfile, delimiter=',', quotechar='"') for line in metareader: count += 1 if line_count > 0 and count > line_count: break topic, label, tweet_id = line tweet_fn = os.path.join( DATA_DIR, dirname, 'rawdata', '%s.json' % tweet_id) try: tweet = json.load(open(tweet_fn, "r")) except __HOLE__: print(("Tweet '%s' not found. Skip." % tweet_fn)) continue if 'text' in tweet and tweet['user']['lang'] == "en": topics.append(topic) labels.append(label) tweets.append(tweet['text']) tweets = np.asarray(tweets) labels = np.asarray(labels) return tweets, labels
IOError
dataset/ETHPy150Open luispedro/BuildingMachineLearningSystemsWithPython/ch06/utils.py/load_sanders_data
2,166
def getComponentByPosition(self, idx): try: return self._componentValues[idx] except __HOLE__: if idx < len(self._componentType): return raise
IndexError
dataset/ETHPy150Open kurrik/chrome-extensions/crx-appengine-packager/pyasn1/type/univ.py/SequenceAndSetBase.getComponentByPosition
2,167
def start(self): """Poet server control shell.""" debug.info('Entering control shell') self.conn = PoetSocket(self.s.accept()[0]) print 'Welcome to posh, the Poet Shell!' print 'Running `help\' will give you a list of supported commands.' while True: try: argv = raw_input(POSH_PROMPT).split() if not argv: continue if argv[0] in self.builtins: self.builtins[argv[0]](argv) elif argv[0] in module.server_commands: try: module.server_commands[argv[0]](self, argv) except Exception as e: self.info(str(e.args)) else: self.info('{}: command not found'.format(argv[0])) # see comment above for self.continue_ for why this is here if not self.continue_: break except __HOLE__: print continue except EOFError: print break self.conn.send('fin') debug.info('Exiting control shell')
KeyboardInterrupt
dataset/ETHPy150Open mossberg/poet/server.py/PoetServer.start
2,168
def drop_privs(): try: new_uid = int(os.getenv('SUDO_UID')) new_gid = int(os.getenv('SUDO_GID')) except __HOLE__: # they were running directly from a root user and didn't have # sudo env variables print """[!] WARNING: Couldn't drop privileges! To avoid this error, run from a non-root user. You may also use sudo, from a non-root user. Continue? (y/n)""", if raw_input().lower()[0] == 'y': return die() debug.info('Dropping privileges to uid: {}, gid: {}'.format(new_uid, new_gid)) # drop group before user, because otherwise you're not privileged enough # to drop group os.setgroups([]) os.setregid(new_gid, new_gid) os.setreuid(new_uid, new_uid) # check to make sure we can't re-escalate try: os.seteuid(0) print '[!] WARNING: Failed to drop privileges! Continue? (y/n)', if raw_input().lower()[0] != 'y': die() except OSError: return
TypeError
dataset/ETHPy150Open mossberg/poet/server.py/drop_privs
2,169
def main(): args = get_args() if args.version: print 'Poet version {}'.format(__version__) sys.exit(0) print_header() PORT = int(args.port) if args.port else 443 try: s = PoetSocketServer(PORT) except socket.error as e: if e.errno == 13: die('You need to be root!') if os.geteuid() == 0: drop_privs() debug.info('Poet server started on port: {}'.format(PORT)) module.load_modules() while True: try: conn, addr = s.accept() except __HOLE__: die() conntime = datetime.now().strftime(debug.DATE_FMT) ping = conn.recv(SIZE) if not ping: die('Socket error: {}'.format(e.message)) auth_err = authenticate(ping) if auth_err: print '[!] ({}) Connected By: {} -> INVALID! ({})'.format(conntime, addr, auth_err) conn.close() else: print '[+] ({}) Connected By: {} -> VALID'.format(conntime, addr) conn.send(FAKEOK) conn.close() try: PoetServer(s).start() break except Exception as e: print e die('Fatal error: {}'.format(e.message)) die()
KeyboardInterrupt
dataset/ETHPy150Open mossberg/poet/server.py/main
2,170
@property def _core_plugin(self): try: return self._plugin except __HOLE__: self._plugin = manager.NeutronManager.get_plugin() return self._plugin
AttributeError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._core_plugin
2,171
@classmethod def _get_interface_info(cls, device_id, network_id, external=False): if cls._device_network_interface_map is None: cls._get_network_interface_map_from_config() try: dev_info = cls._device_network_interface_map[device_id] if external: return dev_info['external'].get(network_id, dev_info['external']['*']) else: return dev_info['internal'].get(network_id, dev_info['internal']['*']) except (__HOLE__, KeyError): LOG.error(_LE('Failed to lookup interface on device %(dev)s' 'for network %(net)s'), {'dev': device_id, 'net': network_id}) return
TypeError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._get_interface_info
2,172
@classmethod def _get_network_interface_map_from_config(cls): dni_dict = config.get_specific_config( 'HwVLANTrunkingPlugDriver'.lower()) temp = {} for hd_uuid, kv_dict in dni_dict.items(): # ensure hd_uuid is properly formatted hd_uuid = config.uuidify(hd_uuid) if hd_uuid not in temp: temp[hd_uuid] = {'internal': {}, 'external': {}} for k, v in kv_dict.items(): try: entry = k[:k.index('_')] net_spec, interface = v.split(':') for net_id in net_spec.split(','): temp[hd_uuid][entry][net_id] = interface except (__HOLE__, KeyError): with excutils.save_and_reraise_exception() as ctx: ctx.reraise = False LOG.error(_LE('Invalid network to interface mapping ' '%(key)s, %(value)s in configuration ' 'file for device = %(dev)s'), {'key': k, 'value': v, 'dev': hd_uuid}) cls._device_network_interface_map = temp
ValueError
dataset/ETHPy150Open openstack/networking-cisco/networking_cisco/plugins/cisco/device_manager/plugging_drivers/hw_vlan_trunking_driver.py/HwVLANTrunkingPlugDriver._get_network_interface_map_from_config
2,173
def __get_yubico_users(username): ''' Grab the YubiKey Client ID & Secret Key ''' user = {} try: if __opts__['yubico_users'].get(username, None): (user['id'], user['key']) = list(__opts__['yubico_users'][username].values()) else: return None except __HOLE__: return None return user
KeyError
dataset/ETHPy150Open saltstack/salt/salt/auth/yubico.py/__get_yubico_users
2,174
def main(): args = docopt.docopt('\n'.join(__doc__.split('\n')[2:]), version=const.VERSION) logging.basicConfig( level=logging.DEBUG if args['--verbose'] else logging.INFO, stream=sys.stdout, ) if len(args['<mail_uid>']) == 0: args['<mail_uid>'] = sys.stdin.read().strip().split() if len(args['<mail_uid>']) == 0: sys.stderr.write('\n'.join(__doc__.split('\n')[2:])) return 1 conf = config.new_context_from_file(args['--config-file'], section='imap') if conf is None: return 1 try: imap_account = imap_cli.connect(**conf) imap_cli.change_dir(imap_account, args['--directory'] or const.DEFAULT_DIRECTORY) fetched_mails = read(imap_account, args['<mail_uid>'], save_directory=args['--save']) if fetched_mails is None: log.error("Mail was not fetched, an error occured") return 1 for fetched_mail in fetched_mails: sys.stdout.write(display(fetched_mail)) imap_cli.disconnect(imap_account) except __HOLE__: log.info('Interrupt by user, exiting') return 0
KeyboardInterrupt
dataset/ETHPy150Open Gentux/imap-cli/imap_cli/fetch.py/main
2,175
def start_dev_appserver(): """Starts the appengine dev_appserver program for the Django project. The appserver is run with default parameters. If you need to pass any special parameters to the dev_appserver you will have to invoke it manually. """ from google.appengine.tools import dev_appserver_main progname = sys.argv[0] args = [] # hack __main__ so --help in dev_appserver_main works OK. sys.modules['__main__'] = dev_appserver_main # Set bind ip/port if specified. if len(sys.argv) > 2: addrport = sys.argv[2] try: addr, port = addrport.split(":") except __HOLE__: addr, port = None, addrport if not port.isdigit(): print "Error: '%s' is not a valid port number." % port sys.exit(1) else: addr, port = None, "8000" if addr: args.extend(["--address", addr]) if port: args.extend(["--port", port]) # Add email settings from django.conf import settings args.extend(['--smtp_host', settings.EMAIL_HOST, '--smtp_port', str(settings.EMAIL_PORT), '--smtp_user', settings.EMAIL_HOST_USER, '--smtp_password', settings.EMAIL_HOST_PASSWORD]) # Allow skipped files so we don't die args.extend(['--allow_skipped_files']) # Pass the application specific datastore location to the server. p = get_datastore_paths() args.extend(["--datastore_path", p[0], "--history_path", p[1]]) # Append the current working directory to the arguments. dev_appserver_main.main([progname] + args + [os.getcwdu()])
ValueError
dataset/ETHPy150Open CollabQ/CollabQ/appengine_django/management/commands/runserver.py/start_dev_appserver
2,176
def RenderAjax(self, request, response): """Run the flow for granting access.""" approval_urn = rdfvalue.RDFURN(request.REQ.get("acl", "/")) _, namespace, _ = approval_urn.Split(3) if namespace == "hunts": try: _, _, hunt_id, user, reason = approval_urn.Split() self.subject = rdfvalue.RDFURN(namespace).Add(hunt_id) self.user = user self.reason = utils.DecodeReasonString(reason) except (ValueError, __HOLE__): raise access_control.UnauthorizedAccess( "Approval object is not well formed.") flow.GRRFlow.StartFlow(flow_name="GrantHuntApprovalFlow", subject_urn=self.subject, reason=self.reason, delegate=self.user, token=request.token) elif namespace == "cron": try: _, _, cron_job_name, user, reason = approval_urn.Split() self.subject = rdfvalue.RDFURN(namespace).Add(cron_job_name) self.user = user self.reason = utils.DecodeReasonString(reason) except (ValueError, TypeError): raise access_control.UnauthorizedAccess( "Approval object is not well formed.") flow.GRRFlow.StartFlow(flow_name="GrantCronJobApprovalFlow", subject_urn=self.subject, reason=self.reason, delegate=self.user, token=request.token) elif aff4.AFF4Object.VFSGRRClient.CLIENT_ID_RE.match(namespace): try: _, client_id, user, reason = approval_urn.Split() self.subject = client_id self.user = user self.reason = utils.DecodeReasonString(reason) except (ValueError, TypeError): raise access_control.UnauthorizedAccess( "Approval object is not well formed.") flow.GRRFlow.StartFlow(client_id=client_id, flow_name="GrantClientApprovalFlow", reason=self.reason, delegate=self.user, subject_urn=rdf_client.ClientURN(self.subject), token=request.token) else: raise access_control.UnauthorizedAccess( "Approval object is not well formed.") return renderers.TemplateRenderer.Layout(self, request, response, apply_template=self.ajax_template)
TypeError
dataset/ETHPy150Open google/grr/grr/gui/plugins/acl_manager.py/GrantAccess.RenderAjax
2,177
def test13_range(self): """Checking ranges in table iterators (case13)""" if common.verbose: print('\n', '-=' * 30) print("Running %s.test13_range..." % self.__class__.__name__) # Case where step < 0 self.step = -11 try: self.check_range() except ValueError: if common.verbose: (type, value, traceback) = sys.exc_info() print("\nGreat!, the next ValueError was catched!") self.h5file.close() #else: # self.fail("expected a ValueError") # Case where step == 0 self.step = 0 try: self.check_range() except __HOLE__: if common.verbose: (type, value, traceback) = sys.exc_info() print("\nGreat!, the next ValueError was catched!") self.h5file.close() #else: # self.fail("expected a ValueError")
ValueError
dataset/ETHPy150Open PyTables/PyTables/tables/tests/test_tablesMD.py/BasicRangeTestCase.test13_range
2,178
def to_xml(self, encoding = "iso-8859-1"): try: import cStringIO as StringIO except __HOLE__: import StringIO f = StringIO.StringIO() self.write_xml(f, encoding) return f.getvalue()
ImportError
dataset/ETHPy150Open joeyb/joeyb-blog/externals/PyRSS2Gen.py/WriteXmlMixin.to_xml
2,179
def l10n_float(string): """Takes a country specfic decimal value as string and returns a float. """ # TODO: Implement a proper transformation with babel or similar if settings.LANGUAGE_CODE == "de": string = string.replace(",", ".") try: return float(string) except __HOLE__: return 0.0
ValueError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/l10n_float
2,180
def atof(value): """ locale.atof() on unicode string fails in some environments, like Czech. """ val = str(value) try: return float(val) except ValueError: try: return float(val.replace(',', '.')) except __HOLE__: pass if isinstance(value, unicode): value = value.encode("utf-8") return locale.atof(value)
ValueError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/atof
2,181
def get_default_shop(request=None): """Returns the default shop. """ from lfs.core.models import Shop if request: try: return request.shop except __HOLE__: pass try: shop = Shop.objects.get(pk=1) except Shop.DoesNotExist, e: # No guarantee that our shop will have pk=1 in postgres shop = Shop.objects.all()[0] if request: request.shop = shop return shop
AttributeError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_default_shop
2,182
def import_module(module): """Imports module with given dotted name. """ try: module = sys.modules[module] except __HOLE__: __import__(module) module = sys.modules[module] return module
KeyError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/import_module
2,183
def get_start_day(date): """Takes a string such as ``2009-07-23`` and returns datetime object of this day. """ try: year, month, day = date.split("-") start = datetime.datetime(int(year), int(month), int(day)) except __HOLE__: return None return start
ValueError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_start_day
2,184
def get_end_day(date): """Takes a string such as ``2009-07-23`` and returns a datetime object with last valid second of this day: 23:59:59. """ try: year, month, day = date.split("-") except __HOLE__: return None end = datetime.datetime(int(year), int(month), int(day)) end = end + datetime.timedelta(1) - datetime.timedelta(microseconds=1) return end
ValueError
dataset/ETHPy150Open diefenbach/django-lfs/lfs/core/utils.py/get_end_day
2,185
def __call__(self, environ, start_response): # initialize a session for the current user _tls.current_session = Session(lifetime=self.lifetime, no_datastore=self.no_datastore, cookie_only_threshold=self.cookie_only_thresh, cookie_key=self.cookie_key) # create a hook for us to insert a cookie into the response headers def my_start_response(status, headers, exc_info=None): try: _tls.current_session.save() # store the session if it was changed except __HOLE__: # 1Mb memcache limit _tls.current_session.clear() for ch in _tls.current_session.make_cookie_headers(): headers.append(('Set-Cookie', ch)) return start_response(status, headers, exc_info) # let the app do its thing return self.app(environ, my_start_response)
ValueError
dataset/ETHPy150Open rwl/muntjac/appengine_config.py/GaeSessionMiddleware.__call__
2,186
def tearDown(self): """ Disconnect the player and observer from their respective transports. """ for p in self.player, self.observer: try: p.destroy() except __HOLE__: pass
AttributeError
dataset/ETHPy150Open twisted/imaginary/imaginary/test/commandutils.py/CommandTestCaseMixin.tearDown
2,187
@classmethod def _vpn_connection_get_route_state(cls, vpn_connection_id, destination_cidr_block=None): try: data = cls.client.describe_vpn_connections( VpnConnectionIds=[vpn_connection_id]) try: route = next( r for r in data['VpnConnections'][0]['Routes'] if r['DestinationCidrBlock'] == destination_cidr_block) except __HOLE__: raise exceptions.NotFound() if route['State'] == 'deleted': raise exceptions.NotFound() return route['State'] except botocore.exceptions.ClientError as ex: error_code = ex.response['Error']['Code'] if error_code == 'InvalidVpnGatewayID.NotFound': raise exceptions.NotFound() raise
StopIteration
dataset/ETHPy150Open openstack/ec2-api/ec2api/tests/functional/base.py/EC2TestCase._vpn_connection_get_route_state
2,188
def query(self, properties=None, filteriw=None, showalldb=None, numberinggroup=None, inlanguagecode=None): """ General information about the site. See `<https://www.mediawiki.org/wiki/API:Meta#siteinfo_.2F_si>`_ :Parameters: properties: set(str) Which sysinfo properties to get: * general - Overall system information * namespaces - List of registered namespaces and their canonical names * namespacealiases - List of registered namespace aliases * specialpagealiases - List of special page aliases * magicwords - List of magic words and their aliases * statistics - Returns site statistics * interwikimap - Returns interwiki map (optionally filtered, (optionally localised by using siinlanguagecode)) * dbrepllag - Returns database server with the highest replication lag * usergroups - Returns user groups and the associated permissions * extensions - Returns extensions installed on the wiki * fileextensions - Returns list of file extensions allowed to be uploaded * rightsinfo - Returns wiki rights (license) information if available * restrictions - Returns information on available restriction (protection) types * languages - Returns a list of languages MediaWiki supports(optionally localised by using siinlanguagecode) * skins - Returns a list of all enabled skins * extensiontags - Returns a list of parser extension tags * functionhooks - Returns a list of parser function hooks * showhooks - Returns a list of all subscribed hooks (contents of $wgHooks) * variables - Returns a list of variable IDs * protocols - Returns a list of protocols that are allowed in external links. * defaultoptions - Returns the default values for user preferences. filteriw : str "local" or "!local" Return only local or only nonlocal entries of the interwiki map showalldb : bool List all database servers, not just the one lagging the most numberingroup : bool Lists the number of users in user groups inlanguagecode : bool Language code for localised language names (best effort, use CLDR extension) """ siprop = self._items(properties, levels=self.PROPERTIES) doc = self.session.get( { 'action': "query", 'meta': "siteinfo", 'siprop': siprop, 'sifilteriw': filteriw, 'sishowalldb': showalldb, 'sinumberinggroup': numberinggroup, 'siinlanguagecode': inlanguagecode } ) try: return doc['query'] except __HOLE__ as e: raise MalformedResponse(str(e), doc)
KeyError
dataset/ETHPy150Open mediawiki-utilities/python-mediawiki-utilities/mw/api/collections/site_info.py/SiteInfo.query
2,189
def formfield_for_dbfield(self, db_field, **kwargs): field = super(FilePickerAdmin, self).formfield_for_dbfield( db_field, **kwargs) if db_field.name in self.adminfiles_fields: try: field.widget.attrs['class'] += " adminfilespicker" except __HOLE__: field.widget.attrs['class'] = 'adminfilespicker' return field
KeyError
dataset/ETHPy150Open carljm/django-adminfiles/adminfiles/admin.py/FilePickerAdmin.formfield_for_dbfield
2,190
def get_form(self, *args, **kwargs): initial = self.get_form_kwargs() if 'ip_type' in self.request.GET and 'ip_str' in self.request.GET: ip_str = self.request.GET['ip_str'] ip_type = self.request.GET['ip_type'] network = calc_parent_str(ip_str, ip_type) if network and network.vlan and network.site: expected_name = "{0}.{1}.mozilla.com".format( network.vlan.name, network.site.get_site_path()) try: domain = Domain.objects.get(name=expected_name) except __HOLE__: domain = None if domain: initial['initial'] = {'ip_str': ip_str, 'domain': domain, 'ip_type': ip_type} else: initial['initial'] = {'ip_str': ip_str, 'ip_type': ip_type} return AddressRecordForm(**initial)
ObjectDoesNotExist
dataset/ETHPy150Open mozilla/inventory/mozdns/address_record/views.py/AddressRecordCreateView.get_form
2,191
def longestCommonPrefix(self, strs): """ O(k*n) :param strs: a list of string :return: string, prefix """ # checking, otherwise: ValueError: min() arg is an empty sequence if not strs: return "" n = len(strs) str_builder = "" min_len = min(len(string) for string in strs) for i in range(min_len): char = strs[0][i] j = 0 while j<n: try: if strs[j][i]!=char: break j += 1 except __HOLE__: break if j==n: str_builder += char else: break return str_builder
IndexError
dataset/ETHPy150Open algorhythms/LeetCode/015 Longest Common Prefix.py/Solution.longestCommonPrefix
2,192
def authenticate(self, auth, stored_password): if auth: username = auth.username client_password = auth.password else: username = "" client_password = "" if self.verify_password_callback: return self.verify_password_callback(username, client_password) if not auth: return False if self.hash_password_callback: try: client_password = self.hash_password_callback(client_password) except __HOLE__: client_password = self.hash_password_callback(username, client_password) return client_password == stored_password
TypeError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/flask_httpauth.py/HTTPBasicAuth.authenticate
2,193
def __init__(self, scheme=None, realm=None, use_ha1_pw=False): super(HTTPDigestAuth, self).__init__(scheme, realm) self.use_ha1_pw = use_ha1_pw self.random = SystemRandom() try: self.random.random() except __HOLE__: self.random = Random() def _generate_random(): return md5(str(self.random.random()).encode('utf-8')).hexdigest() def default_generate_nonce(): session["auth_nonce"] = _generate_random() return session["auth_nonce"] def default_verify_nonce(nonce): return nonce == session.get("auth_nonce") def default_generate_opaque(): session["auth_opaque"] = _generate_random() return session["auth_opaque"] def default_verify_opaque(opaque): return opaque == session.get("auth_opaque") self.generate_nonce(default_generate_nonce) self.generate_opaque(default_generate_opaque) self.verify_nonce(default_verify_nonce) self.verify_opaque(default_verify_opaque)
NotImplementedError
dataset/ETHPy150Open RoseOu/flasky/venv/lib/python2.7/site-packages/flask_httpauth.py/HTTPDigestAuth.__init__
2,194
def _pct_encoded_replace_unreserved(mo): try: i = int(mo.group(1), 16) if _unreserved[i]: return chr(i) else: return mo.group().upper() except __HOLE__: return mo.group()
ValueError
dataset/ETHPy150Open necaris/python3-openid/openid/urinorm.py/_pct_encoded_replace_unreserved
2,195
def _pct_encoded_replace(mo): try: return chr(int(mo.group(1), 16)) except __HOLE__: return mo.group()
ValueError
dataset/ETHPy150Open necaris/python3-openid/openid/urinorm.py/_pct_encoded_replace
2,196
def runEventTransaction(self, player, line, match): """ Take a player, input, and dictionary of parse results, resolve those parse results into implementations of appropriate interfaces in the game world, and execute the actual Action implementation (contained in the 'do' method) in an event transaction. This is the top level of action invocation. @param player: A L{Thing} representing the actor's body. @param line: A unicode string containing the original input @param match: A dictionary containing some parse results to pass through to this L{Action}'s C{do} method as keyword arguments. @raise eimaginary.AmbiguousArgument: if multiple valid targets are found for an argument. """ def thunk(): begin = time.time() try: actor = self.actorInterface(player) for (k, v) in match.items(): try: objs = self.resolve(player, k, v) except __HOLE__: pass else: if len(objs) == 1: match[k] = objs[0] elif len(objs) == 0: self.cantFind(player, actor, k, v) else: raise eimaginary.AmbiguousArgument(self, k, v, objs) return self.do(actor, line, **match) finally: end = time.time() log.msg(interface=iaxiom.IStatEvent, stat_actionDuration=end - begin, stat_actionExecuted=1) events.runEventTransaction(player.store, thunk)
NotImplementedError
dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Action.runEventTransaction
2,197
def do(self, player, line, attribute, target, value): """ Dispatch handling to an attribute-specific method. @type attribute: C{unicode} @param attribute: The model-level attribute of which to manipulate the value. Handling of each attribute will be dispatched to a C{set_}-prefixed method for that attribute based on this value. @type target: L{Thing} @param target: The model object to manipulate. @type value: C{unicode} @param value: The new value for the specified attribute. """ try: method = getattr(self, "set_" + attribute.upper()) except __HOLE__: raise eimaginary.ActionFailure( events.ThatDoesntMakeSense( actor=player.thing, actorMessage="You cannot set that.")) else: method(player, line, target, value)
AttributeError
dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Set.do
2,198
def set_GENDER(self, player, line, target, value): """ Attempt to change the gender of a thing. @param target: The thing to change the gender of. @param value: A string naming a gender on L{language.Gender}. """ try: target.gender = getattr(language.Gender, value.upper()) except __HOLE__: gender = {language.Gender.MALE: "male", language.Gender.FEMALE: "female", language.Gender.NEUTER: "neuter"}.get(target.gender) raise eimaginary.ActionFailure(events.ThatDoesntMakeSense( actor=player.thing, actorMessage=("Only male, female, and neuter are valid " "genders. You remain ", gender, "."))) else: if player.thing is target: # XXX Why can't I do something with Noun to collapse these # cases? event = events.Success( actor=player.thing, actorMessage=(u"You set your gender to ", value, ".")) else: event = events.Success( actor=player.thing, target=target, actorMessage=("You set ", language.Noun(target).hisHer(), " gender to ", value, "."), targetMessage=(player.thing, " set your gender to ", value, ".")) event.broadcast()
AttributeError
dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Set.set_GENDER
2,199
def do(self, player, line, topic): topic = topic.lower().strip() try: helpFile = self.helpContentPath.child(topic).open() except (__HOLE__, IOError, filepath.InsecurePath): player.send("No help available on ", topic, ".", "\n") else: player.send(helpFile.read(), '\n')
OSError
dataset/ETHPy150Open twisted/imaginary/imaginary/action.py/Help.do