Search is not available for this dataset
text
stringlengths
75
104k
def delete_tags(self, *payload): """ Delete a group of tags pass in up to 50 tags, or use *[tags] """ if len(payload) > 50: raise ze.TooManyItems("Only 50 tags or fewer may be deleted") modified_tags = " || ".join([tag for tag in payload]) # first, get version data by getting one tag self.tags(limit=1) headers = { "If-Unmodified-Since-Version": self.request.headers["last-modified-version"] } headers.update(self.default_headers()) req = requests.delete( url=self.endpoint + "/{t}/{u}/tags".format(t=self.library_type, u=self.library_id), params={"tag": modified_tags}, headers=headers, ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
def delete_item(self, payload, last_modified=None): """ Delete Items from a Zotero library Accepts a single argument: a dict containing item data OR a list of dicts containing item data """ params = None if isinstance(payload, list): params = {"itemKey": ",".join([p["key"] for p in payload])} if last_modified is not None: modified = last_modified else: modified = payload[0]["version"] url = self.endpoint + "/{t}/{u}/items".format( t=self.library_type, u=self.library_id ) else: ident = payload["key"] if last_modified is not None: modified = last_modified else: modified = payload["version"] url = self.endpoint + "/{t}/{u}/items/{c}".format( t=self.library_type, u=self.library_id, c=ident ) headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers()) req = requests.delete(url=url, params=params, headers=headers) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
def _validate(self, conditions): """ Validate saved search conditions, raising an error if any contain invalid operators """ allowed_keys = set(self.searchkeys) operators_set = set(self.operators.keys()) for condition in conditions: if set(condition.keys()) != allowed_keys: raise ze.ParamNotPassed( "Keys must be all of: %s" % ", ".join(self.searchkeys) ) if condition.get("operator") not in operators_set: raise ze.ParamNotPassed( "You have specified an unknown operator: %s" % condition.get("operator") ) # dict keys of allowed operators for the current condition permitted_operators = self.conditions_operators.get( condition.get("condition") ) # transform these into values permitted_operators_list = set( [self.operators.get(op) for op in permitted_operators] ) if condition.get("operator") not in permitted_operators_list: raise ze.ParamNotPassed( "You may not use the '%s' operator when selecting the '%s' condition. \nAllowed operators: %s" % ( condition.get("operator"), condition.get("condition"), ", ".join(list(permitted_operators_list)), ) )
def _verify(self, payload): """ ensure that all files to be attached exist open()'s better than exists(), cos it avoids a race condition """ if not payload: # Check payload has nonzero length raise ze.ParamNotPassed for templt in payload: if os.path.isfile(str(self.basedir.joinpath(templt["filename"]))): try: # if it is a file, try to open it, and catch the error with open(str(self.basedir.joinpath(templt["filename"]))): pass except IOError: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) ) # no point in continuing if the file isn't a file else: raise ze.FileDoesNotExist( "The file at %s couldn't be opened or found." % str(self.basedir.joinpath(templt["filename"])) )
def _create_prelim(self): """ Step 0: Register intent to upload files """ self._verify(self.payload) if "key" in self.payload[0] and self.payload[0]["key"]: if next((i for i in self.payload if "key" not in i), False): raise ze.UnsupportedParams( "Can't pass payload entries with and without keys to Zupload" ) return None # Don't do anything if payload comes with keys liblevel = "/{t}/{u}/items" # Create one or more new attachments headers = {"Zotero-Write-Token": token(), "Content-Type": "application/json"} headers.update(self.zinstance.default_headers()) # If we have a Parent ID, add it as a parentItem if self.parentid: for child in self.payload: child["parentItem"] = self.parentid to_send = json.dumps(self.payload) req = requests.post( url=self.zinstance.endpoint + liblevel.format( t=self.zinstance.library_type, u=self.zinstance.library_id ), data=to_send, headers=headers, ) try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) data = req.json() for k in data["success"]: self.payload[int(k)]["key"] = data["success"][k] return data
def _get_auth(self, attachment, reg_key, md5=None): """ Step 1: get upload authorisation for a file """ mtypes = mimetypes.guess_type(attachment) digest = hashlib.md5() with open(attachment, "rb") as att: for chunk in iter(lambda: att.read(8192), b""): digest.update(chunk) auth_headers = {"Content-Type": "application/x-www-form-urlencoded"} if not md5: auth_headers["If-None-Match"] = "*" else: # docs specify that for existing file we use this auth_headers["If-Match"] = md5 auth_headers.update(self.zinstance.default_headers()) data = { "md5": digest.hexdigest(), "filename": os.path.basename(attachment), "filesize": os.path.getsize(attachment), "mtime": str(int(os.path.getmtime(attachment) * 1000)), "contentType": mtypes[0] or "application/octet-stream", "charset": mtypes[1], "params": 1, } auth_req = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=data, headers=auth_headers, ) try: auth_req.raise_for_status() except requests.exceptions.HTTPError: error_handler(auth_req) return auth_req.json()
def _upload_file(self, authdata, attachment, reg_key): """ Step 2: auth successful, and file not on server zotero.org/support/dev/server_api/file_upload#a_full_upload reg_key isn't used, but we need to pass it through to Step 3 """ upload_dict = authdata[ "params" ] # using params now since prefix/suffix concat was giving ConnectionError # must pass tuple of tuples not dict to ensure key comes first upload_list = [("key", upload_dict["key"])] for k in upload_dict: if k != "key": upload_list.append((k, upload_dict[k])) # The prior code for attaching file gave me content not match md5 # errors upload_list.append(("file", open(attachment, "rb").read())) upload_pairs = tuple(upload_list) try: upload = requests.post( url=authdata["url"], files=upload_pairs, headers={ # "Content-Type": authdata['contentType'], "User-Agent": "Pyzotero/%s" % __version__ }, ) except (requests.exceptions.ConnectionError): raise ze.UploadError("ConnectionError") try: upload.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload) # now check the responses return self._register_upload(authdata, reg_key)
def _register_upload(self, authdata, reg_key): """ Step 3: upload successful, so register it """ reg_headers = { "Content-Type": "application/x-www-form-urlencoded", "If-None-Match": "*", } reg_headers.update(self.zinstance.default_headers()) reg_data = {"upload": authdata.get("uploadKey")} upload_reg = requests.post( url=self.zinstance.endpoint + "/{t}/{u}/items/{i}/file".format( t=self.zinstance.library_type, u=self.zinstance.library_id, i=reg_key ), data=reg_data, headers=dict(reg_headers), ) try: upload_reg.raise_for_status() except requests.exceptions.HTTPError: error_handler(upload_reg)
def upload(self): """ File upload functionality Goes through upload steps 0 - 3 (private class methods), and returns a dict noting success, failure, or unchanged (returning the payload entries with that property as a list for each status) """ result = {"success": [], "failure": [], "unchanged": []} self._create_prelim() for item in self.payload: if "key" not in item: result["failure"].append(item) continue attach = str(self.basedir.joinpath(item["filename"])) authdata = self._get_auth(attach, item["key"], md5=item.get("md5", None)) # no need to keep going if the file exists if authdata.get("exists"): result["unchanged"].append(item) continue self._upload_file(authdata, attach, item["key"]) result["success"].append(item) return result
def which(program, win_allow_cross_arch=True): """Identify the location of an executable file.""" def is_exe(path): return os.path.isfile(path) and os.access(path, os.X_OK) def _get_path_list(): return os.environ['PATH'].split(os.pathsep) if os.name == 'nt': def find_exe(program): root, ext = os.path.splitext(program) if ext: if is_exe(program): return program else: for ext in os.environ['PATHEXT'].split(os.pathsep): program_path = root + ext.lower() if is_exe(program_path): return program_path return None def get_path_list(): paths = _get_path_list() if win_allow_cross_arch: alt_sys_path = os.path.expandvars(r"$WINDIR\Sysnative") if os.path.isdir(alt_sys_path): paths.insert(0, alt_sys_path) else: alt_sys_path = os.path.expandvars(r"$WINDIR\SysWOW64") if os.path.isdir(alt_sys_path): paths.append(alt_sys_path) return paths else: def find_exe(program): return program if is_exe(program) else None get_path_list = _get_path_list if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
def split_multiline(value): """Split a multiline string into a list, excluding blank lines.""" return [element for element in (line.strip() for line in value.split('\n')) if element]
def split_elements(value): """Split a string with comma or space-separated elements into a list.""" items = [v.strip() for v in value.split(',')] if len(items) == 1: items = value.split() return items
def eval_environ(value): """Evaluate environment markers.""" def eval_environ_str(value): parts = value.split(';') if len(parts) < 2: return value expr = parts[1].lstrip() if not re.match("^((\\w+(\\.\\w+)?|'.*?'|\".*?\")\\s+" '(in|==|!=|not in)\\s+' "(\\w+(\\.\\w+)?|'.*?'|\".*?\")" '(\\s+(or|and)\\s+)?)+$', expr): raise ValueError('bad environment marker: %r' % expr) expr = re.sub(r"(platform\.\w+)", r"\1()", expr) return parts[0] if eval(expr) else '' if isinstance(value, list): new_value = [] for element in value: element = eval_environ_str(element) if element: new_value.append(element) elif isinstance(value, str): new_value = eval_environ_str(value) else: new_value = value return new_value
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_multiline(value) if (section, option) in ENVIRON_OPTIONS: value = eval_environ(value) return value
def set_cfg_value(config, section, option, value): """Set configuration value.""" if isinstance(value, list): value = '\n'.join(value) config[section][option] = value
def cfg_to_args(config): """Compatibility helper to use setup.cfg in setup.py.""" kwargs = {} opts_to_args = { 'metadata': [ ('name', 'name'), ('author', 'author'), ('author-email', 'author_email'), ('maintainer', 'maintainer'), ('maintainer-email', 'maintainer_email'), ('home-page', 'url'), ('summary', 'description'), ('description', 'long_description'), ('download-url', 'download_url'), ('classifier', 'classifiers'), ('platform', 'platforms'), ('license', 'license'), ('keywords', 'keywords'), ], 'files': [ ('packages_root', 'package_dir'), ('packages', 'packages'), ('modules', 'py_modules'), ('scripts', 'scripts'), ('package_data', 'package_data'), ('data_files', 'data_files'), ], } opts_to_args['metadata'].append(('requires-dist', 'install_requires')) if IS_PY2K and not which('3to2'): kwargs['setup_requires'] = ['3to2'] kwargs['zip_safe'] = False for section in opts_to_args: for option, argname in opts_to_args[section]: value = get_cfg_value(config, section, option) if value: kwargs[argname] = value if 'long_description' not in kwargs: kwargs['long_description'] = read_description_file(config) if 'package_dir' in kwargs: kwargs['package_dir'] = {'': kwargs['package_dir']} if 'keywords' in kwargs: kwargs['keywords'] = split_elements(kwargs['keywords']) if 'package_data' in kwargs: kwargs['package_data'] = get_package_data(kwargs['package_data']) if 'data_files' in kwargs: kwargs['data_files'] = get_data_files(kwargs['data_files']) kwargs['version'] = get_version() if not IS_PY2K: kwargs['test_suite'] = 'test' return kwargs
def run_3to2(args=None): """Convert Python files using lib3to2.""" args = BASE_ARGS_3TO2 if args is None else BASE_ARGS_3TO2 + args try: proc = subprocess.Popen(['3to2'] + args, stderr=subprocess.PIPE) except OSError: for path in glob.glob('*.egg'): if os.path.isdir(path) and path not in sys.path: sys.path.append(path) try: from lib3to2.main import main as lib3to2_main except ImportError: raise OSError('3to2 script is unavailable.') else: if lib3to2_main('lib3to2.fixes', args): raise Exception('lib3to2 parsing error') else: # HACK: workaround for 3to2 never returning non-zero # when using the -j option. num_errors = 0 while proc.poll() is None: line = proc.stderr.readline() sys.stderr.write(line) num_errors += line.count(': ParseError: ') if proc.returncode or num_errors: raise Exception('lib3to2 parsing error')
def write_py2k_header(file_list): """Write Python 2 shebang and add encoding cookie if needed.""" if not isinstance(file_list, list): file_list = [file_list] python_re = re.compile(br"^(#!.*\bpython)(.*)([\r\n]+)$") coding_re = re.compile(br"coding[:=]\s*([-\w.]+)") new_line_re = re.compile(br"([\r\n]+)$") version_3 = LooseVersion('3') for file in file_list: if not os.path.getsize(file): continue rewrite_needed = False python_found = False coding_found = False lines = [] f = open(file, 'rb') try: while len(lines) < 2: line = f.readline() match = python_re.match(line) if match: python_found = True version = LooseVersion(match.group(2).decode() or '2') try: version_test = version >= version_3 except TypeError: version_test = True if version_test: line = python_re.sub(br"\g<1>2\g<3>", line) rewrite_needed = True elif coding_re.search(line): coding_found = True lines.append(line) if not coding_found: match = new_line_re.search(lines[0]) newline = match.group(1) if match else b"\n" line = b"# -*- coding: utf-8 -*-" + newline lines.insert(1 if python_found else 0, line) rewrite_needed = True if rewrite_needed: lines += f.readlines() finally: f.close() if rewrite_needed: f = open(file, 'wb') try: f.writelines(lines) finally: f.close()
def which(program): """Identify the location of an executable file.""" if os.path.split(program)[0]: program_path = find_exe(program) if program_path: return program_path else: for path in get_path_list(): program_path = find_exe(os.path.join(path, program)) if program_path: return program_path return None
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 for n, match in enumerate(matches): frompos, topos = (correct_offset + match.offset, correct_offset + match.offset + match.errorlength) if ltext[frompos:topos] != errors[n]: continue repl = match.replacements[0] ltext[frompos:topos] = list(repl) correct_offset += len(repl) - len(errors[n]) return ''.join(ltext)
def get_version(): """Get LanguageTool version.""" version = _get_attrib().get('version') if not version: match = re.search(r"LanguageTool-?.*?(\S+)$", get_directory()) if match: version = match.group(1) return version
def get_languages() -> set: """Get supported languages.""" try: languages = cache['languages'] except KeyError: languages = LanguageTool._get_languages() cache['languages'] = languages return languages
def get_directory(): """Get LanguageTool directory.""" try: language_check_dir = cache['language_check_dir'] except KeyError: def version_key(string): return [int(e) if e.isdigit() else e for e in re.split(r"(\d+)", string)] def get_lt_dir(base_dir): paths = [ path for path in glob.glob(os.path.join(base_dir, 'LanguageTool*')) if os.path.isdir(path) ] return max(paths, key=version_key) if paths else None base_dir = os.path.dirname(sys.argv[0]) language_check_dir = get_lt_dir(base_dir) if not language_check_dir: try: base_dir = os.path.dirname(os.path.abspath(__file__)) except NameError: pass else: language_check_dir = get_lt_dir(base_dir) if not language_check_dir: raise PathError("can't find LanguageTool directory in {!r}" .format(base_dir)) cache['language_check_dir'] = language_check_dir return language_check_dir
def set_directory(path=None): """Set LanguageTool directory.""" old_path = get_directory() terminate_server() cache.clear() if path: cache['language_check_dir'] = path try: get_jar_info() except Error: cache['language_check_dir'] = old_path raise
def check(self, text: str, srctext=None) -> [Match]: """Match text against enabled rules.""" root = self._get_root(self._url, self._encode(text, srctext)) return [Match(e.attrib) for e in root if e.tag == 'error']
def _check_api(self, text: str, srctext=None) -> bytes: """Match text against enabled rules (result in XML format).""" root = self._get_root(self._url, self._encode(text, srctext)) return (b'<?xml version="1.0" encoding="UTF-8"?>\n' + ElementTree.tostring(root) + b"\n")
def correct(self, text: str, srctext=None) -> str: """Automatically apply suggestions to the text.""" return correct(text, self.check(text, srctext))
def parse_java_version(version_text): """Return Java version (major1, major2). >>> parse_java_version('''java version "1.6.0_65" ... Java(TM) SE Runtime Environment (build 1.6.0_65-b14-462-11M4609) ... Java HotSpot(TM) 64-Bit Server VM (build 20.65-b04-462, mixed mode)) ... ''') (1, 6) >>> parse_java_version(''' ... openjdk version "1.8.0_60" ... OpenJDK Runtime Environment (build 1.8.0_60-b27) ... OpenJDK 64-Bit Server VM (build 25.60-b23, mixed mode)) ... ''') (1, 8) """ match = re.search(JAVA_VERSION_REGEX, version_text) if not match: raise SystemExit( 'Could not parse Java version from """{}""".'.format(version_text)) return (int(match.group('major1')), int(match.group('major2')))
def get_newest_possible_languagetool_version(): """Return newest compatible version. >>> version = get_newest_possible_languagetool_version() >>> version in [JAVA_6_COMPATIBLE_VERSION, ... JAVA_7_COMPATIBLE_VERSION, ... LATEST_VERSION] True """ java_path = find_executable('java') if not java_path: # Just ignore this and assume an old version of Java. It might not be # found because of a PATHEXT-related issue # (https://bugs.python.org/issue2200). return JAVA_6_COMPATIBLE_VERSION output = subprocess.check_output([java_path, '-version'], stderr=subprocess.STDOUT, universal_newlines=True) java_version = parse_java_version(output) if java_version >= (1, 8): return LATEST_VERSION elif java_version >= (1, 7): return JAVA_7_COMPATIBLE_VERSION elif java_version >= (1, 6): warn('language-check would be able to use a newer version of ' 'LanguageTool if you had Java 7 or newer installed') return JAVA_6_COMPATIBLE_VERSION else: raise SystemExit( 'You need at least Java 6 to use language-check')
def get_common_prefix(z): """Get common directory in a zip file if any.""" name_list = z.namelist() if name_list and all(n.startswith(name_list[0]) for n in name_list[1:]): return name_list[0] return None
def _process_events(self, events): """Process events from proactor.""" for f, callback, transferred, key, ov in events: try: self._logger.debug('Invoking event callback {}'.format(callback)) value = callback(transferred, key, ov) except OSError: self._logger.warning('Event callback failed', exc_info=sys.exc_info()) else: f.set_result(value)
def asyncClose(fn): """Allow to run async code before application is closed.""" @functools.wraps(fn) def wrapper(*args, **kwargs): f = asyncio.ensure_future(fn(*args, **kwargs)) while not f.done(): QApplication.instance().processEvents() return wrapper
def asyncSlot(*args): """Make a Qt async slot run on asyncio loop.""" def outer_decorator(fn): @Slot(*args) @functools.wraps(fn) def wrapper(*args, **kwargs): asyncio.ensure_future(fn(*args, **kwargs)) return wrapper return outer_decorator
def with_logger(cls): """Class decorator to add a logger to a class.""" attr_name = '_logger' cls_name = cls.__qualname__ module = cls.__module__ if module is not None: cls_name = module + '.' + cls_name else: raise AssertionError setattr(cls, attr_name, logging.getLogger(cls_name)) return cls
def _process_event(self, key, mask): """Selector has delivered us an event.""" self._logger.debug('Processing event with key {} and mask {}'.format(key, mask)) fileobj, (reader, writer) = key.fileobj, key.data if mask & selectors.EVENT_READ and reader is not None: if reader._cancelled: self.remove_reader(fileobj) else: self._logger.debug('Invoking reader callback: {}'.format(reader)) reader._run() if mask & selectors.EVENT_WRITE and writer is not None: if writer._cancelled: self.remove_writer(fileobj) else: self._logger.debug('Invoking writer callback: {}'.format(writer)) writer._run()
def addSources(self, *sources): """Add more ASN.1 MIB source repositories. MibCompiler.compile will invoke each of configured source objects in order of their addition asking each to fetch MIB module specified by name. Args: sources: reader object(s) Returns: reference to itself (can be used for call chaining) """ self._sources.extend(sources) debug.logger & debug.flagCompiler and debug.logger( 'current MIB source(s): %s' % ', '.join([str(x) for x in self._sources])) return self
def addSearchers(self, *searchers): """Add more transformed MIBs repositories. MibCompiler.compile will invoke each of configured searcher objects in order of their addition asking each if already transformed MIB module already exists and is more recent than specified. Args: searchers: searcher object(s) Returns: reference to itself (can be used for call chaining) """ self._searchers.extend(searchers) debug.logger & debug.flagCompiler and debug.logger( 'current compiled MIBs location(s): %s' % ', '.join([str(x) for x in self._searchers])) return self
def addBorrowers(self, *borrowers): """Add more transformed MIBs repositories to borrow MIBs from. Whenever MibCompiler.compile encounters MIB module which neither of the *searchers* can find or fetched ASN.1 MIB module can not be parsed (due to syntax errors), these *borrowers* objects will be invoked in order of their addition asking each if already transformed MIB can be fetched (borrowed). Args: borrowers: borrower object(s) Returns: reference to itself (can be used for call chaining) """ self._borrowers.extend(borrowers) debug.logger & debug.flagCompiler and debug.logger( 'current MIB borrower(s): %s' % ', '.join([str(x) for x in self._borrowers])) return self
def compile(self, *mibnames, **options): """Transform requested and possibly referred MIBs. The *compile* method should be invoked when *MibCompiler* object is operational meaning at least *sources* are specified. Once called with a MIB module name, *compile* will: * fetch ASN.1 MIB module with given name by calling *sources* * make sure no such transformed MIB already exists (with *searchers*) * parse ASN.1 MIB text with *parser* * perform actual MIB transformation into target format with *code generator* * may attempt to borrow pre-transformed MIB through *borrowers* * write transformed MIB through *writer* The above sequence will be performed for each MIB name given in *mibnames* and may be performed for all MIBs referred to from MIBs being processed. Args: mibnames: list of ASN.1 MIBs names options: options that affect the way PySMI components work Returns: A dictionary of MIB module names processed (keys) and *MibStatus* class instances (values) """ processed = {} parsedMibs = {} failedMibs = {} borrowedMibs = {} builtMibs = {} symbolTableMap = {} mibsToParse = [x for x in mibnames] canonicalMibNames = {} while mibsToParse: mibname = mibsToParse.pop(0) if mibname in parsedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already parsed' % mibname) continue if mibname in failedMibs: debug.logger & debug.flagCompiler and debug.logger('MIB %s already failed' % mibname) continue for source in self._sources: debug.logger & debug.flagCompiler and debug.logger('trying source %s' % source) try: fileInfo, fileData = source.getData(mibname) for mibTree in self._parser.parse(fileData): mibInfo, symbolTable = self._symbolgen.genCode( mibTree, symbolTableMap ) symbolTableMap[mibInfo.name] = symbolTable parsedMibs[mibInfo.name] = fileInfo, mibInfo, mibTree if mibname in failedMibs: del failedMibs[mibname] mibsToParse.extend(mibInfo.imported) if fileInfo.name in mibnames: if mibInfo.name not in canonicalMibNames: canonicalMibNames[mibInfo.name] = [] canonicalMibNames[mibInfo.name].append(fileInfo.name) debug.logger & debug.flagCompiler and debug.logger( '%s (%s) read from %s, immediate dependencies: %s' % ( mibInfo.name, mibname, fileInfo.path, ', '.join(mibInfo.imported) or '<none>')) break except error.PySmiReaderFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger('no %s found at %s' % (mibname, source)) continue except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.source = source exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('%serror %s from %s' % ( options.get('ignoreErrors') and 'ignoring ' or 'failing on ', exc, source)) failedMibs[mibname] = exc processed[mibname] = statusFailed.setOptions(error=exc) else: exc = error.PySmiError('MIB source %s not found' % mibname) exc.mibname = mibname debug.logger & debug.flagCompiler and debug.logger('no %s found everywhere' % mibname) if mibname not in failedMibs: failedMibs[mibname] = exc if mibname not in processed: processed[mibname] = statusMissing debug.logger & debug.flagCompiler and debug.logger( 'MIBs analyzed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # See what MIBs need generating # for mibname in tuple(parsedMibs): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('checking if %s requires updating' % mibname) for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del parsedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from code generation' % mibname) del parsedMibs[mibname] processed[mibname] = statusUntouched continue debug.logger & debug.flagCompiler and debug.logger( 'MIBs parsed %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Generate code for parsed MIBs # for mibname in parsedMibs.copy(): fileInfo, mibInfo, mibTree = parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('compiling %s read from %s' % (mibname, fileInfo.path)) platform_info, user_info = self._get_system_info() comments = [ 'ASN.1 source %s' % fileInfo.path, 'Produced by %s-%s at %s' % (packageName, packageVersion, time.asctime()), 'On host %s platform %s version %s by user %s' % (platform_info[1], platform_info[0], platform_info[2], user_info[0]), 'Using Python version %s' % sys.version.split('\n')[0] ] try: mibInfo, mibData = self._codegen.genCode( mibTree, symbolTableMap, comments=comments, dstTemplate=options.get('dstTemplate'), genTexts=options.get('genTexts'), textFilter=options.get('textFilter') ) builtMibs[mibname] = fileInfo, mibInfo, mibData del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( '%s read from %s and compiled by %s' % (mibname, fileInfo.path, self._writer)) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (self._codegen, exc)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del parsedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(parsedMibs), len(failedMibs))) # # Try to borrow pre-compiled MIBs for failed ones # for mibname in failedMibs.copy(): if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger('excluding imported MIB %s from borrowing' % mibname) continue for borrower in self._borrowers: debug.logger & debug.flagCompiler and debug.logger('trying to borrow %s from %s' % (mibname, borrower)) try: fileInfo, fileData = borrower.getData( mibname, genTexts=options.get('genTexts') ) borrowedMibs[mibname] = fileInfo, MibInfo(name=mibname, imported=[]), fileData del failedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger('%s borrowed with %s' % (mibname, borrower)) break except error.PySmiError: debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (borrower, sys.exc_info()[1])) debug.logger & debug.flagCompiler and debug.logger( 'MIBs available for borrowing %s, MIBs failed %s' % (len(borrowedMibs), len(failedMibs))) # # See what MIBs need borrowing # for mibname in borrowedMibs.copy(): debug.logger & debug.flagCompiler and debug.logger('checking if failed MIB %s requires borrowing' % mibname) fileInfo, mibInfo, mibData = borrowedMibs[mibname] for searcher in self._searchers: try: searcher.fileExists(mibname, fileInfo.mtime, rebuild=options.get('rebuild')) except error.PySmiFileNotFoundError: debug.logger & debug.flagCompiler and debug.logger( 'no compiled MIB %s available through %s' % (mibname, searcher)) continue except error.PySmiFileNotModifiedError: debug.logger & debug.flagCompiler and debug.logger( 'will be using existing compiled MIB %s found by %s' % (mibname, searcher)) del borrowedMibs[mibname] processed[mibname] = statusUntouched break except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.searcher = searcher exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error from %s: %s' % (searcher, exc)) continue else: debug.logger & debug.flagCompiler and debug.logger( 'no suitable compiled MIB %s found anywhere' % mibname) if options.get('noDeps') and mibname not in canonicalMibNames: debug.logger & debug.flagCompiler and debug.logger( 'excluding imported MIB %s from borrowing' % mibname) processed[mibname] = statusUntouched else: debug.logger & debug.flagCompiler and debug.logger('will borrow MIB %s' % mibname) builtMibs[mibname] = borrowedMibs[mibname] processed[mibname] = statusBorrowed.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name ) del borrowedMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs built %s, MIBs failed %s' % (len(builtMibs), len(failedMibs))) # # We could attempt to ignore missing/failed MIBs # if failedMibs and not options.get('ignoreErrors'): debug.logger & debug.flagCompiler and debug.logger('failing with problem MIBs %s' % ', '.join(failedMibs)) for mibname in builtMibs: processed[mibname] = statusUnprocessed return processed debug.logger & debug.flagCompiler and debug.logger( 'proceeding with built MIBs %s, failed MIBs %s' % (', '.join(builtMibs), ', '.join(failedMibs))) # # Store compiled MIBs # for mibname in builtMibs.copy(): fileInfo, mibInfo, mibData = builtMibs[mibname] try: if options.get('writeMibs', True): self._writer.putData( mibname, mibData, dryRun=options.get('dryRun') ) debug.logger & debug.flagCompiler and debug.logger('%s stored by %s' % (mibname, self._writer)) del builtMibs[mibname] if mibname not in processed: processed[mibname] = statusCompiled.setOptions( path=fileInfo.path, file=fileInfo.file, alias=fileInfo.name, oid=mibInfo.oid, oids=mibInfo.oids, identity=mibInfo.identity, revision=mibInfo.revision, enterprise=mibInfo.enterprise, compliance=mibInfo.compliance, ) except error.PySmiError: exc_class, exc, tb = sys.exc_info() exc.handler = self._codegen exc.mibname = mibname exc.msg += ' at MIB %s' % mibname debug.logger & debug.flagCompiler and debug.logger('error %s from %s' % (exc, self._writer)) processed[mibname] = statusFailed.setOptions(error=exc) failedMibs[mibname] = exc del builtMibs[mibname] debug.logger & debug.flagCompiler and debug.logger( 'MIBs modified: %s' % ', '.join([x for x in processed if processed[x] in ('compiled', 'borrowed')])) return processed
def t_UPPERCASE_IDENTIFIER(self, t): r'[A-Z][-a-zA-z0-9]*' if t.value in self.forbidden_words: raise error.PySmiLexerError("%s is forbidden" % t.value, lineno=t.lineno) if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) t.type = self.reserved.get(t.value, 'UPPERCASE_IDENTIFIER') return t
def t_LOWERCASE_IDENTIFIER(self, t): r'[0-9]*[a-z][-a-zA-z0-9]*' if t.value[-1] == '-': raise error.PySmiLexerError("Identifier should not end with '-': %s" % t.value, lineno=t.lineno) return t
def t_NUMBER(self, t): r'-?[0-9]+' t.value = int(t.value) neg = 0 if t.value < 0: neg = 1 val = abs(t.value) if val <= UNSIGNED32_MAX: if neg: t.type = 'NEGATIVENUMBER' elif val <= UNSIGNED64_MAX: if neg: t.type = 'NEGATIVENUMBER64' else: t.type = 'NUMBER64' else: raise error.PySmiLexerError("Number %s is too big" % t.value, lineno=t.lineno) return t
def t_BIN_STRING(self, t): r'\'[01]*\'[bB]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 8: value = value[1:] # XXX raise in strict mode # if len(value) % 8: # raise error.PySmiLexerError("Number of 0s and 1s have to divide by 8 in binary string %s" % t.value, lineno=t.lineno) return t
def t_HEX_STRING(self, t): r'\'[0-9a-fA-F]*\'[hH]' value = t.value[1:-2] while value and value[0] == '0' and len(value) % 2: value = value[1:] # XXX raise in strict mode # if len(value) % 2: # raise error.PySmiLexerError("Number of symbols have to be even in hex string %s" % t.value, lineno=t.lineno) return t
def t_QUOTED_STRING(self, t): r'\"[^\"]*\"' t.lexer.lineno += len(re.findall(r'\r\n|\n|\r', t.value)) return t
def p_modules(self, p): """modules : modules module | module""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_importPart(self, p): """importPart : imports | empty""" # libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1! if p[1]: importDict = {} for imp in p[1]: # don't do just dict() because moduleNames may be repeated fromModule, symbols = imp if fromModule in importDict: importDict[fromModule] += symbols else: importDict[fromModule] = symbols p[0] = importDict
def p_imports(self, p): """imports : imports import | import""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_importIdentifiers(self, p): """importIdentifiers : importIdentifiers ',' importIdentifier | importIdentifier""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_declarations(self, p): """declarations : declarations declaration | declaration""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_typeDeclarationRHS(self, p): """typeDeclarationRHS : Syntax | TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax | choiceClause""" if p[1]: if p[1] == 'TEXTUAL-CONVENTION': p[0] = ('typeDeclarationRHS', p[2], # display p[4], # status (p[5], p[6]), # description p[7], # reference p[9]) # syntax else: p[0] = ('typeDeclarationRHS', p[1])
def p_sequenceItems(self, p): """sequenceItems : sequenceItems ',' sequenceItem | sequenceItem""" # libsmi: TODO: might this list be emtpy? n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_Syntax(self, p): """Syntax : ObjectSyntax | BITS '{' NamedBits '}'""" # libsmi: TODO: standalone `BITS' ok? seen in RMON2-MIB # libsmi: -> no, it's only allowed in a SEQUENCE {...} n = len(p) if n == 2: p[0] = p[1] elif n == 5: p[0] = (p[1], p[3])
def p_NamedBits(self, p): """NamedBits : NamedBits ',' NamedBit | NamedBit""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_objectIdentityClause(self, p): """objectIdentityClause : LOWERCASE_IDENTIFIER OBJECT_IDENTITY STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectIdentityClause', p[1], # id # p[2], # OBJECT_IDENTITY p[4], # status (p[5], p[6]), # description p[7], # reference p[10])
def p_objectTypeClause(self, p): """objectTypeClause : LOWERCASE_IDENTIFIER OBJECT_TYPE SYNTAX Syntax UnitsPart MaxOrPIBAccessPart STATUS Status descriptionClause ReferPart IndexPart MibIndex DefValPart COLON_COLON_EQUAL '{' ObjectName '}'""" p[0] = ('objectTypeClause', p[1], # id # p[2], # OBJECT_TYPE p[4], # syntax p[5], # UnitsPart p[6], # MaxOrPIBAccessPart p[8], # status p[9], # descriptionClause p[10], # reference p[11], # augmentions p[12], # index p[13], # DefValPart p[16])
def p_VarTypes(self, p): """VarTypes : VarTypes ',' VarType | VarType""" n = len(p) if n == 4: p[0] = ('VarTypes', p[1][1] + [p[3]]) elif n == 2: p[0] = ('VarTypes', [p[1]])
def p_moduleIdentityClause(self, p): """moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleIdentityClause', p[1], # id # p[2], # MODULE_IDENTITY # XXX p[3], # SubjectCategoriesPart (p[4], p[5]), # last updated (p[6], p[7]), # organization (p[8], p[9]), # contact info (p[10], p[11]), # description p[12], # RevisionPart p[15])
def p_ObjectSyntax(self, p): """ObjectSyntax : SimpleSyntax | conceptualTable | row | entryType | ApplicationSyntax | typeTag SimpleSyntax""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[2]
def p_SimpleSyntax(self, p): """SimpleSyntax : INTEGER | INTEGER integerSubType | INTEGER enumSpec | INTEGER32 | INTEGER32 integerSubType | UPPERCASE_IDENTIFIER enumSpec | UPPERCASE_IDENTIFIER integerSubType | OCTET STRING | OCTET STRING octetStringSubType | UPPERCASE_IDENTIFIER octetStringSubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 2: p[0] = ('SimpleSyntax', p[1]) elif n == 3: if p[1] == 'OCTET': p[0] = ('SimpleSyntax', p[1] + ' ' + p[2]) else: p[0] = ('SimpleSyntax', p[1], p[2]) elif n == 4: p[0] = ('SimpleSyntax', p[1] + ' ' + p[2], p[3])
def p_valueofSimpleSyntax(self, p): """valueofSimpleSyntax : NUMBER | NEGATIVENUMBER | NUMBER64 | NEGATIVENUMBER64 | HEX_STRING | BIN_STRING | LOWERCASE_IDENTIFIER | QUOTED_STRING | '{' objectIdentifier_defval '}'""" # libsmi for objectIdentifier_defval: # This is only for some MIBs with invalid numerical # OID notation for DEFVALs. We DO NOT parse them # correctly. We just don't want to produce a # parser error. n = len(p) if n == 2: p[0] = p[1] elif n == 4: # XXX pass
def p_sequenceSimpleSyntax(self, p): """sequenceSimpleSyntax : INTEGER anySubType | INTEGER32 anySubType | OCTET STRING anySubType | OBJECT IDENTIFIER anySubType""" n = len(p) if n == 3: p[0] = p[1] # XXX not supporting subtypes here elif n == 4: p[0] = p[1] + ' ' + p[2]
def p_ApplicationSyntax(self, p): """ApplicationSyntax : IPADDRESS anySubType | COUNTER32 | COUNTER32 integerSubType | GAUGE32 | GAUGE32 integerSubType | UNSIGNED32 | UNSIGNED32 integerSubType | TIMETICKS anySubType | OPAQUE | OPAQUE octetStringSubType | COUNTER64 | COUNTER64 integerSubType""" # COUNTER32 and COUNTER64 was with anySubType in libsmi n = len(p) if n == 2: p[0] = ('ApplicationSyntax', p[1]) elif n == 3: p[0] = ('ApplicationSyntax', p[1], p[2])
def p_sequenceApplicationSyntax(self, p): """sequenceApplicationSyntax : IPADDRESS anySubType | COUNTER32 anySubType | GAUGE32 anySubType | UNSIGNED32 anySubType | TIMETICKS anySubType | OPAQUE | COUNTER64 anySubType""" n = len(p) if n == 2: p[0] = p[1] elif n == 3: p[0] = p[1]
def p_ranges(self, p): """ranges : ranges '|' range | range""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_range(self, p): """range : value DOT_DOT value | value""" n = len(p) if n == 2: p[0] = (p[1],) elif n == 4: p[0] = (p[1], p[3])
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_IndexTypes(self, p): """IndexTypes : IndexTypes ',' IndexType | IndexType""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]]
def p_IndexType(self, p): """IndexType : IMPLIED Index | Index""" n = len(p) if n == 2: p[0] = (0, p[1]) elif n == 3: p[0] = (1, p[2])
def p_Value(self, p): """Value : valueofObjectSyntax | '{' BitsValue '}'""" n = len(p) if n == 2: p[0] = p[1] elif n == 4: p[0] = p[2]
def p_BitNames(self, p): """BitNames : BitNames ',' LOWERCASE_IDENTIFIER | LOWERCASE_IDENTIFIER""" n = len(p) if n == 4: p[0] = ('BitNames', p[1][1] + [p[3]]) elif n == 2: p[0] = ('BitNames', [p[1]])
def p_Revisions(self, p): """Revisions : Revisions Revision | Revision""" n = len(p) if n == 3: p[0] = ('Revisions', p[1][1] + [p[2]]) elif n == 2: p[0] = ('Revisions', [p[1]])
def p_Objects(self, p): """Objects : Objects ',' Object | Object""" n = len(p) if n == 4: p[0] = ('Objects', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Objects', [p[1]])
def p_Notifications(self, p): """Notifications : Notifications ',' Notification | Notification""" n = len(p) if n == 4: p[0] = ('Notifications', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Notifications', [p[1]])
def p_subidentifiers(self, p): """subidentifiers : subidentifiers subidentifier | subidentifier""" n = len(p) if n == 3: p[0] = p[1] + [p[2]] elif n == 2: p[0] = [p[1]]
def p_subidentifier(self, p): """subidentifier : fuzzy_lowercase_identifier | NUMBER | LOWERCASE_IDENTIFIER '(' NUMBER ')'""" n = len(p) if n == 2: p[0] = p[1] elif n == 5: # NOTE: we are not creating new symbol p[1] because formally # it is not defined in *this* MIB p[0] = (p[1], p[3])
def p_subidentifiers_defval(self, p): """subidentifiers_defval : subidentifiers_defval subidentifier_defval | subidentifier_defval""" n = len(p) if n == 3: p[0] = ('subidentifiers_defval', p[1][1] + [p[2]]) elif n == 2: p[0] = ('subidentifiers_defval', [p[1]])
def p_subidentifier_defval(self, p): """subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER""" n = len(p) if n == 2: p[0] = ('subidentifier_defval', p[1]) elif n == 5: p[0] = ('subidentifier_defval', p[1], p[3])
def p_objectGroupClause(self, p): """objectGroupClause : LOWERCASE_IDENTIFIER OBJECT_GROUP ObjectGroupObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('objectGroupClause', p[1], # id p[3], # objects p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
def p_notificationGroupClause(self, p): """notificationGroupClause : LOWERCASE_IDENTIFIER NOTIFICATION_GROUP NotificationsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('notificationGroupClause', p[1], # id p[3], # notifications p[5], # status (p[6], p[7]), # description p[8], # reference p[11])
def p_moduleComplianceClause(self, p): """moduleComplianceClause : LOWERCASE_IDENTIFIER MODULE_COMPLIANCE STATUS Status DESCRIPTION Text ReferPart ComplianceModulePart COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('moduleComplianceClause', p[1], # id # p[2], # MODULE_COMPLIANCE p[4], # status (p[5], p[6]), # description p[7], # reference p[8], # ComplianceModules p[11])
def p_ComplianceModules(self, p): """ComplianceModules : ComplianceModules ComplianceModule | ComplianceModule""" n = len(p) if n == 3: p[0] = ('ComplianceModules', p[1][1] + [p[2]]) elif n == 2: p[0] = ('ComplianceModules', [p[1]])
def p_ComplianceModule(self, p): """ComplianceModule : MODULE ComplianceModuleName MandatoryPart CompliancePart""" objects = p[3] and p[3][1] or [] objects += p[4] and p[4][1] or [] p[0] = (p[2], # ModuleName objects)
def p_MandatoryGroups(self, p): """MandatoryGroups : MandatoryGroups ',' MandatoryGroup | MandatoryGroup""" n = len(p) if n == 4: p[0] = ('MandatoryGroups', p[1][1] + [p[3]]) elif n == 2: p[0] = ('MandatoryGroups', [p[1]])
def p_Compliances(self, p): """Compliances : Compliances Compliance | Compliance""" n = len(p) if n == 3: p[0] = p[1] and p[2] and ('Compliances', p[1][1] + [p[2]]) or p[1] elif n == 2: p[0] = p[1] and ('Compliances', [p[1]]) or None
def p_agentCapabilitiesClause(self, p): """agentCapabilitiesClause : LOWERCASE_IDENTIFIER AGENT_CAPABILITIES PRODUCT_RELEASE Text STATUS Status DESCRIPTION Text ReferPart ModulePart_Capabilities COLON_COLON_EQUAL '{' objectIdentifier '}'""" p[0] = ('agentCapabilitiesClause', p[1], # id # p[2], # AGENT_CAPABILITIES (p[3], p[4]), # product release p[6], # status (p[7], p[8]), # description p[9], # reference # p[10], # module capabilities p[13])
def p_Cells(self, p): """Cells : Cells ',' Cell | Cell""" n = len(p) if n == 4: p[0] = ('Cells', p[1][1] + [p[3]]) elif n == 2: p[0] = ('Cells', [p[1]])
def p_typeSMIv1(self, p): """typeSMIv1 : INTEGER | OCTET STRING | IPADDRESS | NETWORKADDRESS""" n = len(p) indextype = n == 3 and p[1] + ' ' + p[2] or p[1] p[0] = indextype
def p_enumItems(self, p): """enumItems : enumItems ',' enumItem | enumItem | enumItems enumItem | enumItems ','""" n = len(p) if n == 4: p[0] = p[1] + [p[3]] elif n == 2: p[0] = [p[1]] elif n == 3: # typo case if p[2] == ',': p[0] = p[1] else: p[0] = p[1] + [p[2]]
def p_notificationTypeClause(self, p): """notificationTypeClause : fuzzy_lowercase_identifier NOTIFICATION_TYPE NotificationObjectsPart STATUS Status DESCRIPTION Text ReferPart COLON_COLON_EQUAL '{' NotificationName '}'""" # some MIBs have uppercase and/or lowercase id p[0] = ('notificationTypeClause', p[1], # id # p[2], # NOTIFICATION_TYPE p[3], # NotificationObjectsPart p[5], # status (p[6], p[7]), # description p[8], # Reference p[11])
def p_trapTypeClause(self, p): """trapTypeClause : fuzzy_lowercase_identifier TRAP_TYPE EnterprisePart VarPart DescrPart ReferPart COLON_COLON_EQUAL NUMBER""" # libsmi: TODO: range of number? p[0] = ('trapTypeClause', p[1], # fuzzy_lowercase_identifier # p[2], # TRAP_TYPE p[3], # EnterprisePart (objectIdentifier) p[4], # VarPart p[5], # description p[6], # reference p[8])
def p_EnterprisePart(self, p): """EnterprisePart : ENTERPRISE objectIdentifier | ENTERPRISE '{' objectIdentifier '}'""" n = len(p) if n == 3: p[0] = p[2] elif n == 5: # common mistake case p[0] = p[3]
def p_CreationPart(self, p): """CreationPart : CREATION_REQUIRES '{' Cells '}' | CREATION_REQUIRES '{' '}' | empty""" n = len(p) if n == 5: p[0] = (p[1], p[3])
def AIC(N, rho, k): r"""Akaike Information Criterion :param rho: rho at order k :param N: sample size :param k: AR order. If k is the AR order and N the size of the sample, then Akaike criterion is .. math:: AIC(k) = \log(\rho_k) + 2\frac{k+1}{N} :: AIC(64, [0.5,0.3,0.2], [1,2,3]) :validation: double checked versus octave. """ from numpy import log, array #k+1 #todo check convention. agrees with octave res = N * log(array(rho)) + 2.* (array(k)+1) return res
def AICc(N, rho, k, norm=True): r"""corrected Akaike information criterion .. math:: AICc(k) = log(\rho_k) + 2 \frac{k+1}{N-k-2} :validation: double checked versus octave. """ from numpy import log, array p = k #todo check convention. agrees with octave res = log(rho) + 2. * (p+1) / (N-p-2) return res
def KIC(N, rho, k): r"""Kullback information criterion .. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N} :validation: double checked versus octave. """ from numpy import log, array res = log(rho) + 3. * (k+1.) /float(N) return res
def AKICc(N, rho, k): r"""approximate corrected Kullback information .. math:: AKICc(k) = log(rho_k) + \frac{p}{N*(N-k)} + (3-\frac{k+2}{N})*\frac{k+1}{N-k-2} """ from numpy import log, array p = k res = log(rho) + p/N/(N-p) + (3.-(p+2.)/N) * (p+1.) / (N-p-2.) return res
def FPE(N,rho, k=None): r"""Final prediction error criterion .. math:: FPE(k) = \frac{N + k + 1}{N - k - 1} \rho_k :validation: double checked versus octave. """ #k #todo check convention. agrees with octave fpe = rho * (N + k + 1.) / (N- k -1) return fpe
def MDL(N, rho, k): r"""Minimum Description Length .. math:: MDL(k) = N log \rho_k + p \log N :validation: results """ from numpy import log #p = arange(1, len(rho)+1) mdl = N* log(rho) + k * log(N) return mdl
def CAT(N, rho, k): r"""Criterion Autoregressive Transfer Function : .. math:: CAT(k) = \frac{1}{N} \sum_{i=1}^k \frac{1}{\rho_i} - \frac{\rho_i}{\rho_k} .. todo:: validation """ from numpy import zeros, arange cat = zeros(len(rho)) for p in arange(1, len(rho)+1): rho_p = float(N)/(N-p)*rho[p-1] s = 0 for j in range(1, p+1): rho_j = float(N)/(N-j)*rho[j-1] s = s + 1./rho_j #print(s, s/float(N), 1./rho_p) cat[p-1] = s/float(N) - 1./rho_p return cat